iron-session 2.0.0-alpha.1 → 2.0.0-alpha.10

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,5 +1,5 @@
1
- import { NextApiRequest, NextApiResponse, GetServerSidePropsResult, GetServerSidePropsContext } from 'next';
2
1
  import { CookieSerializeOptions } from 'cookie';
2
+ import { IncomingMessage, ServerResponse } from 'http';
3
3
 
4
4
  declare type password = string | {
5
5
  id: number;
@@ -18,16 +18,12 @@ interface IronSession {
18
18
  destroy: () => void;
19
19
  save: () => Promise<string>;
20
20
  }
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
+ }>;
21
28
 
22
- interface NextApiRequestWithIronSession extends NextApiRequest {
23
- session: IronSession;
24
- }
25
- declare type NextApiHandlerWithIronSession<T = unknown> = (req: NextApiRequestWithIronSession, res: NextApiResponse<T>) => void | Promise<void>;
26
- interface NextGetSeverSideContextWithIronSession extends GetServerSidePropsContext {
27
- req: NextApiRequestWithIronSession;
28
- }
29
- declare type NextGetServerSidePropsHandlerWithIronSession<P> = (context: NextGetSeverSideContextWithIronSession) => Promise<GetServerSidePropsResult<P>>;
30
- declare function withIronSessionApiRoute(handler: NextApiHandlerWithIronSession, options: IronSessionOptions): NextApiHandlerWithIronSession;
31
- declare function withIronSessionSsr<P>(handler: NextGetServerSidePropsHandlerWithIronSession<P>, options: IronSessionOptions): NextGetServerSidePropsHandlerWithIronSession<P>;
32
-
33
- export { NextApiHandlerWithIronSession, NextApiRequestWithIronSession, NextGetServerSidePropsHandlerWithIronSession, withIronSessionApiRoute, withIronSessionSsr };
29
+ export { IronSession, IronSessionOptions, getIronSession };
package/dist/index.js CHANGED
@@ -1,2 +1,127 @@
1
- var x=Object.create;var c=Object.defineProperty,O=Object.defineProperties,T=Object.getOwnPropertyDescriptor,C=Object.getOwnPropertyDescriptors,b=Object.getOwnPropertyNames,u=Object.getOwnPropertySymbols,A=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable;var f=(e,s,o)=>s in e?c(e,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[s]=o,r=(e,s)=>{for(var o in s||(s={}))w.call(s,o)&&f(e,o,s[o]);if(u)for(var o of u(s))I.call(s,o)&&f(e,o,s[o]);return e},d=(e,s)=>O(e,C(s)),h=e=>c(e,"__esModule",{value:!0});var R=(e,s)=>{h(e);for(var o in s)c(e,o,{get:s[o],enumerable:!0})},E=(e,s,o)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of b(s))!w.call(e,t)&&t!=="default"&&c(e,t,{get:()=>s[t],enumerable:!(o=T(s,t))||o.enumerable});return e},y=e=>E(h(c(e!=null?x(A(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);R(exports,{getIronSession:()=>z});var m=y(require("iron-store")),g=y(require("cookie")),N=60,S={ttl:15*24*3600,cookieOptions:{httpOnly:!0,secure:!0,sameSite:"lax",path:"/"}};async function z(e,s,o){var l,k;if(!e||!s||!o||!o.cookieName||!o.password)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');let t=Array.isArray(o.password)?o.password:[{id:1,password:o.password}];t.forEach(({password:a})=>{if(a.length<32)throw new Error("iron-session: Bad usage. Password must be at least 32 characters long.")});let i=d(r(r({},S),o),{cookieOptions:r(r({},S.cookieOptions),o.cookieOptions||{})});i.ttl===0&&(i.ttl=2147483647),i.cookieOptions.maxAge=M((k=(l=o.cookieOptions)==null?void 0:l.maxAge)!=null?k:i.ttl);let n=await q({sealed:g.default.parse(e.headers.cookie||"")[i.cookieName],password:t,ttl:i.ttl*1e3});return{set:n.set,get:n.get,unset:n.unset,async save(){let a=await n.seal(),p=g.default.serialize(i.cookieName,a,i.cookieOptions);if(p.length>4096)throw new Error(`iron-session: Cookie length is too big ${p.length}, browsers will refuse it. Try to remove some data.`);return v(p,s),p},destroy(){n.clear();let a=g.default.serialize(i.cookieName,"",d(r({},i.cookieOptions),{maxAge:0}));v(a,s)}}}function v(e,s){var t;let o=(t=s.getHeader("set-cookie"))!=null?t:[];typeof o=="string"&&(o=[o]),s.setHeader("set-cookie",[...o,e])}function M(e){return e-N}async function q({sealed:e,password:s,ttl:o}){try{return await(0,m.default)({sealed:e,password:s,ttl:o})}catch(t){if(t instanceof Error&&(t.message==="Expired seal"||t.message==="Bad hmac value"||t.message==="Cannot find password: "))return await(0,m.default)({password:s,ttl:o});throw t}}0&&(module.exports={getIronSession});
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
+ // src/index.ts
26
+ __export(exports, {
27
+ getIronSession: () => getIronSession
28
+ });
29
+ var import_iron_store = __toModule(require("iron-store"));
30
+ var import_cookie = __toModule(require("cookie"));
31
+ var timestampSkewSec = 60;
32
+ var defaultOptions = {
33
+ ttl: 15 * 24 * 3600,
34
+ cookieOptions: {
35
+ httpOnly: true,
36
+ secure: true,
37
+ sameSite: "lax",
38
+ path: "/"
39
+ }
40
+ };
41
+ async function getIronSession(req, res, userOptions) {
42
+ var _a, _b;
43
+ if (!req || !res || !userOptions || !userOptions.cookieName || !userOptions.password) {
44
+ 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`);
45
+ }
46
+ const passwordAsAnArray = Array.isArray(userOptions.password) ? userOptions.password : [{ id: 1, password: userOptions.password }];
47
+ passwordAsAnArray.forEach(({ password }) => {
48
+ if (password.length < 32) {
49
+ throw new Error(`iron-session: Bad usage. Password must be at least 32 characters long.`);
50
+ }
51
+ });
52
+ const options = {
53
+ ...defaultOptions,
54
+ ...userOptions,
55
+ cookieOptions: {
56
+ ...defaultOptions.cookieOptions,
57
+ ...userOptions.cookieOptions || {}
58
+ }
59
+ };
60
+ if (options.ttl === 0) {
61
+ options.ttl = 2147483647;
62
+ }
63
+ options.cookieOptions.maxAge = computeCookieMaxAge((_b = (_a = userOptions.cookieOptions) == null ? void 0 : _a.maxAge) != null ? _b : options.ttl);
64
+ const store = await getOrCreateStore({
65
+ sealed: import_cookie.default.parse(req.headers.cookie || "")[options.cookieName],
66
+ password: passwordAsAnArray,
67
+ ttl: options.ttl * 1e3
68
+ });
69
+ return {
70
+ set: store.set,
71
+ get: store.get,
72
+ unset: store.unset,
73
+ async save() {
74
+ const seal = await store.seal();
75
+ const cookieValue = import_cookie.default.serialize(options.cookieName, seal, options.cookieOptions);
76
+ if (cookieValue.length > 4096) {
77
+ throw new Error(`iron-session: Cookie length is too big ${cookieValue.length}, browsers will refuse it. Try to remove some data.`);
78
+ }
79
+ addToCookies(cookieValue, res);
80
+ return cookieValue;
81
+ },
82
+ destroy() {
83
+ store.clear();
84
+ const cookieValue = import_cookie.default.serialize(options.cookieName, "", {
85
+ ...options.cookieOptions,
86
+ maxAge: 0
87
+ });
88
+ addToCookies(cookieValue, res);
89
+ }
90
+ };
91
+ }
92
+ function addToCookies(cookieValue, res) {
93
+ var _a;
94
+ let existingSetCookie = (_a = res.getHeader("set-cookie")) != null ? _a : [];
95
+ if (typeof existingSetCookie === "string") {
96
+ existingSetCookie = [existingSetCookie];
97
+ }
98
+ res.setHeader("set-cookie", [...existingSetCookie, cookieValue]);
99
+ }
100
+ function computeCookieMaxAge(ttl) {
101
+ return ttl - timestampSkewSec;
102
+ }
103
+ async function getOrCreateStore({
104
+ sealed,
105
+ password,
106
+ ttl
107
+ }) {
108
+ try {
109
+ return await (0, import_iron_store.default)({
110
+ sealed,
111
+ password,
112
+ ttl
113
+ });
114
+ } catch (error) {
115
+ if (error instanceof Error) {
116
+ if (error.message === "Expired seal" || error.message === "Bad hmac value" || error.message === "Cannot find password: ") {
117
+ return await (0, import_iron_store.default)({ password, ttl });
118
+ }
119
+ }
120
+ throw error;
121
+ }
122
+ }
123
+ // Annotate the CommonJS export names for ESM import in node:
124
+ 0 && (module.exports = {
125
+ getIronSession
126
+ });
2
127
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
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": "s6BAAA,kCAAA,MAAsB,yBACtB,EAA+C,qBAKzC,EAAmB,GAInB,EAGF,CACF,IAAK,GAAK,GAAK,KACf,cAAe,CACb,SAAU,GACV,OAAQ,GACR,SAAU,MACV,KAAM,MAmBV,iBAGE,EAAkB,EAAmB,EAAiC,CAzCxE,QA0CE,GACE,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,EAAY,YACb,CAAC,EAAY,SAEb,KAAM,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M,MAAM;AACzB,YAAM,cAAc,sBAAO,UACzB,QAAQ,YACR,MACA,QAAQ;AAGV,UAAI,YAAY,SAAS,MAAM;AAC7B,cAAM,IAAI,MACR,0CAA0C,YAAY;AAAA;AAI1D,mBAAa,aAAa;AAC1B,aAAO;AAAA;AAAA,IAET,UAAU;AACR,YAAM;AACN,YAAM,cAAc,sBAAO,UAAU,QAAQ,YAAY,IAAI;AAAA,WACxD,QAAQ;AAAA,QACX,QAAQ;AAAA;AAEV,mBAAa,aAAa;AAAA;AAAA;AAAA;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,+BAAU;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,+BAAU,EAAE,UAAU;AAAA;AAAA;AAIvC,UAAM;AAAA;AAAA;",
6
6
  "names": []
7
7
  }
package/dist/index.mjs CHANGED
@@ -1,2 +1,99 @@
1
- var h=Object.defineProperty,y=Object.defineProperties;var S=Object.getOwnPropertyDescriptors;var l=Object.getOwnPropertySymbols;var v=Object.prototype.hasOwnProperty,x=Object.prototype.propertyIsEnumerable;var k=(s,o,e)=>o in s?h(s,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[o]=e,r=(s,o)=>{for(var e in o||(o={}))v.call(o,e)&&k(s,e,o[e]);if(l)for(var e of l(o))x.call(o,e)&&k(s,e,o[e]);return s},p=(s,o)=>y(s,S(o));import u from"iron-store";import g from"cookie";var O=60,w={ttl:15*24*3600,cookieOptions:{httpOnly:!0,secure:!0,sameSite:"lax",path:"/"}};async function E(s,o,e){var d,m;if(!s||!o||!e||!e.cookieName||!e.password)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');let t=Array.isArray(e.password)?e.password:[{id:1,password:e.password}];t.forEach(({password:a})=>{if(a.length<32)throw new Error("iron-session: Bad usage. Password must be at least 32 characters long.")});let i=p(r(r({},w),e),{cookieOptions:r(r({},w.cookieOptions),e.cookieOptions||{})});i.ttl===0&&(i.ttl=2147483647),i.cookieOptions.maxAge=T((m=(d=e.cookieOptions)==null?void 0:d.maxAge)!=null?m:i.ttl);let n=await C({sealed:g.parse(s.headers.cookie||"")[i.cookieName],password:t,ttl:i.ttl*1e3});return{set:n.set,get:n.get,unset:n.unset,async save(){let a=await n.seal(),c=g.serialize(i.cookieName,a,i.cookieOptions);if(c.length>4096)throw new Error(`iron-session: Cookie length is too big ${c.length}, browsers will refuse it. Try to remove some data.`);return f(c,o),c},destroy(){n.clear();let a=g.serialize(i.cookieName,"",p(r({},i.cookieOptions),{maxAge:0}));f(a,o)}}}function f(s,o){var t;let e=(t=o.getHeader("set-cookie"))!=null?t:[];typeof e=="string"&&(e=[e]),o.setHeader("set-cookie",[...e,s])}function T(s){return s-O}async function C({sealed:s,password:o,ttl:e}){try{return await u({sealed:s,password:o,ttl:e})}catch(t){if(t instanceof Error&&(t.message==="Expired seal"||t.message==="Bad hmac value"||t.message==="Cannot find password: "))return await u({password:o,ttl:e});throw t}}export{E as getIronSession};
1
+ // src/index.ts
2
+ import ironStore from "iron-store";
3
+ import cookie from "cookie";
4
+ var timestampSkewSec = 60;
5
+ var defaultOptions = {
6
+ ttl: 15 * 24 * 3600,
7
+ cookieOptions: {
8
+ httpOnly: true,
9
+ secure: true,
10
+ sameSite: "lax",
11
+ path: "/"
12
+ }
13
+ };
14
+ async function getIronSession(req, res, userOptions) {
15
+ var _a, _b;
16
+ if (!req || !res || !userOptions || !userOptions.cookieName || !userOptions.password) {
17
+ 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
+ }
19
+ const passwordAsAnArray = Array.isArray(userOptions.password) ? userOptions.password : [{ id: 1, password: userOptions.password }];
20
+ passwordAsAnArray.forEach(({ password }) => {
21
+ if (password.length < 32) {
22
+ throw new Error(`iron-session: Bad usage. Password must be at least 32 characters long.`);
23
+ }
24
+ });
25
+ const options = {
26
+ ...defaultOptions,
27
+ ...userOptions,
28
+ cookieOptions: {
29
+ ...defaultOptions.cookieOptions,
30
+ ...userOptions.cookieOptions || {}
31
+ }
32
+ };
33
+ if (options.ttl === 0) {
34
+ options.ttl = 2147483647;
35
+ }
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
41
+ });
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.`);
51
+ }
52
+ addToCookies(cookieValue, res);
53
+ return cookieValue;
54
+ },
55
+ destroy() {
56
+ store.clear();
57
+ const cookieValue = cookie.serialize(options.cookieName, "", {
58
+ ...options.cookieOptions,
59
+ maxAge: 0
60
+ });
61
+ addToCookies(cookieValue, res);
62
+ }
63
+ };
64
+ }
65
+ function addToCookies(cookieValue, res) {
66
+ var _a;
67
+ let existingSetCookie = (_a = res.getHeader("set-cookie")) != null ? _a : [];
68
+ if (typeof existingSetCookie === "string") {
69
+ existingSetCookie = [existingSetCookie];
70
+ }
71
+ res.setHeader("set-cookie", [...existingSetCookie, cookieValue]);
72
+ }
73
+ function computeCookieMaxAge(ttl) {
74
+ return ttl - timestampSkewSec;
75
+ }
76
+ async function getOrCreateStore({
77
+ sealed,
78
+ password,
79
+ ttl
80
+ }) {
81
+ try {
82
+ return await ironStore({
83
+ sealed,
84
+ password,
85
+ ttl
86
+ });
87
+ } catch (error) {
88
+ 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 });
91
+ }
92
+ }
93
+ throw error;
94
+ }
95
+ }
96
+ export {
97
+ getIronSession
98
+ };
2
99
  //# sourceMappingURL=index.mjs.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
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": "6aAAA,0BACA,sBAKA,GAAM,GAAmB,GAInB,EAGF,CACF,IAAK,GAAK,GAAK,KACf,cAAe,CACb,SAAU,GACV,OAAQ,GACR,SAAU,MACV,KAAM,MAmBV,iBAGE,EAAkB,EAAmB,EAAiC,CAzCxE,QA0CE,GACE,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,EAAY,YACb,CAAC,EAAY,SAEb,KAAM,IAAI,OACR,4LAIJ,GAAM,GAAoB,MAAM,QAAQ,EAAY,UAChD,EAAY,SACZ,CAAC,CAAE,GAAI,EAAG,SAAU,EAAY,WAEpC,EAAkB,QAAQ,CAAC,CAAE,cAAe,CAC1C,GAAI,EAAS,OAAS,GACpB,KAAM,IAAI,OACR,4EAKN,GAAM,GAAwC,SACzC,GACA,GAFyC,CAG5C,cAAe,OACV,EAAe,eACd,EAAY,eAAiB,MAIrC,AAAI,EAAQ,MAAQ,GAKlB,GAAQ,IAAM,YAGhB,EAAQ,cAAc,OAAS,EAC7B,QAAY,gBAAZ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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;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,15 @@
1
+ import { NextApiRequest, NextApiResponse, GetServerSidePropsResult, GetServerSidePropsContext } from 'next';
2
+ import { IronSession, IronSessionOptions } from 'iron-session';
3
+
4
+ interface NextApiRequestWithIronSession extends NextApiRequest {
5
+ session: IronSession;
6
+ }
7
+ declare type NextApiHandlerWithIronSession<T = unknown> = (req: NextApiRequestWithIronSession, res: NextApiResponse<T>) => void | Promise<void>;
8
+ interface NextGetSeverSideContextWithIronSession extends GetServerSidePropsContext {
9
+ req: NextApiRequestWithIronSession;
10
+ }
11
+ declare type NextGetServerSidePropsHandlerWithIronSession<P> = (context: NextGetSeverSideContextWithIronSession) => Promise<GetServerSidePropsResult<P>>;
12
+ declare function withIronSessionApiRoute(handler: NextApiHandlerWithIronSession, options: IronSessionOptions): NextApiHandlerWithIronSession;
13
+ declare function withIronSessionSsr<P>(handler: NextGetServerSidePropsHandlerWithIronSession<P>, options: IronSessionOptions): NextGetServerSidePropsHandlerWithIronSession<P>;
14
+
15
+ export { NextApiHandlerWithIronSession, NextApiRequestWithIronSession, NextGetServerSidePropsHandlerWithIronSession, withIronSessionApiRoute, withIronSessionSsr };
@@ -0,0 +1,48 @@
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
+ // next/index.ts
26
+ __export(exports, {
27
+ withIronSessionApiRoute: () => withIronSessionApiRoute,
28
+ withIronSessionSsr: () => withIronSessionSsr
29
+ });
30
+ var import_iron_session = __toModule(require("iron-session"));
31
+ function withIronSessionApiRoute(handler, options) {
32
+ return async function nextApiHandlerWrappedWithIronSession(req, res) {
33
+ req.session = await (0, import_iron_session.getIronSession)(req, res, options);
34
+ return handler(req, res);
35
+ };
36
+ }
37
+ function withIronSessionSsr(handler, options) {
38
+ return async function nextGetServerSidePropsHandlerWrappedWithIronSession(context) {
39
+ context.req.session = await (0, import_iron_session.getIronSession)(context.req, context.res, options);
40
+ return handler(context);
41
+ };
42
+ }
43
+ // Annotate the CommonJS export names for ESM import in node:
44
+ 0 && (module.exports = {
45
+ withIronSessionApiRoute,
46
+ withIronSessionSsr
47
+ });
48
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../index.ts"],
4
+ "sourcesContent": ["import type {\n GetServerSidePropsContext,\n GetServerSidePropsResult,\n NextApiRequest,\n NextApiResponse,\n} from \"next\";\nimport type { IronSession, IronSessionOptions } from \"iron-session\";\nimport { getIronSession } from \"iron-session\";\n\nexport interface NextApiRequestWithIronSession extends NextApiRequest {\n session: IronSession;\n}\n\nexport declare type NextApiHandlerWithIronSession<T = unknown> = (\n req: NextApiRequestWithIronSession,\n res: NextApiResponse<T>,\n) => void | Promise<void>;\n\ninterface NextGetSeverSideContextWithIronSession\n extends GetServerSidePropsContext {\n req: NextApiRequestWithIronSession;\n}\n\nexport declare type NextGetServerSidePropsHandlerWithIronSession<P> = (\n context: NextGetSeverSideContextWithIronSession,\n) => Promise<GetServerSidePropsResult<P>>;\n\nexport function withIronSessionApiRoute(\n handler: NextApiHandlerWithIronSession,\n options: IronSessionOptions,\n): NextApiHandlerWithIronSession {\n return async function nextApiHandlerWrappedWithIronSession(req, res) {\n req.session = await getIronSession(req, res, options);\n return handler(req, res);\n };\n}\n\nexport function withIronSessionSsr<P>(\n handler: NextGetServerSidePropsHandlerWithIronSession<P>,\n options: IronSessionOptions,\n): NextGetServerSidePropsHandlerWithIronSession<P> {\n return async function nextGetServerSidePropsHandlerWrappedWithIronSession(\n context: NextGetSeverSideContextWithIronSession,\n ) {\n context.req.session = await getIronSession(\n context.req,\n context.res,\n options,\n );\n return handler(context);\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAOA,0BAA+B;AAoBxB,iCACL,SACA,SAC+B;AAC/B,SAAO,oDAAoD,KAAK,KAAK;AACnE,QAAI,UAAU,MAAM,wCAAe,KAAK,KAAK;AAC7C,WAAO,QAAQ,KAAK;AAAA;AAAA;AAIjB,4BACL,SACA,SACiD;AACjD,SAAO,mEACL,SACA;AACA,YAAQ,IAAI,UAAU,MAAM,wCAC1B,QAAQ,KACR,QAAQ,KACR;AAEF,WAAO,QAAQ;AAAA;AAAA;",
6
+ "names": []
7
+ }
@@ -0,0 +1,19 @@
1
+ // next/index.ts
2
+ import { getIronSession } from "iron-session";
3
+ function withIronSessionApiRoute(handler, options) {
4
+ return async function nextApiHandlerWrappedWithIronSession(req, res) {
5
+ req.session = await getIronSession(req, res, options);
6
+ return handler(req, res);
7
+ };
8
+ }
9
+ function withIronSessionSsr(handler, options) {
10
+ return async function nextGetServerSidePropsHandlerWrappedWithIronSession(context) {
11
+ context.req.session = await getIronSession(context.req, context.res, options);
12
+ return handler(context);
13
+ };
14
+ }
15
+ export {
16
+ withIronSessionApiRoute,
17
+ withIronSessionSsr
18
+ };
19
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../index.ts"],
4
+ "sourcesContent": ["import type {\n GetServerSidePropsContext,\n GetServerSidePropsResult,\n NextApiRequest,\n NextApiResponse,\n} from \"next\";\nimport type { IronSession, IronSessionOptions } from \"iron-session\";\nimport { getIronSession } from \"iron-session\";\n\nexport interface NextApiRequestWithIronSession extends NextApiRequest {\n session: IronSession;\n}\n\nexport declare type NextApiHandlerWithIronSession<T = unknown> = (\n req: NextApiRequestWithIronSession,\n res: NextApiResponse<T>,\n) => void | Promise<void>;\n\ninterface NextGetSeverSideContextWithIronSession\n extends GetServerSidePropsContext {\n req: NextApiRequestWithIronSession;\n}\n\nexport declare type NextGetServerSidePropsHandlerWithIronSession<P> = (\n context: NextGetSeverSideContextWithIronSession,\n) => Promise<GetServerSidePropsResult<P>>;\n\nexport function withIronSessionApiRoute(\n handler: NextApiHandlerWithIronSession,\n options: IronSessionOptions,\n): NextApiHandlerWithIronSession {\n return async function nextApiHandlerWrappedWithIronSession(req, res) {\n req.session = await getIronSession(req, res, options);\n return handler(req, res);\n };\n}\n\nexport function withIronSessionSsr<P>(\n handler: NextGetServerSidePropsHandlerWithIronSession<P>,\n options: IronSessionOptions,\n): NextGetServerSidePropsHandlerWithIronSession<P> {\n return async function nextGetServerSidePropsHandlerWrappedWithIronSession(\n context: NextGetSeverSideContextWithIronSession,\n ) {\n context.req.session = await getIronSession(\n context.req,\n context.res,\n options,\n );\n return handler(context);\n };\n}\n"],
5
+ "mappings": ";AAOA;AAoBO,iCACL,SACA,SAC+B;AAC/B,SAAO,oDAAoD,KAAK,KAAK;AACnE,QAAI,UAAU,MAAM,eAAe,KAAK,KAAK;AAC7C,WAAO,QAAQ,KAAK;AAAA;AAAA;AAIjB,4BACL,SACA,SACiD;AACjD,SAAO,mEACL,SACA;AACA,YAAQ,IAAI,UAAU,MAAM,eAC1B,QAAQ,KACR,QAAQ,KACR;AAEF,WAAO,QAAQ;AAAA;AAAA;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iron-session",
3
- "version": "2.0.0-alpha.1",
3
+ "version": "2.0.0-alpha.10",
4
4
  "license": "MIT",
5
5
  "author": "Vincent Voyer <vincent@codeagain.com>",
6
6
  "exports": {
@@ -10,39 +10,27 @@
10
10
  "types": "./dist/index.d.ts"
11
11
  },
12
12
  "./next": {
13
- "import": "./dist/next/index.mjs",
14
- "require": "./dist/next/index.js",
15
- "types": "./dist/next/index.d.ts"
13
+ "import": "./next/dist/index.mjs",
14
+ "require": "./next/dist/index.js",
15
+ "types": "./next/dist/index.d.ts"
16
16
  }
17
17
  },
18
18
  "main": "./dist/index.js",
19
19
  "module": "./dist/index.mjs",
20
20
  "types": "./dist/index.d.ts",
21
21
  "files": [
22
- "dist"
22
+ "dist",
23
+ "next/dist"
23
24
  ],
24
25
  "workspaces": [
25
26
  "examples/next.js",
26
27
  "examples/next.js-typescript"
27
28
  ],
28
29
  "scripts": {
29
- "build": "tsup",
30
+ "build": "rimraf dist/ next/dist && tsup src/index.ts && tsup next/index.ts -d next/dist",
30
31
  "lint": "eslint . && (cd examples/next.js && npm run lint) && (cd examples/next.js-typescript && npm run lint)",
31
32
  "prepublishOnly": "npm run build",
32
- "test": "jest && npm run lint"
33
- },
34
- "babel": {
35
- "presets": [
36
- [
37
- "@babel/preset-env",
38
- {
39
- "targets": {
40
- "node": "current"
41
- }
42
- }
43
- ],
44
- "@babel/preset-typescript"
45
- ]
33
+ "test": "jest --coverage && npm run lint"
46
34
  },
47
35
  "prettier": {
48
36
  "trailingComma": "all"
@@ -69,6 +57,26 @@
69
57
  ]
70
58
  }
71
59
  },
60
+ "jest": {
61
+ "collectCoverageFrom": [
62
+ "src/*.ts",
63
+ "next/*.ts"
64
+ ],
65
+ "coverageProvider": "v8",
66
+ "coverageReporters": [
67
+ "text"
68
+ ],
69
+ "transform": {
70
+ ".ts$": [
71
+ "@swc-node/jest",
72
+ {
73
+ "jsc": {
74
+ "minify": false
75
+ }
76
+ }
77
+ ]
78
+ }
79
+ },
72
80
  "dependencies": {
73
81
  "@types/cookie": "^0.4.0",
74
82
  "@types/node": "^16.11.1",
@@ -76,19 +84,17 @@
76
84
  "iron-store": "^1.3.5"
77
85
  },
78
86
  "devDependencies": {
79
- "@babel/core": "7.15.8",
80
- "@babel/preset-env": "7.15.8",
81
- "@babel/preset-typescript": "7.15.0",
87
+ "@swc-node/jest": "1.3.3",
82
88
  "@tsconfig/node12": "1.0.9",
83
89
  "@types/jest": "27.0.2",
84
90
  "@typescript-eslint/eslint-plugin": "5.1.0",
85
91
  "@typescript-eslint/parser": "5.1.0",
86
- "babel-jest": "27.3.1",
87
92
  "eslint": "8.0.1",
88
93
  "jest": "27.3.1",
89
94
  "jest-date-mock": "1.0.8",
90
95
  "prettier": "2.4.1",
91
96
  "prettier-plugin-packagejson": "2.2.13",
97
+ "rimraf": "3.0.2",
92
98
  "tsup": "5.4.1",
93
99
  "typescript": "4.4.4"
94
100
  },
@@ -124,14 +130,13 @@
124
130
  "sourcemap": true,
125
131
  "clean": true,
126
132
  "dts": true,
127
- "entryPoints": [
128
- "src/index.ts",
129
- "src/next/index.ts"
130
- ],
133
+ "target": "es2019",
131
134
  "format": [
132
135
  "esm",
133
136
  "cjs"
134
137
  ],
135
- "minify": true
138
+ "external": [
139
+ "iron-session"
140
+ ]
136
141
  }
137
142
  }
@@ -1,2 +0,0 @@
1
- var y=Object.create;var p=Object.defineProperty,N=Object.defineProperties,A=Object.getOwnPropertyDescriptor,R=Object.getOwnPropertyDescriptors,P=Object.getOwnPropertyNames,x=Object.getOwnPropertySymbols,W=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable;var w=(e,o,s)=>o in e?p(e,o,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[o]=s,i=(e,o)=>{for(var s in o||(o={}))h.call(o,s)&&w(e,s,o[s]);if(x)for(var s of x(o))C.call(o,s)&&w(e,s,o[s]);return e},S=(e,o)=>N(e,R(o)),k=e=>p(e,"__esModule",{value:!0});var O=(e,o)=>{k(e);for(var s in o)p(e,s,{get:o[s],enumerable:!0})},T=(e,o,s)=>{if(o&&typeof o=="object"||typeof o=="function")for(let t of P(o))!h.call(e,t)&&t!=="default"&&p(e,t,{get:()=>o[t],enumerable:!(s=A(o,t))||s.enumerable});return e},f=e=>T(k(p(e!=null?y(W(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);O(exports,{withIronSessionApiRoute:()=>E,withIronSessionSsr:()=>z});var u=f(require("iron-store")),c=f(require("cookie")),q=60,I={ttl:15*24*3600,cookieOptions:{httpOnly:!0,secure:!0,sameSite:"lax",path:"/"}};async function m(e,o,s){var l,g;if(!e||!o||!s||!s.cookieName||!s.password)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');let t=Array.isArray(s.password)?s.password:[{id:1,password:s.password}];t.forEach(({password:a})=>{if(a.length<32)throw new Error("iron-session: Bad usage. Password must be at least 32 characters long.")});let r=S(i(i({},I),s),{cookieOptions:i(i({},I.cookieOptions),s.cookieOptions||{})});r.ttl===0&&(r.ttl=2147483647),r.cookieOptions.maxAge=H((g=(l=s.cookieOptions)==null?void 0:l.maxAge)!=null?g:r.ttl);let n=await b({sealed:c.default.parse(e.headers.cookie||"")[r.cookieName],password:t,ttl:r.ttl*1e3});return{set:n.set,get:n.get,unset:n.unset,async save(){let a=await n.seal(),d=c.default.serialize(r.cookieName,a,r.cookieOptions);if(d.length>4096)throw new Error(`iron-session: Cookie length is too big ${d.length}, browsers will refuse it. Try to remove some data.`);return v(d,o),d},destroy(){n.clear();let a=c.default.serialize(r.cookieName,"",S(i({},r.cookieOptions),{maxAge:0}));v(a,o)}}}function v(e,o){var t;let s=(t=o.getHeader("set-cookie"))!=null?t:[];typeof s=="string"&&(s=[s]),o.setHeader("set-cookie",[...s,e])}function H(e){return e-q}async function b({sealed:e,password:o,ttl:s}){try{return await(0,u.default)({sealed:e,password:o,ttl:s})}catch(t){if(t instanceof Error&&(t.message==="Expired seal"||t.message==="Bad hmac value"||t.message==="Cannot find password: "))return await(0,u.default)({password:o,ttl:s});throw t}}function E(e,o){return async function(t,r){return t.session=await m(t,r,o),e(t,r)}}function z(e,o){return async function(t){return t.req.session=await m(t.req,t.res,o),e(t)}}0&&(module.exports={withIronSessionApiRoute,withIronSessionSsr});
2
- //# sourceMappingURL=index.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/next/index.ts", "../../src/index.ts"],
4
- "sourcesContent": ["import type {\n GetServerSidePropsContext,\n GetServerSidePropsResult,\n NextApiRequest,\n NextApiResponse,\n} from \"next\";\nimport type { IronSession, IronSessionOptions } from \"..\";\nimport { getIronSession } from \"..\";\n\nexport interface NextApiRequestWithIronSession extends NextApiRequest {\n session: IronSession;\n}\n\nexport declare type NextApiHandlerWithIronSession<T = unknown> = (\n req: NextApiRequestWithIronSession,\n res: NextApiResponse<T>,\n) => void | Promise<void>;\n\ninterface NextGetSeverSideContextWithIronSession\n extends GetServerSidePropsContext {\n req: NextApiRequestWithIronSession;\n}\n\nexport declare type NextGetServerSidePropsHandlerWithIronSession<P> = (\n context: NextGetSeverSideContextWithIronSession,\n) => Promise<GetServerSidePropsResult<P>>;\n\nexport function withIronSessionApiRoute(\n handler: NextApiHandlerWithIronSession,\n options: IronSessionOptions,\n): NextApiHandlerWithIronSession {\n return async function nextApiHandlerWrappedWithIronSession(req, res) {\n req.session = await getIronSession(req, res, options);\n return handler(req, res);\n };\n}\n\nexport function withIronSessionSsr<P>(\n handler: NextGetServerSidePropsHandlerWithIronSession<P>,\n options: IronSessionOptions,\n): NextGetServerSidePropsHandlerWithIronSession<P> {\n return async function nextGetServerSidePropsHandlerWrappedWithIronSession(\n context: NextGetSeverSideContextWithIronSession,\n ) {\n context.req.session = await getIronSession(\n context.req,\n context.res,\n options,\n );\n return handler(context);\n };\n}\n", "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": "s6BAAA,oECAA,MAAsB,yBACtB,EAA+C,qBAKzC,EAAmB,GAInB,EAGF,CACF,IAAK,GAAK,GAAK,KACf,cAAe,CACb,SAAU,GACV,OAAQ,GACR,SAAU,MACV,KAAM,MAmBV,iBAGE,EAAkB,EAAmB,EAAiC,CAzCxE,QA0CE,GACE,CAAC,GACD,CAAC,GACD,CAAC,GACD,CAAC,EAAY,YACb,CAAC,EAAY,SAEb,KAAM,IAAI,OACR,4LAIJ,GAAM,GAAoB,MAAM,QAAQ,EAAY,UAChD,EAAY,SACZ,CAAC,CAAE,GAAI,EAAG,SAAU,EAAY,WAEpC,EAAkB,QAAQ,CAAC,CAAE,cAAe,CAC1C,GAAI,EAAS,OAAS,GACpB,KAAM,IAAI,OACR,4EAKN,GAAM,GAAwC,SACzC,GACA,GAFyC,CAG5C,cAAe,OACV,EAAe,eACd,EAAY,eAAiB,MAIrC,AAAI,EAAQ,MAAQ,GAKlB,GAAQ,IAAM,YAGhB,EAAQ,cAAc,OAAS,EAC7B,QAAY,gBAAZ,cAA2B,SAA3B,OAAqC,EAAQ,KAG/C,GAAM,GAAQ,KAAM,GAAiB,CACnC,OAAQ,UAAO,MAAM,EAAI,QAAQ,QAAU,IAAI,EAAQ,YACvD,SAAU,EACV,IAAK,EAAQ,IAAM,MAGrB,MAAO,CACL,IAAK,EAAM,IACX,IAAK,EAAM,IACX,MAAO,EAAM,WACP,OAAO,CACX,GAAM,GAAO,KAAM,GAAM,OACnB,EAAc,UAAO,UACzB,EAAQ,WACR,EACA,EAAQ,eAGV,GAAI,EAAY,OAAS,KACvB,KAAM,IAAI,OACR,0CAA0C,EAAY,6DAI1D,SAAa,EAAa,GACnB,GAET,SAAU,CACR,EAAM,QACN,GAAM,GAAc,UAAO,UAAU,EAAQ,WAAY,GAAI,OACxD,EAAQ,eADgD,CAE3D,OAAQ,KAEV,EAAa,EAAa,KAKhC,WAAsB,EAAqB,EAAqB,CA7HhE,MA8HE,GAAI,GACD,KAAI,UAAU,gBAAd,OAAqD,GACxD,AAAI,MAAO,IAAsB,UAC/B,GAAoB,CAAC,IAEvB,EAAI,UAAU,aAAc,CAAC,GAAG,EAAmB,IAGrD,WAA6B,EAAa,CAIxC,MAAO,GAAM,EAGf,iBAAgC,CAC9B,SACA,WACA,OAKC,CACD,GAAI,CACF,MAAO,MAAM,cAAU,CACrB,SACA,WACA,cAEK,EAAP,CACA,GAAI,YAAiB,QAEjB,GAAM,UAAY,gBAClB,EAAM,UAAY,kBAClB,EAAM,UAAY,0BAMlB,MAAO,MAAM,cAAU,CAAE,WAAU,QAIvC,KAAM,IDhJH,WACL,EACA,EAC+B,CAC/B,MAAO,gBAAoD,EAAK,EAAK,CACnE,SAAI,QAAU,KAAM,GAAe,EAAK,EAAK,GACtC,EAAQ,EAAK,IAIjB,WACL,EACA,EACiD,CACjD,MAAO,gBACL,EACA,CACA,SAAQ,IAAI,QAAU,KAAM,GAC1B,EAAQ,IACR,EAAQ,IACR,GAEK,EAAQ",
6
- "names": []
7
- }
@@ -1,2 +0,0 @@
1
- var k=Object.defineProperty,f=Object.defineProperties;var I=Object.getOwnPropertyDescriptors;var l=Object.getOwnPropertySymbols;var v=Object.prototype.hasOwnProperty,y=Object.prototype.propertyIsEnumerable;var g=(s,o,e)=>o in s?k(s,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[o]=e,i=(s,o)=>{for(var e in o||(o={}))v.call(o,e)&&g(s,e,o[e]);if(l)for(var e of l(o))y.call(o,e)&&g(s,e,o[e]);return s},d=(s,o)=>f(s,I(o));import x from"iron-store";import c from"cookie";var N=60,h={ttl:15*24*3600,cookieOptions:{httpOnly:!0,secure:!0,sameSite:"lax",path:"/"}};async function S(s,o,e){var u,m;if(!s||!o||!e||!e.cookieName||!e.password)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');let t=Array.isArray(e.password)?e.password:[{id:1,password:e.password}];t.forEach(({password:a})=>{if(a.length<32)throw new Error("iron-session: Bad usage. Password must be at least 32 characters long.")});let r=d(i(i({},h),e),{cookieOptions:i(i({},h.cookieOptions),e.cookieOptions||{})});r.ttl===0&&(r.ttl=2147483647),r.cookieOptions.maxAge=A((m=(u=e.cookieOptions)==null?void 0:u.maxAge)!=null?m:r.ttl);let n=await R({sealed:c.parse(s.headers.cookie||"")[r.cookieName],password:t,ttl:r.ttl*1e3});return{set:n.set,get:n.get,unset:n.unset,async save(){let a=await n.seal(),p=c.serialize(r.cookieName,a,r.cookieOptions);if(p.length>4096)throw new Error(`iron-session: Cookie length is too big ${p.length}, browsers will refuse it. Try to remove some data.`);return w(p,o),p},destroy(){n.clear();let a=c.serialize(r.cookieName,"",d(i({},r.cookieOptions),{maxAge:0}));w(a,o)}}}function w(s,o){var t;let e=(t=o.getHeader("set-cookie"))!=null?t:[];typeof e=="string"&&(e=[e]),o.setHeader("set-cookie",[...e,s])}function A(s){return s-N}async function R({sealed:s,password:o,ttl:e}){try{return await x({sealed:s,password:o,ttl:e})}catch(t){if(t instanceof Error&&(t.message==="Expired seal"||t.message==="Bad hmac value"||t.message==="Cannot find password: "))return await x({password:o,ttl:e});throw t}}function q(s,o){return async function(t,r){return t.session=await S(t,r,o),s(t,r)}}function H(s,o){return async function(t){return t.req.session=await S(t.req,t.res,o),s(t)}}export{q as withIronSessionApiRoute,H as withIronSessionSsr};
2
- //# sourceMappingURL=index.mjs.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/index.ts", "../../src/next/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", "import type {\n GetServerSidePropsContext,\n GetServerSidePropsResult,\n NextApiRequest,\n NextApiResponse,\n} from \"next\";\nimport type { IronSession, IronSessionOptions } from \"..\";\nimport { getIronSession } from \"..\";\n\nexport interface NextApiRequestWithIronSession extends NextApiRequest {\n session: IronSession;\n}\n\nexport declare type NextApiHandlerWithIronSession<T = unknown> = (\n req: NextApiRequestWithIronSession,\n res: NextApiResponse<T>,\n) => void | Promise<void>;\n\ninterface NextGetSeverSideContextWithIronSession\n extends GetServerSidePropsContext {\n req: NextApiRequestWithIronSession;\n}\n\nexport declare type NextGetServerSidePropsHandlerWithIronSession<P> = (\n context: NextGetSeverSideContextWithIronSession,\n) => Promise<GetServerSidePropsResult<P>>;\n\nexport function withIronSessionApiRoute(\n handler: NextApiHandlerWithIronSession,\n options: IronSessionOptions,\n): NextApiHandlerWithIronSession {\n return async function nextApiHandlerWrappedWithIronSession(req, res) {\n req.session = await getIronSession(req, res, options);\n return handler(req, res);\n };\n}\n\nexport function withIronSessionSsr<P>(\n handler: NextGetServerSidePropsHandlerWithIronSession<P>,\n options: IronSessionOptions,\n): NextGetServerSidePropsHandlerWithIronSession<P> {\n return async function nextGetServerSidePropsHandlerWrappedWithIronSession(\n context: NextGetSeverSideContextWithIronSession,\n ) {\n context.req.session = await getIronSession(\n context.req,\n context.res,\n options,\n );\n return handler(context);\n };\n}\n"],
5
- "mappings": "6aAAA,0BACA,sBAKA,GAAM,GAAmB,GAInB,EAGF,CACF,IAAK,GAAK,GAAK,KACf,cAAe,CACb,SAAU,GACV,OAAQ,GACR,SAAU,MACV,KAAM,MAmBV,iBAGE,EAAkB,EAAmB,E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