iron-session 2.0.0-alpha.9 → 6.0.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/dist/index.d.ts CHANGED
@@ -1,29 +1,64 @@
1
1
  import { CookieSerializeOptions } from 'cookie';
2
2
  import { IncomingMessage, ServerResponse } from 'http';
3
3
 
4
- declare type password = string | {
5
- id: number;
6
- password: string;
7
- }[];
4
+ declare type passwordsMap = {
5
+ [id: string]: string;
6
+ };
7
+ declare type password = string | passwordsMap;
8
8
  interface IronSessionOptions {
9
+ /**
10
+ * This is the cookie name that will be used inside the browser. You should make sure it's unique given
11
+ * your application. Example: vercel-session
12
+ */
9
13
  cookieName: string;
14
+ /**
15
+ * This is the password(s) that will be used to encrypt the cookie. It can be either a string or an object
16
+ * like {1: "password", 2: password}.
17
+ *
18
+ * When you provide multiple passwords then all of them will be used to decrypt the cookie and only the most
19
+ * recent (= highest key, 2 in this example) password will be used to encrypt the cookie. This allow you
20
+ * to use password rotation (security)
21
+ */
10
22
  password: password;
23
+ /**
24
+ * This is the time in seconds that the session will be valid for. This also set the max-age attribute of
25
+ * the cookie automatically (minus 60 seconds so that the cookie always expire before the session).
26
+ */
11
27
  ttl?: number;
28
+ /**
29
+ * This is the options that will be passed to the cookie library.
30
+ * You can see all of them here: https://github.com/jshttp/cookie#options-1.
31
+ *
32
+ * If you want to use "session cookies" (cookies that are deleted when the browser is closed) then you need
33
+ * to pass cookieOptions: { maxAge: undefined }.
34
+ */
12
35
  cookieOptions?: CookieSerializeOptions;
13
36
  }
14
- interface IronSession {
15
- set: <T = unknown>(name: string, value: T) => T;
16
- get: <T = unknown>(name: string) => T | undefined;
17
- unset: (name: string) => void;
37
+ interface IronSessionData {
38
+ }
39
+ declare type IronSession = IronSessionData & {
40
+ /**
41
+ * Destroys the session data and removes the cookie.
42
+ */
18
43
  destroy: () => void;
19
- save: () => Promise<string>;
44
+ /**
45
+ * Encrypts the session data and sets the cookie.
46
+ */
47
+ save: () => Promise<void>;
48
+ };
49
+ declare module "http" {
50
+ interface IncomingMessage {
51
+ session: IronSession;
52
+ }
20
53
  }
21
- declare function getIronSession<RequestType extends IncomingMessage, ResponseType extends ServerResponse>(req: RequestType, res: ResponseType, userOptions: IronSessionOptions): Promise<{
22
- set: <T = any>(name: string, value: T) => T;
23
- get: (name?: string | undefined) => any;
24
- unset: (name: string) => void;
25
- save(): Promise<string>;
26
- destroy(): void;
27
- }>;
54
+ declare function getIronSession(req: IncomingMessage, res: ServerResponse, userSessionOptions: IronSessionOptions): Promise<IronSession>;
55
+ declare function unsealData<T = Record<string, unknown>>(seal: string, { password, ttl, }: {
56
+ password: password;
57
+ ttl?: number;
58
+ }): Promise<T>;
59
+ declare function sealData(data: unknown, { password, ttl, }: {
60
+ password: password;
61
+ ttl?: number;
62
+ }): Promise<string>;
28
63
 
29
- export { IronSession, IronSessionOptions, getIronSession };
64
+ export { IronSession, IronSessionData, IronSessionOptions, getIronSession, sealData, unsealData };
package/dist/index.js CHANGED
@@ -1,9 +1,41 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __export = (target, all) => {
9
+ __markAsModule(target);
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __reExport = (target, module2, desc) => {
14
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
15
+ for (let key of __getOwnPropNames(module2))
16
+ if (!__hasOwnProp.call(target, key) && key !== "default")
17
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
18
+ }
19
+ return target;
20
+ };
21
+ var __toModule = (module2) => {
22
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
23
+ };
24
+
1
25
  // src/index.ts
2
- import ironStore from "iron-store";
3
- import cookie from "cookie";
26
+ __export(exports, {
27
+ getIronSession: () => getIronSession,
28
+ sealData: () => sealData,
29
+ unsealData: () => unsealData
30
+ });
31
+ var import_iron = __toModule(require("@hapi/iron"));
32
+ var import_cookie = __toModule(require("cookie"));
4
33
  var timestampSkewSec = 60;
34
+ var fourteenDaysInSeconds = 15 * 24 * 3600;
35
+ var currentMajorVersion = 2;
36
+ var versionDelimiter = "~";
5
37
  var defaultOptions = {
6
- ttl: 15 * 24 * 3600,
38
+ ttl: fourteenDaysInSeconds,
7
39
  cookieOptions: {
8
40
  httpOnly: true,
9
41
  secure: true,
@@ -11,56 +43,77 @@ var defaultOptions = {
11
43
  path: "/"
12
44
  }
13
45
  };
14
- async function getIronSession(req, res, userOptions) {
15
- var _a, _b;
16
- if (!req || !res || !userOptions || !userOptions.cookieName || !userOptions.password) {
46
+ async function getIronSession(req, res, userSessionOptions) {
47
+ var _a;
48
+ if (!req || !res || !userSessionOptions || !userSessionOptions.cookieName || !userSessionOptions.password) {
17
49
  throw new Error(`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`);
18
50
  }
19
- const passwordAsAnArray = Array.isArray(userOptions.password) ? userOptions.password : [{ id: 1, password: userOptions.password }];
20
- passwordAsAnArray.forEach(({ password }) => {
51
+ const passwordsAsMap = normalizeStringPasswordToMap(userSessionOptions.password);
52
+ Object.values(normalizeStringPasswordToMap(userSessionOptions.password)).forEach((password) => {
21
53
  if (password.length < 32) {
22
54
  throw new Error(`iron-session: Bad usage. Password must be at least 32 characters long.`);
23
55
  }
24
56
  });
25
57
  const options = {
26
58
  ...defaultOptions,
27
- ...userOptions,
59
+ ...userSessionOptions,
28
60
  cookieOptions: {
29
61
  ...defaultOptions.cookieOptions,
30
- ...userOptions.cookieOptions || {}
62
+ ...userSessionOptions.cookieOptions || {}
31
63
  }
32
64
  };
65
+ if (((_a = userSessionOptions.cookieOptions) == null ? void 0 : _a.secure) === void 0) {
66
+ const isHttps = req.socket.encrypted === true;
67
+ options.cookieOptions.secure = isHttps;
68
+ }
33
69
  if (options.ttl === 0) {
34
70
  options.ttl = 2147483647;
35
71
  }
36
- options.cookieOptions.maxAge = computeCookieMaxAge((_b = (_a = userOptions.cookieOptions) == null ? void 0 : _a.maxAge) != null ? _b : options.ttl);
37
- const store = await getOrCreateStore({
38
- sealed: cookie.parse(req.headers.cookie || "")[options.cookieName],
39
- password: passwordAsAnArray,
40
- ttl: options.ttl * 1e3
72
+ if (userSessionOptions.cookieOptions && "maxAge" in userSessionOptions.cookieOptions) {
73
+ if (userSessionOptions.cookieOptions.maxAge === void 0) {
74
+ options.ttl = 0;
75
+ } else {
76
+ options.cookieOptions.maxAge = computeCookieMaxAge(userSessionOptions.cookieOptions.maxAge);
77
+ }
78
+ } else {
79
+ options.cookieOptions.maxAge = computeCookieMaxAge(options.ttl);
80
+ }
81
+ const sealFromCookies = (0, import_cookie.parse)(req.headers.cookie || "")[options.cookieName];
82
+ const session = sealFromCookies === void 0 ? {} : await unsealData(sealFromCookies, {
83
+ password: passwordsAsMap,
84
+ ttl: options.ttl
41
85
  });
42
- return {
43
- set: store.set,
44
- get: store.get,
45
- unset: store.unset,
46
- async save() {
47
- const seal = await store.seal();
48
- const cookieValue = cookie.serialize(options.cookieName, seal, options.cookieOptions);
49
- if (cookieValue.length > 4096) {
50
- throw new Error(`iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it. Try to remove some data.`);
86
+ Object.defineProperties(session, {
87
+ save: {
88
+ value: async function save() {
89
+ if (res.headersSent === true) {
90
+ 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()`);
91
+ }
92
+ const seal = await sealData(session, {
93
+ password: passwordsAsMap,
94
+ ttl: options.ttl
95
+ });
96
+ const cookieValue = (0, import_cookie.serialize)(options.cookieName, seal, options.cookieOptions);
97
+ if (cookieValue.length > 4096) {
98
+ throw new Error(`iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it. Try to remove some data.`);
99
+ }
100
+ addToCookies(cookieValue, res);
51
101
  }
52
- addToCookies(cookieValue, res);
53
- return cookieValue;
54
102
  },
55
- destroy() {
56
- store.clear();
57
- const cookieValue = cookie.serialize(options.cookieName, "", {
58
- ...options.cookieOptions,
59
- maxAge: 0
60
- });
61
- addToCookies(cookieValue, res);
103
+ destroy: {
104
+ value: function destroy() {
105
+ Object.keys(session).forEach((key) => {
106
+ delete session[key];
107
+ });
108
+ const cookieValue = (0, import_cookie.serialize)(options.cookieName, "", {
109
+ ...options.cookieOptions,
110
+ maxAge: 0
111
+ });
112
+ addToCookies(cookieValue, res);
113
+ }
62
114
  }
63
- };
115
+ });
116
+ return session;
64
117
  }
65
118
  function addToCookies(cookieValue, res) {
66
119
  var _a;
@@ -73,27 +126,65 @@ function addToCookies(cookieValue, res) {
73
126
  function computeCookieMaxAge(ttl) {
74
127
  return ttl - timestampSkewSec;
75
128
  }
76
- async function getOrCreateStore({
77
- sealed,
129
+ async function unsealData(seal, {
78
130
  password,
79
- ttl
131
+ ttl = fourteenDaysInSeconds
80
132
  }) {
133
+ const passwordsAsMap = normalizeStringPasswordToMap(password);
134
+ const { sealWithoutVersion, tokenVersion } = parseSeal(seal);
81
135
  try {
82
- return await ironStore({
83
- sealed,
84
- password,
85
- ttl
136
+ const data = await import_iron.default.unseal(sealWithoutVersion, passwordsAsMap, {
137
+ ...import_iron.default.defaults,
138
+ ttl: ttl * 1e3
86
139
  });
140
+ if (tokenVersion === 2) {
141
+ return data;
142
+ }
143
+ return {
144
+ ...data.persistent
145
+ };
87
146
  } catch (error) {
88
147
  if (error instanceof Error) {
89
- if (error.message === "Expired seal" || error.message === "Bad hmac value" || error.message === "Cannot find password: ") {
90
- return await ironStore({ password, ttl });
148
+ if (error.message === "Expired seal" || error.message === "Bad hmac value" || error.message === "Cannot find password: " || error.message === "Incorrect number of sealed components") {
149
+ return {};
91
150
  }
92
151
  }
93
152
  throw error;
94
153
  }
95
154
  }
96
- export {
97
- getIronSession
98
- };
155
+ function parseSeal(seal) {
156
+ if (seal[seal.length - 2] === versionDelimiter) {
157
+ const [sealWithoutVersion, tokenVersionAsString] = seal.split(versionDelimiter);
158
+ return {
159
+ sealWithoutVersion,
160
+ tokenVersion: parseInt(tokenVersionAsString, 10)
161
+ };
162
+ }
163
+ return { sealWithoutVersion: seal, tokenVersion: null };
164
+ }
165
+ async function sealData(data, {
166
+ password,
167
+ ttl = fourteenDaysInSeconds
168
+ }) {
169
+ const passwordsAsMap = normalizeStringPasswordToMap(password);
170
+ const mostRecentPasswordId = Math.max(...Object.keys(passwordsAsMap).map((id) => parseInt(id, 10)));
171
+ const passwordForSeal = {
172
+ id: mostRecentPasswordId.toString(),
173
+ secret: passwordsAsMap[mostRecentPasswordId]
174
+ };
175
+ const seal = await import_iron.default.seal(data, passwordForSeal, {
176
+ ...import_iron.default.defaults,
177
+ ttl: ttl * 1e3
178
+ });
179
+ return `${seal}${versionDelimiter}${currentMajorVersion}`;
180
+ }
181
+ function normalizeStringPasswordToMap(password) {
182
+ return typeof password === "string" ? { 1: password } : password;
183
+ }
184
+ // Annotate the CommonJS export names for ESM import in node:
185
+ 0 && (module.exports = {
186
+ getIronSession,
187
+ sealData,
188
+ unsealData
189
+ });
99
190
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["import ironStore from \"iron-store\";\nimport cookie, { CookieSerializeOptions } 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 password = string | { id: number; password: string }[];\n\nconst defaultOptions: {\n ttl: number;\n cookieOptions: CookieSerializeOptions;\n} = {\n ttl: 15 * 24 * 3600,\n cookieOptions: {\n httpOnly: true,\n secure: true,\n sameSite: \"lax\",\n path: \"/\",\n },\n};\n\nexport interface IronSessionOptions {\n cookieName: string;\n password: password;\n ttl?: number;\n cookieOptions?: CookieSerializeOptions;\n}\n\nexport interface IronSession {\n set: <T = unknown>(name: string, value: T) => T;\n get: <T = unknown>(name: string) => T | undefined;\n unset: (name: string) => void;\n destroy: () => void;\n save: () => Promise<string>;\n}\n\nexport async function getIronSession<\n RequestType extends IncomingMessage,\n ResponseType extends ServerResponse,\n>(req: RequestType, res: ResponseType, userOptions: IronSessionOptions) {\n if (\n !req ||\n !res ||\n !userOptions ||\n !userOptions.cookieName ||\n !userOptions.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 passwordAsAnArray = Array.isArray(userOptions.password)\n ? userOptions.password\n : [{ id: 1, password: userOptions.password }];\n\n passwordAsAnArray.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 ...userOptions,\n cookieOptions: {\n ...defaultOptions.cookieOptions,\n ...(userOptions.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 options.cookieOptions.maxAge = computeCookieMaxAge(\n userOptions.cookieOptions?.maxAge ?? options.ttl,\n );\n\n const store = await getOrCreateStore({\n sealed: cookie.parse(req.headers.cookie || \"\")[options.cookieName],\n password: passwordAsAnArray,\n ttl: options.ttl * 1000,\n });\n\n return {\n set: store.set,\n get: store.get,\n unset: store.unset,\n async save() {\n const seal = await store.seal();\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 return cookieValue;\n },\n destroy() {\n store.clear();\n const cookieValue = cookie.serialize(options.cookieName, \"\", {\n ...options.cookieOptions,\n maxAge: 0,\n });\n addToCookies(cookieValue, res);\n },\n };\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\nasync function getOrCreateStore({\n sealed,\n password,\n ttl,\n}: {\n sealed: string;\n password: password;\n ttl: number;\n}) {\n try {\n return await ironStore({\n sealed,\n password,\n ttl,\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 ) {\n // if seal expired or\n // if seal is not valid (encrypted using a different password, when passwords are updated) or\n // if we can't find back the password in the seal\n // then we just start a new session over\n return await ironStore({ password, ttl });\n }\n }\n\n throw error;\n }\n}\n"],
5
- "mappings": ";AAAA;AACA;AAKA,IAAM,mBAAmB;AAIzB,IAAM,iBAGF;AAAA,EACF,KAAK,KAAK,KAAK;AAAA,EACf,eAAe;AAAA,IACb,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,UAAU;AAAA,I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;AAKhC,sBAAsB,aAAqB,KAAqB;AA7HhE;AA8HE,MAAI,oBACD,UAAI,UAAU,kBAAd,YAAqD;AACxD,MAAI,OAAO,sBAAsB,UAAU;AACzC,wBAAoB,CAAC;AAAA;AAEvB,MAAI,UAAU,cAAc,CAAC,GAAG,mBAAmB;AAAA;AAGrD,6BAA6B,KAAa;AAIxC,SAAO,MAAM;AAAA;AAGf,gCAAgC;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,GAKC;AACD,MAAI;AACF,WAAO,MAAM,UAAU;AAAA,MACrB;AAAA,MACA;AAAA,MACA;AAAA;AAAA,WAEK,OAAP;AACA,QAAI,iBAAiB,OAAO;AAC1B,UACE,MAAM,YAAY,kBAClB,MAAM,YAAY,oBAClB,MAAM,YAAY,0BAClB;AAKA,eAAO,MAAM,UAAU,EAAE,UAAU;AAAA;AAAA;AAIvC,UAAM;AAAA;AAAA;",
4
+ "sourcesContent": ["import Iron from \"@hapi/iron\";\nimport type { CookieSerializeOptions } from \"cookie\";\nimport { parse as parseCookie, serialize as serializeCookie } from \"cookie\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport type { TLSSocket } from \"tls\";\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 the user did not set the secure flag themselves, we automatically configure it\n if (userSessionOptions.cookieOptions?.secure === undefined) {\n const isHttps = (req.socket as TLSSocket).encrypted === true;\n\n options.cookieOptions.secure = isHttps;\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 = parseCookie(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 = serializeCookie(\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 = serializeCookie(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;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAiB;AAEjB,oBAAmE;AAMnE,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;AAlGxB;AAmGE,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;AAA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MAAM,oBAAK,KAAK,MAAM,iBAAiB;AAAA,OAC/C,oBAAK;AAAA,IACR,KAAK,MAAM;AAAA;AAGb,SAAO,GAAG,OAAO,mBAAmB;AAAA;AAGtC,sCAAsC,UAAoB;AACxD,SAAO,OAAO,aAAa,WAAW,EAAE,GAAG,aAAa;AAAA;",
6
6
  "names": []
7
7
  }
package/dist/index.mjs ADDED
@@ -0,0 +1,160 @@
1
+ // src/index.ts
2
+ import Iron from "@hapi/iron";
3
+ import { parse as parseCookie, serialize as serializeCookie } from "cookie";
4
+ var timestampSkewSec = 60;
5
+ var fourteenDaysInSeconds = 15 * 24 * 3600;
6
+ var currentMajorVersion = 2;
7
+ var versionDelimiter = "~";
8
+ var defaultOptions = {
9
+ ttl: fourteenDaysInSeconds,
10
+ cookieOptions: {
11
+ httpOnly: true,
12
+ secure: true,
13
+ sameSite: "lax",
14
+ path: "/"
15
+ }
16
+ };
17
+ async function getIronSession(req, res, userSessionOptions) {
18
+ var _a;
19
+ if (!req || !res || !userSessionOptions || !userSessionOptions.cookieName || !userSessionOptions.password) {
20
+ throw new Error(`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`);
21
+ }
22
+ const passwordsAsMap = normalizeStringPasswordToMap(userSessionOptions.password);
23
+ Object.values(normalizeStringPasswordToMap(userSessionOptions.password)).forEach((password) => {
24
+ if (password.length < 32) {
25
+ throw new Error(`iron-session: Bad usage. Password must be at least 32 characters long.`);
26
+ }
27
+ });
28
+ const options = {
29
+ ...defaultOptions,
30
+ ...userSessionOptions,
31
+ cookieOptions: {
32
+ ...defaultOptions.cookieOptions,
33
+ ...userSessionOptions.cookieOptions || {}
34
+ }
35
+ };
36
+ if (((_a = userSessionOptions.cookieOptions) == null ? void 0 : _a.secure) === void 0) {
37
+ const isHttps = req.socket.encrypted === true;
38
+ options.cookieOptions.secure = isHttps;
39
+ }
40
+ if (options.ttl === 0) {
41
+ options.ttl = 2147483647;
42
+ }
43
+ if (userSessionOptions.cookieOptions && "maxAge" in userSessionOptions.cookieOptions) {
44
+ if (userSessionOptions.cookieOptions.maxAge === void 0) {
45
+ options.ttl = 0;
46
+ } else {
47
+ options.cookieOptions.maxAge = computeCookieMaxAge(userSessionOptions.cookieOptions.maxAge);
48
+ }
49
+ } else {
50
+ options.cookieOptions.maxAge = computeCookieMaxAge(options.ttl);
51
+ }
52
+ const sealFromCookies = parseCookie(req.headers.cookie || "")[options.cookieName];
53
+ const session = sealFromCookies === void 0 ? {} : await unsealData(sealFromCookies, {
54
+ password: passwordsAsMap,
55
+ ttl: options.ttl
56
+ });
57
+ Object.defineProperties(session, {
58
+ save: {
59
+ value: async function save() {
60
+ if (res.headersSent === true) {
61
+ 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()`);
62
+ }
63
+ const seal = await sealData(session, {
64
+ password: passwordsAsMap,
65
+ ttl: options.ttl
66
+ });
67
+ const cookieValue = serializeCookie(options.cookieName, seal, options.cookieOptions);
68
+ if (cookieValue.length > 4096) {
69
+ throw new Error(`iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it. Try to remove some data.`);
70
+ }
71
+ addToCookies(cookieValue, res);
72
+ }
73
+ },
74
+ destroy: {
75
+ value: function destroy() {
76
+ Object.keys(session).forEach((key) => {
77
+ delete session[key];
78
+ });
79
+ const cookieValue = serializeCookie(options.cookieName, "", {
80
+ ...options.cookieOptions,
81
+ maxAge: 0
82
+ });
83
+ addToCookies(cookieValue, res);
84
+ }
85
+ }
86
+ });
87
+ return session;
88
+ }
89
+ function addToCookies(cookieValue, res) {
90
+ var _a;
91
+ let existingSetCookie = (_a = res.getHeader("set-cookie")) != null ? _a : [];
92
+ if (typeof existingSetCookie === "string") {
93
+ existingSetCookie = [existingSetCookie];
94
+ }
95
+ res.setHeader("set-cookie", [...existingSetCookie, cookieValue]);
96
+ }
97
+ function computeCookieMaxAge(ttl) {
98
+ return ttl - timestampSkewSec;
99
+ }
100
+ async function unsealData(seal, {
101
+ password,
102
+ ttl = fourteenDaysInSeconds
103
+ }) {
104
+ const passwordsAsMap = normalizeStringPasswordToMap(password);
105
+ const { sealWithoutVersion, tokenVersion } = parseSeal(seal);
106
+ try {
107
+ const data = await Iron.unseal(sealWithoutVersion, passwordsAsMap, {
108
+ ...Iron.defaults,
109
+ ttl: ttl * 1e3
110
+ });
111
+ if (tokenVersion === 2) {
112
+ return data;
113
+ }
114
+ return {
115
+ ...data.persistent
116
+ };
117
+ } catch (error) {
118
+ if (error instanceof Error) {
119
+ if (error.message === "Expired seal" || error.message === "Bad hmac value" || error.message === "Cannot find password: " || error.message === "Incorrect number of sealed components") {
120
+ return {};
121
+ }
122
+ }
123
+ throw error;
124
+ }
125
+ }
126
+ function parseSeal(seal) {
127
+ if (seal[seal.length - 2] === versionDelimiter) {
128
+ const [sealWithoutVersion, tokenVersionAsString] = seal.split(versionDelimiter);
129
+ return {
130
+ sealWithoutVersion,
131
+ tokenVersion: parseInt(tokenVersionAsString, 10)
132
+ };
133
+ }
134
+ return { sealWithoutVersion: seal, tokenVersion: null };
135
+ }
136
+ async function sealData(data, {
137
+ password,
138
+ ttl = fourteenDaysInSeconds
139
+ }) {
140
+ const passwordsAsMap = normalizeStringPasswordToMap(password);
141
+ const mostRecentPasswordId = Math.max(...Object.keys(passwordsAsMap).map((id) => parseInt(id, 10)));
142
+ const passwordForSeal = {
143
+ id: mostRecentPasswordId.toString(),
144
+ secret: passwordsAsMap[mostRecentPasswordId]
145
+ };
146
+ const seal = await Iron.seal(data, passwordForSeal, {
147
+ ...Iron.defaults,
148
+ ttl: ttl * 1e3
149
+ });
150
+ return `${seal}${versionDelimiter}${currentMajorVersion}`;
151
+ }
152
+ function normalizeStringPasswordToMap(password) {
153
+ return typeof password === "string" ? { 1: password } : password;
154
+ }
155
+ export {
156
+ getIronSession,
157
+ sealData,
158
+ unsealData
159
+ };
160
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["import Iron from \"@hapi/iron\";\nimport type { CookieSerializeOptions } from \"cookie\";\nimport { parse as parseCookie, serialize as serializeCookie } from \"cookie\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport type { TLSSocket } from \"tls\";\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 the user did not set the secure flag themselves, we automatically configure it\n if (userSessionOptions.cookieOptions?.secure === undefined) {\n const isHttps = (req.socket as TLSSocket).encrypted === true;\n\n options.cookieOptions.secure = isHttps;\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 = parseCookie(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 = serializeCookie(\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 = serializeCookie(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;AAMA,IAAM,mBAAmB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AAO;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
+ }
@@ -0,0 +1,6 @@
1
+ import { IronSessionOptions } from 'iron-session';
2
+ import { Request, Response, NextFunction } from 'express';
3
+
4
+ declare function ironSession(sessionOptions: IronSessionOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
5
+
6
+ export { ironSession };
@@ -0,0 +1,65 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __export = (target, all) => {
9
+ __markAsModule(target);
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __reExport = (target, module2, desc) => {
14
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
15
+ for (let key of __getOwnPropNames(module2))
16
+ if (!__hasOwnProp.call(target, key) && key !== "default")
17
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
18
+ }
19
+ return target;
20
+ };
21
+ var __toModule = (module2) => {
22
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
23
+ };
24
+
25
+ // express/index.ts
26
+ __export(exports, {
27
+ ironSession: () => ironSession
28
+ });
29
+ var import_iron_session = __toModule(require("iron-session"));
30
+
31
+ // src/getPropertyDescriptorForReqSession.ts
32
+ function getPropertyDescriptorForReqSession(session) {
33
+ return {
34
+ enumerable: true,
35
+ get() {
36
+ return session;
37
+ },
38
+ set(value) {
39
+ const keys = Object.keys(value);
40
+ const currentKeys = Object.keys(session);
41
+ currentKeys.forEach((key) => {
42
+ if (!keys.includes(key)) {
43
+ delete session[key];
44
+ }
45
+ });
46
+ keys.forEach((key) => {
47
+ session[key] = value[key];
48
+ });
49
+ }
50
+ };
51
+ }
52
+
53
+ // express/index.ts
54
+ function ironSession(sessionOptions) {
55
+ return async function ironSessionMiddleware(req, res, next) {
56
+ const session = await (0, import_iron_session.getIronSession)(req, res, sessionOptions);
57
+ Object.defineProperty(req, "session", getPropertyDescriptorForReqSession(session));
58
+ next();
59
+ };
60
+ }
61
+ // Annotate the CommonJS export names for ESM import in node:
62
+ 0 && (module.exports = {
63
+ ironSession
64
+ });
65
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../index.ts", "../../src/getPropertyDescriptorForReqSession.ts"],
4
+ "sourcesContent": ["import type { IronSessionOptions } from \"iron-session\";\nimport { getIronSession } from \"iron-session\";\nimport type { Request, Response, NextFunction } from \"express\";\nimport getPropertyDescriptorForReqSession from \"../src/getPropertyDescriptorForReqSession\";\n\nexport function ironSession(\n sessionOptions: IronSessionOptions,\n): (req: Request, res: Response, next: NextFunction) => Promise<void> {\n return async function ironSessionMiddleware(req, res, next) {\n const session = await getIronSession(req, res, sessionOptions);\n Object.defineProperty(\n req,\n \"session\",\n getPropertyDescriptorForReqSession(session),\n );\n\n next();\n };\n}\n", "import type { IronSession } from \".\";\n\nexport default function getPropertyDescriptorForReqSession(\n session: IronSession,\n): PropertyDescriptor {\n return {\n enumerable: true,\n get() {\n return session;\n },\n set(value) {\n const keys = Object.keys(value);\n const currentKeys = Object.keys(session);\n\n currentKeys.forEach((key) => {\n if (!keys.includes(key)) {\n // @ts-ignore See comment in IronSessionData interface\n delete session[key];\n }\n });\n\n keys.forEach((key) => {\n // @ts-ignore See comment in IronSessionData interface\n session[key] = value[key];\n });\n },\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AACA,0BAA+B;;;ACChB,4CACb,SACoB;AACpB,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,MAAM;AACJ,aAAO;AAAA;AAAA,IAET,IAAI,OAAO;AACT,YAAM,OAAO,OAAO,KAAK;AACzB,YAAM,cAAc,OAAO,KAAK;AAEhC,kBAAY,QAAQ,CAAC,QAAQ;AAC3B,YAAI,CAAC,KAAK,SAAS,MAAM;AAEvB,iBAAO,QAAQ;AAAA;AAAA;AAInB,WAAK,QAAQ,CAAC,QAAQ;AAEpB,gBAAQ,OAAO,MAAM;AAAA;AAAA;AAAA;AAAA;;;ADlBtB,qBACL,gBACoE;AACpE,SAAO,qCAAqC,KAAK,KAAK,MAAM;AAC1D,UAAM,UAAU,MAAM,wCAAe,KAAK,KAAK;AAC/C,WAAO,eACL,KACA,WACA,mCAAmC;AAGrC;AAAA;AAAA;",
6
+ "names": []
7
+ }