-
-
Notifications
You must be signed in to change notification settings - Fork 253
/
core.ts
504 lines (437 loc) · 14.7 KB
/
core.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
import type { IncomingMessage, ServerResponse } from "http";
import { parse, serialize, type CookieSerializeOptions } from "cookie";
import {
defaults as ironDefaults,
seal as ironSeal,
unseal as ironUnseal,
} from "iron-webcrypto";
type PasswordsMap = Record<string, string>;
type Password = PasswordsMap | string;
type RequestType = IncomingMessage | Request;
type ResponseType = Response | ServerResponse;
/**
* {@link https://wicg.github.io/cookie-store/#dictdef-cookielistitem CookieListItem}
* as specified by W3C.
*/
interface CookieListItem
extends Pick<
CookieSerializeOptions,
"domain" | "path" | "sameSite" | "secure"
> {
/** A string with the name of a cookie. */
name: string;
/** A string containing the value of the cookie. */
value: string;
/** A number of milliseconds or Date interface containing the expires of the cookie. */
expires?: CookieSerializeOptions["expires"] | number;
}
/**
* Superset of {@link CookieListItem} extending it with
* the `httpOnly`, `maxAge` and `priority` properties.
*/
type ResponseCookie = CookieListItem &
Pick<CookieSerializeOptions, "httpOnly" | "maxAge" | "priority">;
/**
* The high-level type definition of the .get() and .set() methods
* of { cookies() } from "next/headers"
*/
export interface CookieStore {
get: (name: string) => { name: string; value: string } | undefined;
set: {
(name: string, value: string, cookie?: Partial<ResponseCookie>): void;
(options: ResponseCookie): void;
};
}
/**
* Set-Cookie Attributes do not include `encode`. We omit this from our `cookieOptions` type.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
* @see https://developer.chrome.com/docs/devtools/application/cookies/
*/
type CookieOptions = Omit<CookieSerializeOptions, "encode">;
export interface SessionOptions {
/**
* The cookie name that will be used inside the browser. Make sure it's unique
* given your application.
*
* @example 'vercel-session'
*/
cookieName: string;
/**
* The password(s) that will be used to encrypt the cookie. Can either be a string
* or an object.
*
* When you provide multiple passwords then all of them will be used to decrypt
* the cookie. But only the most recent (`= highest key`, `2` in the example)
* password will be used to encrypt the cookie. This allows password rotation.
*
* @example { 1: 'password-1', 2: 'password-2' }
*/
password: Password;
/**
* The time (in seconds) that the session will be valid for. Also sets the
* `max-age` attribute of the cookie automatically (`= ttl - 60s`, so that the
* cookie always expire before the session).
*
* `ttl = 0` means no expiration.
*
* @default 1209600
*/
ttl?: number;
/**
* The options that will be passed to the cookie library.
*
* If you want to use "session cookies" (cookies that are deleted when the browser
* is closed) then you need to pass `cookieOptions: { maxAge: undefined }`
*
* @see https://github.com/jshttp/cookie#options-1
*/
cookieOptions?: CookieOptions;
}
export type IronSession<T> = T & {
/**
* Encrypts the session data and sets the cookie.
*/
readonly save: () => Promise<void>;
/**
* Destroys the session data and removes the cookie.
*/
readonly destroy: () => void;
/**
* Update the session configuration. You still need to call save() to send the new cookie.
*/
readonly updateConfig: (newSessionOptions: SessionOptions) => void;
};
// default time allowed to check for iron seal validity when ttl passed
// see https://hapi.dev/module/iron/api/?v=7.0.1#options
const timestampSkewSec = 60;
const fourteenDaysInSeconds = 14 * 24 * 3600;
// We store a token major version to handle data format changes so that the cookies
// can be kept alive between upgrades, no need to disconnect everyone.
const currentMajorVersion = 2;
const versionDelimiter = "~";
const defaultOptions: Required<Pick<SessionOptions, "ttl" | "cookieOptions">> =
{
ttl: fourteenDaysInSeconds,
cookieOptions: { httpOnly: true, secure: true, sameSite: "lax", path: "/" },
};
function normalizeStringPasswordToMap(password: Password): PasswordsMap {
return typeof password === "string" ? { 1: password } : password;
}
function parseSeal(seal: string): {
sealWithoutVersion: string;
tokenVersion: number | null;
} {
const [sealWithoutVersion, tokenVersionAsString] =
seal.split(versionDelimiter);
const tokenVersion =
tokenVersionAsString == null ? null : parseInt(tokenVersionAsString, 10);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return { sealWithoutVersion: sealWithoutVersion!, tokenVersion };
}
function computeCookieMaxAge(ttl: number): number {
if (ttl === 0) {
// ttl = 0 means no expiration
// but in reality cookies have to expire (can't have no max-age)
// 2147483647 is the max value for max-age in cookies
// see https://stackoverflow.com/a/11685301/147079
return 2147483647;
}
// The next line makes sure browser will expire cookies before seals are considered expired by the server.
// It also allows for clock difference of 60 seconds between server and clients.
return ttl - timestampSkewSec;
}
function getCookie(req: RequestType, cookieName: string): string {
return (
parse(
("headers" in req && typeof req.headers.get === "function"
? req.headers.get("cookie")
: (req as IncomingMessage).headers.cookie) ?? "",
)[cookieName] ?? ""
);
}
function getServerActionCookie(
cookieName: string,
cookieHandler: CookieStore,
): string {
const cookieObject = cookieHandler.get(cookieName);
const cookie = cookieObject?.value;
if (typeof cookie === "string") {
return cookie;
}
return "";
}
function setCookie(res: ResponseType, cookieValue: string): void {
if ("headers" in res && typeof res.headers.append === "function") {
res.headers.append("set-cookie", cookieValue);
return;
}
let existingSetCookie = (res as ServerResponse).getHeader("set-cookie") ?? [];
if (!Array.isArray(existingSetCookie)) {
existingSetCookie = [existingSetCookie.toString()];
}
(res as ServerResponse).setHeader("set-cookie", [
...existingSetCookie,
cookieValue,
]);
}
export function createSealData(_crypto: Crypto) {
return async function sealData(
data: unknown,
{
password,
ttl = fourteenDaysInSeconds,
}: { password: Password; ttl?: number },
): Promise<string> {
const passwordsMap = normalizeStringPasswordToMap(password);
const mostRecentPasswordId = Math.max(
...Object.keys(passwordsMap).map(Number),
);
const passwordForSeal = {
id: mostRecentPasswordId.toString(),
secret: passwordsMap[mostRecentPasswordId]!,
};
const seal = await ironSeal(_crypto, data, passwordForSeal, {
...ironDefaults,
ttl: ttl * 1000,
});
return `${seal}${versionDelimiter}${currentMajorVersion}`;
};
}
export function createUnsealData(_crypto: Crypto) {
return async function unsealData<T>(
seal: string,
{
password,
ttl = fourteenDaysInSeconds,
}: { password: Password; ttl?: number },
): Promise<T> {
const passwordsMap = normalizeStringPasswordToMap(password);
const { sealWithoutVersion, tokenVersion } = parseSeal(seal);
try {
const data =
(await ironUnseal(_crypto, sealWithoutVersion, passwordsMap, {
...ironDefaults,
ttl: ttl * 1000,
})) ?? {};
if (tokenVersion === 2) {
return data as T;
}
// @ts-expect-error `persistent` does not exist on newer tokens
return { ...data.persistent } as T;
} catch (error) {
if (
error instanceof Error &&
/^(Expired seal|Bad hmac value|Cannot find password|Incorrect number of sealed components)/.test(
error.message,
)
) {
// if seal expired or
// if seal is not valid (encrypted using a different password, when passwords are badly rotated) or
// if we can't find back the password in the seal
// then we just start a new session over
return {} as T;
}
throw error;
}
};
}
function getSessionConfig(
sessionOptions: SessionOptions,
): Required<SessionOptions> {
const options = {
...defaultOptions,
...sessionOptions,
cookieOptions: {
...defaultOptions.cookieOptions,
...(sessionOptions.cookieOptions || {}),
},
};
if (
sessionOptions.cookieOptions &&
"maxAge" in sessionOptions.cookieOptions
) {
if (sessionOptions.cookieOptions.maxAge === undefined) {
// session cookies, do not set maxAge, consider token as infinite
options.ttl = 0;
}
} else {
options.cookieOptions.maxAge = computeCookieMaxAge(options.ttl);
}
return options;
}
const badUsageMessage =
"iron-session: Bad usage: use getIronSession(req, res, options) or getIronSession(cookieStore, options).";
export function createGetIronSession(
sealData: ReturnType<typeof createSealData>,
unsealData: ReturnType<typeof createUnsealData>,
) {
return getIronSession;
async function getIronSession<T extends object>(
cookies: CookieStore,
sessionOptions: SessionOptions,
): Promise<IronSession<T>>;
async function getIronSession<T extends object>(
req: RequestType,
res: ResponseType,
sessionOptions: SessionOptions,
): Promise<IronSession<T>>;
async function getIronSession<T extends object>(
reqOrCookieStore: RequestType | CookieStore,
resOrsessionOptions: ResponseType | SessionOptions,
sessionOptions?: SessionOptions,
): Promise<IronSession<T>> {
if (!reqOrCookieStore) {
throw new Error(badUsageMessage);
}
if (!resOrsessionOptions) {
throw new Error(badUsageMessage);
}
if (!sessionOptions) {
return getIronSessionFromCookieStore<T>(
reqOrCookieStore as CookieStore,
resOrsessionOptions as SessionOptions,
sealData,
unsealData,
);
}
const req = reqOrCookieStore as RequestType;
const res = resOrsessionOptions as ResponseType;
if (!sessionOptions) {
throw new Error(badUsageMessage);
}
if (!sessionOptions.cookieName) {
throw new Error("iron-session: Bad usage. Missing cookie name.");
}
if (!sessionOptions.password) {
throw new Error("iron-session: Bad usage. Missing password.");
}
const passwordsMap = normalizeStringPasswordToMap(sessionOptions.password);
if (Object.values(passwordsMap).some((password) => password.length < 32)) {
throw new Error(
"iron-session: Bad usage. Password must be at least 32 characters long.",
);
}
let sessionConfig = getSessionConfig(sessionOptions);
const sealFromCookies = getCookie(req, sessionConfig.cookieName);
const session = sealFromCookies
? await unsealData<T>(sealFromCookies, {
password: passwordsMap,
ttl: sessionConfig.ttl,
})
: ({} as T);
Object.defineProperties(session, {
updateConfig: {
value: function updateConfig(newSessionOptions: SessionOptions) {
sessionConfig = getSessionConfig(newSessionOptions);
},
},
save: {
value: async function save() {
if ("headersSent" in res && res.headersSent) {
throw new Error(
"iron-session: Cannot set session cookie: session.save() was called after headers were sent. Make sure to call it before any res.send() or res.end()",
);
}
const seal = await sealData(session, {
password: passwordsMap,
ttl: sessionConfig.ttl,
});
const cookieValue = serialize(
sessionConfig.cookieName,
seal,
sessionConfig.cookieOptions,
);
if (cookieValue.length > 4096) {
throw new Error(
`iron-session: Cookie length is too big (${cookieValue.length} bytes), browsers will refuse it. Try to remove some data.`,
);
}
setCookie(res, cookieValue);
},
},
destroy: {
value: function destroy() {
Object.keys(session).forEach((key) => {
delete (session as Record<string, unknown>)[key];
});
const cookieValue = serialize(sessionConfig.cookieName, "", {
...sessionConfig.cookieOptions,
maxAge: 0,
});
setCookie(res, cookieValue);
},
},
});
return session as IronSession<T>;
}
}
async function getIronSessionFromCookieStore<T extends object>(
cookieStore: CookieStore,
sessionOptions: SessionOptions,
sealData: ReturnType<typeof createSealData>,
unsealData: ReturnType<typeof createUnsealData>,
): Promise<IronSession<T>> {
if (!sessionOptions.cookieName) {
throw new Error("iron-session: Bad usage. Missing cookie name.");
}
if (!sessionOptions.password) {
throw new Error("iron-session: Bad usage. Missing password.");
}
const passwordsMap = normalizeStringPasswordToMap(sessionOptions.password);
if (Object.values(passwordsMap).some((password) => password.length < 32)) {
throw new Error(
"iron-session: Bad usage. Password must be at least 32 characters long.",
);
}
let sessionConfig = getSessionConfig(sessionOptions);
const sealFromCookies = getServerActionCookie(
sessionConfig.cookieName,
cookieStore,
);
const session = sealFromCookies
? await unsealData<T>(sealFromCookies, {
password: passwordsMap,
ttl: sessionConfig.ttl,
})
: ({} as T);
Object.defineProperties(session, {
updateConfig: {
value: function updateConfig(newSessionOptions: SessionOptions) {
sessionConfig = getSessionConfig(newSessionOptions);
},
},
save: {
value: async function save() {
const seal = await sealData(session, {
password: passwordsMap,
ttl: sessionConfig.ttl,
});
const cookieLength =
sessionConfig.cookieName.length +
seal.length +
JSON.stringify(sessionConfig.cookieOptions).length;
if (cookieLength > 4096) {
throw new Error(
`iron-session: Cookie length is too big (${cookieLength} bytes), browsers will refuse it. Try to remove some data.`,
);
}
cookieStore.set(
sessionConfig.cookieName,
seal,
sessionConfig.cookieOptions,
);
},
},
destroy: {
value: function destroy() {
Object.keys(session).forEach((key) => {
delete (session as Record<string, unknown>)[key];
});
const cookieOptions = { ...sessionConfig.cookieOptions, maxAge: 0 };
cookieStore.set(sessionConfig.cookieName, "", cookieOptions);
},
},
});
return session as IronSession<T>;
}