iron-session 6.1.3 → 6.2.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -8
- package/dist/index.d.ts +25 -8
- package/dist/index.js +171 -115
- package/dist/index.js.map +1 -7
- package/dist/index.mjs +151 -103
- package/dist/index.mjs.map +1 -7
- package/edge/dist/index.d.ts +19 -0
- package/edge/dist/index.js +244 -0
- package/edge/dist/index.js.map +1 -0
- package/edge/dist/index.mjs +209 -0
- package/edge/dist/index.mjs.map +1 -0
- package/edge/index.d.ts +19 -0
- package/edge/index.js +244 -0
- package/edge/index.js.map +1 -0
- package/edge/index.mjs +209 -0
- package/edge/index.mjs.map +1 -0
- package/edge/index.ts +29 -0
- package/edge/tsconfig.json +8 -0
- package/express/dist/index.js +18 -17
- package/express/dist/index.js.map +1 -7
- package/express/dist/index.mjs +6 -2
- package/express/dist/index.mjs.map +1 -7
- package/express/index.js +18 -17
- package/express/index.js.map +1 -7
- package/express/index.mjs +6 -2
- package/express/index.mjs.map +1 -7
- package/next/dist/index.js +28 -19
- package/next/dist/index.js.map +1 -7
- package/next/dist/index.mjs +16 -4
- package/next/dist/index.mjs.map +1 -7
- package/next/index.js +28 -19
- package/next/index.js.map +1 -7
- package/next/index.mjs +16 -4
- package/next/index.mjs.map +1 -7
- package/package.json +36 -24
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// src/
|
|
2
|
-
import Iron from "
|
|
1
|
+
// src/core.ts
|
|
2
|
+
import * as Iron from "iron-webcrypto";
|
|
3
3
|
import cookie from "cookie";
|
|
4
4
|
var timestampSkewSec = 60;
|
|
5
5
|
var fourteenDaysInSeconds = 15 * 24 * 3600;
|
|
@@ -14,75 +14,101 @@ var defaultOptions = {
|
|
|
14
14
|
path: "/"
|
|
15
15
|
}
|
|
16
16
|
};
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
if (password.length < 32) {
|
|
24
|
-
throw new Error(`iron-session: Bad usage. Password must be at least 32 characters long.`);
|
|
17
|
+
function createGetIronSession(_crypto2, unsealData2, sealData2) {
|
|
18
|
+
return async (req, res, userSessionOptions) => {
|
|
19
|
+
if (!req || !res || !userSessionOptions || !userSessionOptions.cookieName || !userSessionOptions.password) {
|
|
20
|
+
throw new Error(
|
|
21
|
+
`iron-session: Bad usage. Minimum usage is const session = await getIronSession(req, res, { cookieName: "...", password: "...". Check the usage here: https://github.com/vvo/iron-session`
|
|
22
|
+
);
|
|
25
23
|
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
24
|
+
const passwordsAsMap = normalizeStringPasswordToMap(
|
|
25
|
+
userSessionOptions.password
|
|
26
|
+
);
|
|
27
|
+
Object.values(
|
|
28
|
+
normalizeStringPasswordToMap(userSessionOptions.password)
|
|
29
|
+
).forEach((password) => {
|
|
30
|
+
if (password.length < 32) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
`iron-session: Bad usage. Password must be at least 32 characters long.`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
const options = {
|
|
37
|
+
...defaultOptions,
|
|
38
|
+
...userSessionOptions,
|
|
39
|
+
cookieOptions: {
|
|
40
|
+
...defaultOptions.cookieOptions,
|
|
41
|
+
...userSessionOptions.cookieOptions || {}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
if (options.ttl === 0) {
|
|
45
|
+
options.ttl = 2147483647;
|
|
33
46
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
47
|
+
if (userSessionOptions.cookieOptions && "maxAge" in userSessionOptions.cookieOptions) {
|
|
48
|
+
if (userSessionOptions.cookieOptions.maxAge === void 0) {
|
|
49
|
+
options.ttl = 0;
|
|
50
|
+
} else {
|
|
51
|
+
options.cookieOptions.maxAge = computeCookieMaxAge(
|
|
52
|
+
userSessionOptions.cookieOptions.maxAge
|
|
53
|
+
);
|
|
54
|
+
}
|
|
41
55
|
} else {
|
|
42
|
-
options.cookieOptions.maxAge = computeCookieMaxAge(
|
|
56
|
+
options.cookieOptions.maxAge = computeCookieMaxAge(options.ttl);
|
|
43
57
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
58
|
+
const sealFromCookies = cookie.parse(
|
|
59
|
+
"credentials" in req ? req.headers.get("cookie") || "" : req.headers.cookie || ""
|
|
60
|
+
)[options.cookieName];
|
|
61
|
+
const session = sealFromCookies === void 0 ? {} : await unsealData2(sealFromCookies, {
|
|
62
|
+
password: passwordsAsMap,
|
|
63
|
+
ttl: options.ttl
|
|
64
|
+
});
|
|
65
|
+
Object.defineProperties(session, {
|
|
66
|
+
save: {
|
|
67
|
+
value: async function save() {
|
|
68
|
+
if ("headersSent" in res && res.headersSent === true) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
`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()`
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
const seal2 = await sealData2(session, {
|
|
74
|
+
password: passwordsAsMap,
|
|
75
|
+
ttl: options.ttl
|
|
76
|
+
});
|
|
77
|
+
const cookieValue = cookie.serialize(
|
|
78
|
+
options.cookieName,
|
|
79
|
+
seal2,
|
|
80
|
+
options.cookieOptions
|
|
81
|
+
);
|
|
82
|
+
if (cookieValue.length > 4096) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
`iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it. Try to remove some data.`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
addToCookies(cookieValue, res);
|
|
57
88
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
89
|
+
},
|
|
90
|
+
destroy: {
|
|
91
|
+
value: function destroy() {
|
|
92
|
+
Object.keys(session).forEach((key) => {
|
|
93
|
+
delete session[key];
|
|
94
|
+
});
|
|
95
|
+
const cookieValue = cookie.serialize(options.cookieName, "", {
|
|
96
|
+
...options.cookieOptions,
|
|
97
|
+
maxAge: 0
|
|
98
|
+
});
|
|
99
|
+
addToCookies(cookieValue, res);
|
|
65
100
|
}
|
|
66
|
-
addToCookies(cookieValue, res);
|
|
67
|
-
}
|
|
68
|
-
},
|
|
69
|
-
destroy: {
|
|
70
|
-
value: function destroy() {
|
|
71
|
-
Object.keys(session).forEach((key) => {
|
|
72
|
-
delete session[key];
|
|
73
|
-
});
|
|
74
|
-
const cookieValue = cookie.serialize(options.cookieName, "", {
|
|
75
|
-
...options.cookieOptions,
|
|
76
|
-
maxAge: 0
|
|
77
|
-
});
|
|
78
|
-
addToCookies(cookieValue, res);
|
|
79
101
|
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
|
|
102
|
+
});
|
|
103
|
+
return session;
|
|
104
|
+
};
|
|
83
105
|
}
|
|
84
106
|
function addToCookies(cookieValue, res) {
|
|
85
107
|
var _a;
|
|
108
|
+
if ("headers" in res) {
|
|
109
|
+
res.headers.append("set-cookie", cookieValue);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
86
112
|
let existingSetCookie = (_a = res.getHeader("set-cookie")) != null ? _a : [];
|
|
87
113
|
if (typeof existingSetCookie === "string") {
|
|
88
114
|
existingSetCookie = [existingSetCookie];
|
|
@@ -92,64 +118,86 @@ function addToCookies(cookieValue, res) {
|
|
|
92
118
|
function computeCookieMaxAge(ttl) {
|
|
93
119
|
return ttl - timestampSkewSec;
|
|
94
120
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
121
|
+
function createUnsealData(_crypto2) {
|
|
122
|
+
return async (seal2, {
|
|
123
|
+
password,
|
|
124
|
+
ttl = fourteenDaysInSeconds
|
|
125
|
+
}) => {
|
|
126
|
+
const passwordsAsMap = normalizeStringPasswordToMap(password);
|
|
127
|
+
const { sealWithoutVersion, tokenVersion } = parseSeal(seal2);
|
|
128
|
+
try {
|
|
129
|
+
const data = await Iron.unseal(
|
|
130
|
+
_crypto2,
|
|
131
|
+
sealWithoutVersion,
|
|
132
|
+
passwordsAsMap,
|
|
133
|
+
{ ...Iron.defaults, ttl: ttl * 1e3 }
|
|
134
|
+
);
|
|
135
|
+
if (tokenVersion === 2) {
|
|
136
|
+
return data;
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
...data.persistent
|
|
140
|
+
};
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (error instanceof Error) {
|
|
143
|
+
if (error.message === "Expired seal" || error.message === "Bad hmac value" || error.message === "Cannot find password: " || error.message === "Incorrect number of sealed components") {
|
|
144
|
+
return {};
|
|
145
|
+
}
|
|
116
146
|
}
|
|
147
|
+
throw error;
|
|
117
148
|
}
|
|
118
|
-
|
|
119
|
-
}
|
|
149
|
+
};
|
|
120
150
|
}
|
|
121
|
-
function parseSeal(
|
|
122
|
-
if (
|
|
123
|
-
const [sealWithoutVersion, tokenVersionAsString] =
|
|
151
|
+
function parseSeal(seal2) {
|
|
152
|
+
if (seal2[seal2.length - 2] === versionDelimiter) {
|
|
153
|
+
const [sealWithoutVersion, tokenVersionAsString] = seal2.split(versionDelimiter);
|
|
124
154
|
return {
|
|
125
155
|
sealWithoutVersion,
|
|
126
156
|
tokenVersion: parseInt(tokenVersionAsString, 10)
|
|
127
157
|
};
|
|
128
158
|
}
|
|
129
|
-
return { sealWithoutVersion:
|
|
159
|
+
return { sealWithoutVersion: seal2, tokenVersion: null };
|
|
130
160
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
161
|
+
function createSealData(_crypto2) {
|
|
162
|
+
return async (data, {
|
|
163
|
+
password,
|
|
164
|
+
ttl = fourteenDaysInSeconds
|
|
165
|
+
}) => {
|
|
166
|
+
const passwordsAsMap = normalizeStringPasswordToMap(password);
|
|
167
|
+
const mostRecentPasswordId = Math.max(
|
|
168
|
+
...Object.keys(passwordsAsMap).map((id) => parseInt(id, 10))
|
|
169
|
+
);
|
|
170
|
+
const passwordForSeal = {
|
|
171
|
+
id: mostRecentPasswordId.toString(),
|
|
172
|
+
secret: passwordsAsMap[mostRecentPasswordId]
|
|
173
|
+
};
|
|
174
|
+
const seal2 = await Iron.seal(_crypto2, data, passwordForSeal, {
|
|
175
|
+
...Iron.defaults,
|
|
176
|
+
ttl: ttl * 1e3
|
|
177
|
+
});
|
|
178
|
+
return `${seal2}${versionDelimiter}${currentMajorVersion}`;
|
|
140
179
|
};
|
|
141
|
-
const seal = await Iron.seal(data, passwordForSeal, {
|
|
142
|
-
...Iron.defaults,
|
|
143
|
-
ttl: ttl * 1e3
|
|
144
|
-
});
|
|
145
|
-
return `${seal}${versionDelimiter}${currentMajorVersion}`;
|
|
146
180
|
}
|
|
147
181
|
function normalizeStringPasswordToMap(password) {
|
|
148
182
|
return typeof password === "string" ? { 1: password } : password;
|
|
149
183
|
}
|
|
184
|
+
|
|
185
|
+
// src/index.ts
|
|
186
|
+
import { Crypto } from "@peculiar/webcrypto";
|
|
187
|
+
var _crypto = new Crypto();
|
|
188
|
+
var unsealData = createUnsealData(_crypto);
|
|
189
|
+
var sealData = createSealData(_crypto);
|
|
190
|
+
var getIronSession = createGetIronSession(
|
|
191
|
+
_crypto,
|
|
192
|
+
unsealData,
|
|
193
|
+
sealData
|
|
194
|
+
);
|
|
150
195
|
export {
|
|
196
|
+
createGetIronSession,
|
|
197
|
+
createSealData,
|
|
198
|
+
createUnsealData,
|
|
151
199
|
getIronSession,
|
|
152
200
|
sealData,
|
|
153
201
|
unsealData
|
|
154
202
|
};
|
|
155
|
-
//# sourceMappingURL=index.mjs.map
|
|
203
|
+
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1,7 +1 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["import Iron from \"@hapi/iron\";\nimport type { CookieSerializeOptions } from \"cookie\";\nimport cookie from \"cookie\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\n\n// default time allowed to check for iron seal validity when ttl passed\n// see https://hapi.dev/family/iron/api/?v=6.0.0#options\nconst timestampSkewSec = 60;\n\ntype passwordsMap = { [id: string]: string };\ntype password = string | passwordsMap;\n\nconst fourteenDaysInSeconds = 15 * 24 * 3600;\n\n// We store a token major version to handle data format changes when any. So that when you upgrade the cookies\n// can be kept alive between upgrades, no need to disconnect everyone.\nconst currentMajorVersion = 2;\nconst versionDelimiter = \"~\";\n\nconst defaultOptions: {\n ttl: number;\n cookieOptions: CookieSerializeOptions;\n} = {\n ttl: fourteenDaysInSeconds,\n cookieOptions: {\n httpOnly: true,\n secure: true,\n sameSite: \"lax\",\n path: \"/\",\n },\n};\n\nexport interface IronSessionOptions {\n /**\n * This is the cookie name that will be used inside the browser. You should make sure it's unique given\n * your application. Example: vercel-session\n */\n cookieName: string;\n\n /**\n * This is the password(s) that will be used to encrypt the cookie. It can be either a string or an object\n * like {1: \"password\", 2: password}.\n *\n * When you provide multiple passwords then all of them will be used to decrypt the cookie and only the most\n * recent (= highest key, 2 in this example) password will be used to encrypt the cookie. This allow you\n * to use password rotation (security)\n */\n password: password;\n\n /**\n * This is the time in seconds that the session will be valid for. This also set the max-age attribute of\n * the cookie automatically (minus 60 seconds so that the cookie always expire before the session).\n */\n ttl?: number;\n\n /**\n * This is the options that will be passed to the cookie library.\n * You can see all of them here: https://github.com/jshttp/cookie#options-1.\n *\n * If you want to use \"session cookies\" (cookies that are deleted when the browser is closed) then you need\n * to pass cookieOptions: { maxAge: undefined }.\n */\n cookieOptions?: CookieSerializeOptions;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface IronSessionData {\n // If we allow for any keys, then there's no more type check on unknown properties\n // which is not good\n // If we allow for any keys, the later delete will work but I prefer to disable the\n // check at this stage and\n // provide good type checking instead\n // [key: string]: unknown;\n}\n\nexport type IronSession = IronSessionData & {\n /**\n * Destroys the session data and removes the cookie.\n */\n destroy: () => void;\n\n /**\n * Encrypts the session data and sets the cookie.\n */\n save: () => Promise<void>;\n};\n\ndeclare module \"http\" {\n interface IncomingMessage {\n session: IronSession;\n }\n}\n\nexport async function getIronSession(\n req: IncomingMessage,\n res: ServerResponse,\n userSessionOptions: IronSessionOptions,\n): Promise<IronSession> {\n if (\n !req ||\n !res ||\n !userSessionOptions ||\n !userSessionOptions.cookieName ||\n !userSessionOptions.password\n ) {\n throw new Error(\n `iron-session: Bad usage. Minimum usage is const session = await getIronSession(req, res, { cookieName: \"...\", password: \"...\". Check the usage here: https://github.com/vvo/iron-session`,\n );\n }\n\n const passwordsAsMap = normalizeStringPasswordToMap(\n userSessionOptions.password,\n );\n\n Object.values(\n normalizeStringPasswordToMap(userSessionOptions.password),\n ).forEach((password) => {\n if (password.length < 32) {\n throw new Error(\n `iron-session: Bad usage. Password must be at least 32 characters long.`,\n );\n }\n });\n\n const options: Required<IronSessionOptions> = {\n ...defaultOptions,\n ...userSessionOptions,\n cookieOptions: {\n ...defaultOptions.cookieOptions,\n ...(userSessionOptions.cookieOptions || {}),\n },\n };\n\n if (options.ttl === 0) {\n // ttl = 0 means no expiration\n // but in reality cookies have to expire (can't have no max-age)\n // 2147483647 is the max value for max-age in cookies\n // see https://stackoverflow.com/a/11685301/147079\n options.ttl = 2147483647;\n }\n\n if (\n userSessionOptions.cookieOptions &&\n \"maxAge\" in userSessionOptions.cookieOptions\n ) {\n // session cookie, do not set maxAge, consider token as infinite\n if (userSessionOptions.cookieOptions.maxAge === undefined) {\n options.ttl = 0;\n } else {\n options.cookieOptions.maxAge = computeCookieMaxAge(\n userSessionOptions.cookieOptions.maxAge,\n );\n }\n } else {\n options.cookieOptions.maxAge = computeCookieMaxAge(options.ttl);\n }\n\n const sealFromCookies = cookie.parse(req.headers.cookie || \"\")[\n options.cookieName\n ];\n\n const session =\n sealFromCookies === undefined\n ? {}\n : await unsealData<IronSessionData>(sealFromCookies, {\n password: passwordsAsMap,\n ttl: options.ttl,\n });\n\n Object.defineProperties(session, {\n save: {\n value: async function save() {\n if (res.headersSent === true) {\n throw new Error(\n `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()`,\n );\n }\n const seal = await sealData(session, {\n password: passwordsAsMap,\n ttl: options.ttl,\n });\n const cookieValue = cookie.serialize(\n options.cookieName,\n seal,\n options.cookieOptions,\n );\n\n if (cookieValue.length > 4096) {\n throw new Error(\n `iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it. Try to remove some data.`,\n );\n }\n\n addToCookies(cookieValue, res);\n },\n },\n destroy: {\n value: function destroy() {\n Object.keys(session).forEach((key) => {\n // @ts-ignore See comment on the IronSessionData interface\n delete session[key];\n });\n\n const cookieValue = cookie.serialize(options.cookieName, \"\", {\n ...options.cookieOptions,\n maxAge: 0,\n });\n addToCookies(cookieValue, res);\n },\n },\n });\n\n return session as IronSession;\n}\n\nfunction addToCookies(cookieValue: string, res: ServerResponse) {\n let existingSetCookie =\n (res.getHeader(\"set-cookie\") as string[] | string) ?? [];\n if (typeof existingSetCookie === \"string\") {\n existingSetCookie = [existingSetCookie];\n }\n res.setHeader(\"set-cookie\", [...existingSetCookie, cookieValue]);\n}\n\nfunction computeCookieMaxAge(ttl: number) {\n // The next line makes sure browser will expire cookies before seals are considered expired by the server.\n // It also allows for clock difference of 60 seconds maximum between server and clients.\n // It also makes sure to expire the cookie immediately when value is 0\n return ttl - timestampSkewSec;\n}\n\nexport async function unsealData<T = Record<string, unknown>>(\n seal: string,\n {\n password,\n ttl = fourteenDaysInSeconds,\n }: { password: password; ttl?: number },\n): Promise<T> {\n const passwordsAsMap = normalizeStringPasswordToMap(password);\n const { sealWithoutVersion, tokenVersion } = parseSeal(seal);\n\n try {\n const data = await Iron.unseal(sealWithoutVersion, passwordsAsMap, {\n ...Iron.defaults,\n ttl: ttl * 1000,\n });\n\n if (tokenVersion === 2) {\n return data;\n }\n\n return {\n ...data.persistent,\n };\n } catch (error) {\n if (error instanceof Error) {\n if (\n error.message === \"Expired seal\" ||\n error.message === \"Bad hmac value\" ||\n error.message === \"Cannot find password: \" ||\n error.message === \"Incorrect number of sealed components\"\n ) {\n // if seal expired or\n // if seal is not valid (encrypted using a different password, when passwords are badly rotated) or\n // if we can't find back the password in the seal\n // then we just start a new session over\n return {} as T;\n }\n }\n\n throw error;\n }\n}\n\nfunction parseSeal(seal: string): {\n sealWithoutVersion: string;\n tokenVersion: number | null;\n} {\n if (seal[seal.length - 2] === versionDelimiter) {\n const [sealWithoutVersion, tokenVersionAsString] =\n seal.split(versionDelimiter);\n return {\n sealWithoutVersion,\n tokenVersion: parseInt(tokenVersionAsString, 10),\n };\n }\n\n return { sealWithoutVersion: seal, tokenVersion: null };\n}\n\nexport async function sealData(\n data: unknown,\n {\n password,\n ttl = fourteenDaysInSeconds,\n }: { password: password; ttl?: number },\n) {\n const passwordsAsMap = normalizeStringPasswordToMap(password);\n\n const mostRecentPasswordId = Math.max(\n ...Object.keys(passwordsAsMap).map((id) => parseInt(id, 10)),\n );\n\n const passwordForSeal = {\n id: mostRecentPasswordId.toString(),\n secret: passwordsAsMap[mostRecentPasswordId],\n };\n\n const seal = await Iron.seal(data, passwordForSeal, {\n ...Iron.defaults,\n ttl: ttl * 1000,\n });\n\n return `${seal}${versionDelimiter}${currentMajorVersion}`;\n}\n\nfunction normalizeStringPasswordToMap(password: password) {\n return typeof password === \"string\" ? { 1: password } : password;\n}\n"],
|
|
5
|
-
"mappings": ";AAAA;AAEA;AAKA,IAAM,mBAAmB;AAKzB,IAAM,wBAAwB,KAAK,KAAK;AAIxC,IAAM,sBAAsB;AAC5B,IAAM,mBAAmB;AAEzB,IAAM,iBAGF;AAAA,EACF,KAAK;AAAA,EACL,eAAe;AAAA,IACb,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,MAAM;AAAA;AAAA;AAiEV,8BACE,KACA,KACA,oBACsB;AACtB,MACE,CAAC,OACD,CAAC,OACD,CAAC,sBACD,CAAC,mBAAmB,cACpB,CAAC,mBAAmB,UACpB;AACA,UAAM,IAAI,MACR;AAAA;AAIJ,QAAM,iBAAiB,6BACrB,mBAAmB;AAGrB,SAAO,OACL,6BAA6B,mBAAmB,WAChD,QAAQ,CAAC,aAAa;AACtB,QAAI,SAAS,SAAS,IAAI;AACxB,YAAM,IAAI,MACR;AAAA;AAAA;AAKN,QAAM,UAAwC;AAAA,OACzC;AAAA,OACA;AAAA,IACH,eAAe;AAAA,SACV,eAAe;AAAA,SACd,mBAAmB,iBAAiB;AAAA;AAAA;AAI5C,MAAI,QAAQ,QAAQ,GAAG;AAKrB,YAAQ,MAAM;AAAA;AAGhB,MACE,mBAAmB,iBACnB,YAAY,mBAAmB,eAC/B;AAEA,QAAI,mBAAmB,cAAc,WAAW,QAAW;AACzD,cAAQ,MAAM;AAAA,WACT;AACL,cAAQ,cAAc,SAAS,oBAC7B,mBAAmB,cAAc;AAAA;AAAA,SAGhC;AACL,YAAQ,cAAc,SAAS,oBAAoB,QAAQ;AAAA;AAG7D,QAAM,kBAAkB,OAAO,MAAM,IAAI,QAAQ,UAAU,IACzD,QAAQ;AAGV,QAAM,UACJ,oBA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BAAiB,GAAG;AACtB,aAAO;AAAA;AAGT,WAAO;AAAA,SACF,KAAK;AAAA;AAAA,WAEH,OAAP;AACA,QAAI,iBAAiB,OAAO;AAC1B,UACE,MAAM,YAAY,kBAClB,MAAM,YAAY,oBAClB,MAAM,YAAY,4BAClB,MAAM,YAAY,yCAClB;AAKA,eAAO;AAAA;AAAA;AAIX,UAAM;AAAA;AAAA;AAIV,mBAAmB,MAGjB;AACA,MAAI,KAAK,KAAK,SAAS,OAAO,kBAAkB;AAC9C,UAAM,CAAC,oBAAoB,wBACzB,KAAK,MAAM;AACb,WAAO;AAAA,MACL;AAAA,MACA,cAAc,SAAS,sBAAsB;AAAA;AAAA;AAIjD,SAAO,EAAE,oBAAoB,MAAM,cAAc;AAAA;AAGnD,wBACE,MACA;AAAA,EACE;AAAA,EACA,MAAM;AAAA,GAER;AACA,QAAM,iBAAiB,6BAA6B;AAEpD,QAAM,uBAAuB,KAAK,IAChC,GAAG,OAAO,KAAK,gBAAgB,IAAI,CAAC,OAAO,SAAS,IAAI;AAG1D,QAAM,kBAAkB;AAAA,IACtB,IAAI,qBAAqB;AAAA,IACzB,QAAQ,eAAe;AAAA;AAGzB,QAAM,OAAO,MAAM,KAAK,KAAK,MAAM,iBAAiB;AAAA,OAC/C,KAAK;AAAA,IACR,KAAK,MAAM;AAAA;AAGb,SAAO,GAAG,OAAO,mBAAmB;AAAA;AAGtC,sCAAsC,UAAoB;AACxD,SAAO,OAAO,aAAa,WAAW,EAAE,GAAG,aAAa;AAAA;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|
|
1
|
+
{"version":3,"sources":["../src/core.ts","../src/index.ts"],"sourcesContent":["import * as Iron from \"iron-webcrypto\";\nimport type { CookieSerializeOptions } from \"cookie\";\nimport cookie from \"cookie\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\n\n// default time allowed to check for iron seal validity when ttl passed\n// see https://hapi.dev/family/iron/api/?v=6.0.0#options\nconst timestampSkewSec = 60;\n\ntype passwordsMap = { [id: string]: string };\ntype password = string | passwordsMap;\n\nconst fourteenDaysInSeconds = 15 * 24 * 3600;\n\n// We store a token major version to handle data format changes when any. So that when you upgrade the cookies\n// can be kept alive between upgrades, no need to disconnect everyone.\nconst currentMajorVersion = 2;\nconst versionDelimiter = \"~\";\n\nconst defaultOptions: {\n ttl: number;\n cookieOptions: CookieSerializeOptions;\n} = {\n ttl: fourteenDaysInSeconds,\n cookieOptions: {\n httpOnly: true,\n secure: true,\n sameSite: \"lax\",\n path: \"/\",\n },\n};\n\nexport interface IronSessionOptions {\n /**\n * This is the cookie name that will be used inside the browser. You should make sure it's unique given\n * your application. Example: vercel-session\n */\n cookieName: string;\n\n /**\n * This is the password(s) that will be used to encrypt the cookie. It can be either a string or an object\n * like {1: \"password\", 2: password}.\n *\n * When you provide multiple passwords then all of them will be used to decrypt the cookie and only the most\n * recent (= highest key, 2 in this example) password will be used to encrypt the cookie. This allow you\n * to use password rotation (security)\n */\n password: password;\n\n /**\n * This is the time in seconds that the session will be valid for. This also set the max-age attribute of\n * the cookie automatically (minus 60 seconds so that the cookie always expire before the session).\n */\n ttl?: number;\n\n /**\n * This is the options that will be passed to the cookie library.\n * You can see all of them here: https://github.com/jshttp/cookie#options-1.\n *\n * If you want to use \"session cookies\" (cookies that are deleted when the browser is closed) then you need\n * to pass cookieOptions: { maxAge: undefined }.\n */\n cookieOptions?: CookieSerializeOptions;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface IronSessionData {\n // If we allow for any keys, then there's no more type check on unknown properties\n // which is not good\n // If we allow for any keys, the later delete will work but I prefer to disable the\n // check at this stage and\n // provide good type checking instead\n // [key: string]: unknown;\n}\n\nexport type IronSession = IronSessionData & {\n /**\n * Destroys the session data and removes the cookie.\n */\n destroy: () => void;\n\n /**\n * Encrypts the session data and sets the cookie.\n */\n save: () => Promise<void>;\n};\n\ndeclare module \"http\" {\n interface IncomingMessage {\n session: IronSession;\n }\n}\n\ntype RequestType = IncomingMessage | Request;\ntype ResponseType = ServerResponse | Response;\n\nexport function createGetIronSession(\n _crypto: Crypto,\n unsealData: ReturnType<typeof createUnsealData>,\n sealData: ReturnType<typeof createSealData>,\n) {\n return async (\n req: RequestType,\n res: ResponseType,\n userSessionOptions: IronSessionOptions,\n ): Promise<IronSession> => {\n if (\n !req ||\n !res ||\n !userSessionOptions ||\n !userSessionOptions.cookieName ||\n !userSessionOptions.password\n ) {\n throw new Error(\n `iron-session: Bad usage. Minimum usage is const session = await getIronSession(req, res, { cookieName: \"...\", password: \"...\". Check the usage here: https://github.com/vvo/iron-session`,\n );\n }\n\n const passwordsAsMap = normalizeStringPasswordToMap(\n userSessionOptions.password,\n );\n\n Object.values(\n normalizeStringPasswordToMap(userSessionOptions.password),\n ).forEach((password) => {\n if (password.length < 32) {\n throw new Error(\n `iron-session: Bad usage. Password must be at least 32 characters long.`,\n );\n }\n });\n\n const options: Required<IronSessionOptions> = {\n ...defaultOptions,\n ...userSessionOptions,\n cookieOptions: {\n ...defaultOptions.cookieOptions,\n ...(userSessionOptions.cookieOptions || {}),\n },\n };\n\n if (options.ttl === 0) {\n // ttl = 0 means no expiration\n // but in reality cookies have to expire (can't have no max-age)\n // 2147483647 is the max value for max-age in cookies\n // see https://stackoverflow.com/a/11685301/147079\n options.ttl = 2147483647;\n }\n\n if (\n userSessionOptions.cookieOptions &&\n \"maxAge\" in userSessionOptions.cookieOptions\n ) {\n // session cookie, do not set maxAge, consider token as infinite\n if (userSessionOptions.cookieOptions.maxAge === undefined) {\n options.ttl = 0;\n } else {\n options.cookieOptions.maxAge = computeCookieMaxAge(\n userSessionOptions.cookieOptions.maxAge,\n );\n }\n } else {\n options.cookieOptions.maxAge = computeCookieMaxAge(options.ttl);\n }\n\n const sealFromCookies = cookie.parse(\n \"credentials\" in req\n ? req.headers.get(\"cookie\") || \"\"\n : req.headers.cookie || \"\",\n )[options.cookieName];\n\n const session =\n sealFromCookies === undefined\n ? {}\n : await unsealData<IronSessionData>(sealFromCookies, {\n password: passwordsAsMap,\n ttl: options.ttl,\n });\n\n Object.defineProperties(session, {\n save: {\n value: async function save() {\n if (\"headersSent\" in res && res.headersSent === true) {\n throw new Error(\n `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()`,\n );\n }\n const seal = await sealData(session, {\n password: passwordsAsMap,\n ttl: options.ttl,\n });\n const cookieValue = cookie.serialize(\n options.cookieName,\n seal,\n options.cookieOptions,\n );\n\n if (cookieValue.length > 4096) {\n throw new Error(\n `iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it. Try to remove some data.`,\n );\n }\n\n addToCookies(cookieValue, res);\n },\n },\n destroy: {\n value: function destroy() {\n Object.keys(session).forEach((key) => {\n // @ts-ignore See comment on the IronSessionData interface\n delete session[key];\n });\n\n const cookieValue = cookie.serialize(options.cookieName, \"\", {\n ...options.cookieOptions,\n maxAge: 0,\n });\n addToCookies(cookieValue, res);\n },\n },\n });\n\n return session as IronSession;\n };\n}\n\nfunction addToCookies(cookieValue: string, res: ResponseType) {\n if (\"headers\" in res) {\n res.headers.append(\"set-cookie\", cookieValue);\n return;\n }\n\n let existingSetCookie =\n (res.getHeader(\"set-cookie\") as string[] | string) ?? [];\n if (typeof existingSetCookie === \"string\") {\n existingSetCookie = [existingSetCookie];\n }\n res.setHeader(\"set-cookie\", [...existingSetCookie, cookieValue]);\n}\n\nfunction computeCookieMaxAge(ttl: number) {\n // The next line makes sure browser will expire cookies before seals are considered expired by the server.\n // It also allows for clock difference of 60 seconds maximum between server and clients.\n // It also makes sure to expire the cookie immediately when value is 0\n return ttl - timestampSkewSec;\n}\n\nexport function createUnsealData(_crypto: Crypto) {\n return async <T = Record<string, unknown>>(\n seal: string,\n {\n password,\n ttl = fourteenDaysInSeconds,\n }: { password: password; ttl?: number },\n ): Promise<T> => {\n const passwordsAsMap = normalizeStringPasswordToMap(password);\n const { sealWithoutVersion, tokenVersion } = parseSeal(seal);\n\n try {\n const data = await Iron.unseal(\n _crypto,\n sealWithoutVersion,\n passwordsAsMap,\n { ...Iron.defaults, ttl: ttl * 1000 },\n );\n\n if (tokenVersion === 2) {\n return data as T;\n }\n\n return {\n // @ts-expect-error `persistent` does not exist on newer tokens\n ...data.persistent,\n };\n } catch (error) {\n if (error instanceof Error) {\n if (\n error.message === \"Expired seal\" ||\n error.message === \"Bad hmac value\" ||\n error.message === \"Cannot find password: \" ||\n error.message === \"Incorrect number of sealed components\"\n ) {\n // if seal expired or\n // if seal is not valid (encrypted using a different password, when passwords are badly rotated) or\n // if we can't find back the password in the seal\n // then we just start a new session over\n return {} as T;\n }\n }\n\n throw error;\n }\n };\n}\n\nfunction parseSeal(seal: string): {\n sealWithoutVersion: string;\n tokenVersion: number | null;\n} {\n if (seal[seal.length - 2] === versionDelimiter) {\n const [sealWithoutVersion, tokenVersionAsString] =\n seal.split(versionDelimiter);\n return {\n sealWithoutVersion,\n tokenVersion: parseInt(tokenVersionAsString, 10),\n };\n }\n\n return { sealWithoutVersion: seal, tokenVersion: null };\n}\n\nexport function createSealData(_crypto: Crypto) {\n return async (\n data: unknown,\n {\n password,\n ttl = fourteenDaysInSeconds,\n }: { password: password; ttl?: number },\n ) => {\n const passwordsAsMap = normalizeStringPasswordToMap(password);\n\n const mostRecentPasswordId = Math.max(\n ...Object.keys(passwordsAsMap).map((id) => parseInt(id, 10)),\n );\n\n const passwordForSeal = {\n id: mostRecentPasswordId.toString(),\n secret: passwordsAsMap[mostRecentPasswordId],\n };\n\n const seal = await Iron.seal(_crypto, data, passwordForSeal, {\n ...Iron.defaults,\n ttl: ttl * 1000,\n });\n\n return `${seal}${versionDelimiter}${currentMajorVersion}`;\n };\n}\n\nfunction normalizeStringPasswordToMap(password: password) {\n return typeof password === \"string\" ? { 1: password } : password;\n}\n","import { createGetIronSession, createSealData, createUnsealData } from \"./core\";\nimport { Crypto } from \"@peculiar/webcrypto\";\n\nconst _crypto = new Crypto();\n\nexport * from \"./core\";\nexport const unsealData = createUnsealData(_crypto);\nexport const sealData = createSealData(_crypto);\nexport const getIronSession = createGetIronSession(\n _crypto,\n unsealData,\n sealData,\n);\n"],"mappings":";AAAA,YAAY,UAAU;AAEtB,OAAO,YAAY;AAKnB,IAAM,mBAAmB;AAKzB,IAAM,wBAAwB,KAAK,KAAK;AAIxC,IAAM,sBAAsB;AAC5B,IAAM,mBAAmB;AAEzB,IAAM,iBAGF;AAAA,EACF,KAAK;AAAA,EACL,eAAe;AAAA,IACb,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,MAAM;AAAA,EACR;AACF;AAkEO,SAAS,qBACdA,UACAC,aACAC,WACA;AACA,SAAO,OACL,KACA,KACA,uBACyB;AACzB,QACE,CAAC,OACD,CAAC,OACD,CAAC,sBACD,CAAC,mBAAmB,cACpB,CAAC,mBAAmB,UACpB;AACA,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,iBAAiB;AAAA,MACrB,mBAAmB;AAAA,IACrB;AAEA,WAAO;AAAA,MACL,6BAA6B,mBAAmB,QAAQ;AAAA,IAC1D,EAAE,QAAQ,CAAC,aAAa;AACtB,UAAI,SAAS,SAAS,IAAI;AACxB,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAED,UAAM,UAAwC;AAAA,MAC5C,GAAG;AAAA,MACH,GAAG;AAAA,MACH,eAAe;AAAA,QACb,GAAG,eAAe;AAAA,QAClB,GAAI,mBAAmB,iBAAiB,CAAC;AAAA,MAC3C;AAAA,IACF;AAEA,QAAI,QAAQ,QAAQ,GAAG;AAKrB,cAAQ,MAAM;AAAA,IAChB;AAEA,QACE,mBAAmB,iBACnB,YAAY,mBAAmB,eAC/B;AAEA,UAAI,mBAAmB,cAAc,WAAW,QAAW;AACzD,gBAAQ,MAAM;AAAA,MAChB,OAAO;AACL,gBAAQ,cAAc,SAAS;AAAA,UAC7B,mBAAmB,cAAc;AAAA,QACnC;AAAA,MACF;AAAA,IACF,OAAO;A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O,OACL,MACA;AAAA,IACE;AAAA,IACA,MAAM;AAAA,EACR,MACG;AACH,UAAM,iBAAiB,6BAA6B,QAAQ;AAE5D,UAAM,uBAAuB,KAAK;AAAA,MAChC,GAAG,OAAO,KAAK,cAAc,EAAE,IAAI,CAAC,OAAO,SAAS,IAAI,EAAE,CAAC;AAAA,IAC7D;AAEA,UAAM,kBAAkB;AAAA,MACtB,IAAI,qBAAqB,SAAS;AAAA,MAClC,QAAQ,eAAe;AAAA,IACzB;AAEA,UAAMG,QAAO,MAAW,UAAKH,UAAS,MAAM,iBAAiB;AAAA,MAC3D,GAAQ;AAAA,MACR,KAAK,MAAM;AAAA,IACb,CAAC;AAED,WAAO,GAAGG,QAAO,mBAAmB;AAAA,EACtC;AACF;AAEA,SAAS,6BAA6B,UAAoB;AACxD,SAAO,OAAO,aAAa,WAAW,EAAE,GAAG,SAAS,IAAI;AAC1D;;;ACpVA,SAAS,cAAc;AAEvB,IAAM,UAAU,IAAI,OAAO;AAGpB,IAAM,aAAa,iBAAiB,OAAO;AAC3C,IAAM,WAAW,eAAe,OAAO;AACvC,IAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AACF;","names":["_crypto","unsealData","sealData","seal"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as iron_session from 'iron-session';
|
|
2
|
+
export { IronSessionData, IronSessionOptions } from 'iron-session';
|
|
3
|
+
import * as http from 'http';
|
|
4
|
+
|
|
5
|
+
declare const unsealData: <T = Record<string, unknown>>(seal: string, { password, ttl, }: {
|
|
6
|
+
password: string | {
|
|
7
|
+
[id: string]: string;
|
|
8
|
+
};
|
|
9
|
+
ttl?: number | undefined;
|
|
10
|
+
}) => Promise<T>;
|
|
11
|
+
declare const sealData: (data: unknown, { password, ttl, }: {
|
|
12
|
+
password: string | {
|
|
13
|
+
[id: string]: string;
|
|
14
|
+
};
|
|
15
|
+
ttl?: number | undefined;
|
|
16
|
+
}) => Promise<string>;
|
|
17
|
+
declare const getIronSession: (req: http.IncomingMessage | Request, res: http.ServerResponse | Response, userSessionOptions: iron_session.IronSessionOptions) => Promise<iron_session.IronSession>;
|
|
18
|
+
|
|
19
|
+
export { getIronSession, sealData, unsealData };
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
22
|
+
mod
|
|
23
|
+
));
|
|
24
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
25
|
+
|
|
26
|
+
// edge/index.ts
|
|
27
|
+
var edge_exports = {};
|
|
28
|
+
__export(edge_exports, {
|
|
29
|
+
getIronSession: () => getIronSession,
|
|
30
|
+
sealData: () => sealData,
|
|
31
|
+
unsealData: () => unsealData
|
|
32
|
+
});
|
|
33
|
+
module.exports = __toCommonJS(edge_exports);
|
|
34
|
+
|
|
35
|
+
// src/core.ts
|
|
36
|
+
var Iron = __toESM(require("iron-webcrypto"));
|
|
37
|
+
var import_cookie = __toESM(require("cookie"));
|
|
38
|
+
var timestampSkewSec = 60;
|
|
39
|
+
var fourteenDaysInSeconds = 15 * 24 * 3600;
|
|
40
|
+
var currentMajorVersion = 2;
|
|
41
|
+
var versionDelimiter = "~";
|
|
42
|
+
var defaultOptions = {
|
|
43
|
+
ttl: fourteenDaysInSeconds,
|
|
44
|
+
cookieOptions: {
|
|
45
|
+
httpOnly: true,
|
|
46
|
+
secure: true,
|
|
47
|
+
sameSite: "lax",
|
|
48
|
+
path: "/"
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
function createGetIronSession(_crypto2, unsealData2, sealData2) {
|
|
52
|
+
return async (req, res, userSessionOptions) => {
|
|
53
|
+
if (!req || !res || !userSessionOptions || !userSessionOptions.cookieName || !userSessionOptions.password) {
|
|
54
|
+
throw new Error(
|
|
55
|
+
`iron-session: Bad usage. Minimum usage is const session = await getIronSession(req, res, { cookieName: "...", password: "...". Check the usage here: https://github.com/vvo/iron-session`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
const passwordsAsMap = normalizeStringPasswordToMap(
|
|
59
|
+
userSessionOptions.password
|
|
60
|
+
);
|
|
61
|
+
Object.values(
|
|
62
|
+
normalizeStringPasswordToMap(userSessionOptions.password)
|
|
63
|
+
).forEach((password) => {
|
|
64
|
+
if (password.length < 32) {
|
|
65
|
+
throw new Error(
|
|
66
|
+
`iron-session: Bad usage. Password must be at least 32 characters long.`
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
const options = {
|
|
71
|
+
...defaultOptions,
|
|
72
|
+
...userSessionOptions,
|
|
73
|
+
cookieOptions: {
|
|
74
|
+
...defaultOptions.cookieOptions,
|
|
75
|
+
...userSessionOptions.cookieOptions || {}
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
if (options.ttl === 0) {
|
|
79
|
+
options.ttl = 2147483647;
|
|
80
|
+
}
|
|
81
|
+
if (userSessionOptions.cookieOptions && "maxAge" in userSessionOptions.cookieOptions) {
|
|
82
|
+
if (userSessionOptions.cookieOptions.maxAge === void 0) {
|
|
83
|
+
options.ttl = 0;
|
|
84
|
+
} else {
|
|
85
|
+
options.cookieOptions.maxAge = computeCookieMaxAge(
|
|
86
|
+
userSessionOptions.cookieOptions.maxAge
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
options.cookieOptions.maxAge = computeCookieMaxAge(options.ttl);
|
|
91
|
+
}
|
|
92
|
+
const sealFromCookies = import_cookie.default.parse(
|
|
93
|
+
"credentials" in req ? req.headers.get("cookie") || "" : req.headers.cookie || ""
|
|
94
|
+
)[options.cookieName];
|
|
95
|
+
const session = sealFromCookies === void 0 ? {} : await unsealData2(sealFromCookies, {
|
|
96
|
+
password: passwordsAsMap,
|
|
97
|
+
ttl: options.ttl
|
|
98
|
+
});
|
|
99
|
+
Object.defineProperties(session, {
|
|
100
|
+
save: {
|
|
101
|
+
value: async function save() {
|
|
102
|
+
if ("headersSent" in res && res.headersSent === true) {
|
|
103
|
+
throw new Error(
|
|
104
|
+
`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()`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
const seal2 = await sealData2(session, {
|
|
108
|
+
password: passwordsAsMap,
|
|
109
|
+
ttl: options.ttl
|
|
110
|
+
});
|
|
111
|
+
const cookieValue = import_cookie.default.serialize(
|
|
112
|
+
options.cookieName,
|
|
113
|
+
seal2,
|
|
114
|
+
options.cookieOptions
|
|
115
|
+
);
|
|
116
|
+
if (cookieValue.length > 4096) {
|
|
117
|
+
throw new Error(
|
|
118
|
+
`iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it. Try to remove some data.`
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
addToCookies(cookieValue, res);
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
destroy: {
|
|
125
|
+
value: function destroy() {
|
|
126
|
+
Object.keys(session).forEach((key) => {
|
|
127
|
+
delete session[key];
|
|
128
|
+
});
|
|
129
|
+
const cookieValue = import_cookie.default.serialize(options.cookieName, "", {
|
|
130
|
+
...options.cookieOptions,
|
|
131
|
+
maxAge: 0
|
|
132
|
+
});
|
|
133
|
+
addToCookies(cookieValue, res);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
return session;
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function addToCookies(cookieValue, res) {
|
|
141
|
+
var _a;
|
|
142
|
+
if ("headers" in res) {
|
|
143
|
+
res.headers.append("set-cookie", cookieValue);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
let existingSetCookie = (_a = res.getHeader("set-cookie")) != null ? _a : [];
|
|
147
|
+
if (typeof existingSetCookie === "string") {
|
|
148
|
+
existingSetCookie = [existingSetCookie];
|
|
149
|
+
}
|
|
150
|
+
res.setHeader("set-cookie", [...existingSetCookie, cookieValue]);
|
|
151
|
+
}
|
|
152
|
+
function computeCookieMaxAge(ttl) {
|
|
153
|
+
return ttl - timestampSkewSec;
|
|
154
|
+
}
|
|
155
|
+
function createUnsealData(_crypto2) {
|
|
156
|
+
return async (seal2, {
|
|
157
|
+
password,
|
|
158
|
+
ttl = fourteenDaysInSeconds
|
|
159
|
+
}) => {
|
|
160
|
+
const passwordsAsMap = normalizeStringPasswordToMap(password);
|
|
161
|
+
const { sealWithoutVersion, tokenVersion } = parseSeal(seal2);
|
|
162
|
+
try {
|
|
163
|
+
const data = await Iron.unseal(
|
|
164
|
+
_crypto2,
|
|
165
|
+
sealWithoutVersion,
|
|
166
|
+
passwordsAsMap,
|
|
167
|
+
{ ...Iron.defaults, ttl: ttl * 1e3 }
|
|
168
|
+
);
|
|
169
|
+
if (tokenVersion === 2) {
|
|
170
|
+
return data;
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
...data.persistent
|
|
174
|
+
};
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (error instanceof Error) {
|
|
177
|
+
if (error.message === "Expired seal" || error.message === "Bad hmac value" || error.message === "Cannot find password: " || error.message === "Incorrect number of sealed components") {
|
|
178
|
+
return {};
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function parseSeal(seal2) {
|
|
186
|
+
if (seal2[seal2.length - 2] === versionDelimiter) {
|
|
187
|
+
const [sealWithoutVersion, tokenVersionAsString] = seal2.split(versionDelimiter);
|
|
188
|
+
return {
|
|
189
|
+
sealWithoutVersion,
|
|
190
|
+
tokenVersion: parseInt(tokenVersionAsString, 10)
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return { sealWithoutVersion: seal2, tokenVersion: null };
|
|
194
|
+
}
|
|
195
|
+
function createSealData(_crypto2) {
|
|
196
|
+
return async (data, {
|
|
197
|
+
password,
|
|
198
|
+
ttl = fourteenDaysInSeconds
|
|
199
|
+
}) => {
|
|
200
|
+
const passwordsAsMap = normalizeStringPasswordToMap(password);
|
|
201
|
+
const mostRecentPasswordId = Math.max(
|
|
202
|
+
...Object.keys(passwordsAsMap).map((id) => parseInt(id, 10))
|
|
203
|
+
);
|
|
204
|
+
const passwordForSeal = {
|
|
205
|
+
id: mostRecentPasswordId.toString(),
|
|
206
|
+
secret: passwordsAsMap[mostRecentPasswordId]
|
|
207
|
+
};
|
|
208
|
+
const seal2 = await Iron.seal(_crypto2, data, passwordForSeal, {
|
|
209
|
+
...Iron.defaults,
|
|
210
|
+
ttl: ttl * 1e3
|
|
211
|
+
});
|
|
212
|
+
return `${seal2}${versionDelimiter}${currentMajorVersion}`;
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
function normalizeStringPasswordToMap(password) {
|
|
216
|
+
return typeof password === "string" ? { 1: password } : password;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// edge/index.ts
|
|
220
|
+
var getCrypto = () => {
|
|
221
|
+
var _a, _b, _c;
|
|
222
|
+
if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.subtle) === "object")
|
|
223
|
+
return globalThis.crypto;
|
|
224
|
+
if (typeof ((_c = (_b = globalThis.crypto) == null ? void 0 : _b.webcrypto) == null ? void 0 : _c.subtle) === "object")
|
|
225
|
+
return globalThis.crypto.webcrypto;
|
|
226
|
+
throw new Error(
|
|
227
|
+
"no native implementation of WebCrypto is available in current context"
|
|
228
|
+
);
|
|
229
|
+
};
|
|
230
|
+
var _crypto = getCrypto();
|
|
231
|
+
var unsealData = createUnsealData(_crypto);
|
|
232
|
+
var sealData = createSealData(_crypto);
|
|
233
|
+
var getIronSession = createGetIronSession(
|
|
234
|
+
_crypto,
|
|
235
|
+
unsealData,
|
|
236
|
+
sealData
|
|
237
|
+
);
|
|
238
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
239
|
+
0 && (module.exports = {
|
|
240
|
+
getIronSession,
|
|
241
|
+
sealData,
|
|
242
|
+
unsealData
|
|
243
|
+
});
|
|
244
|
+
//# sourceMappingURL=index.js.map
|