better-call 1.1.5 → 1.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/dist/_virtual/rolldown_runtime.cjs +29 -0
- package/dist/adapters/node/request.cjs +125 -0
- package/dist/adapters/node/request.cjs.map +1 -0
- package/dist/{node.d.ts → adapters/node/request.d.cts} +2 -6
- package/dist/adapters/node/request.d.mts +16 -0
- package/dist/{node.js → adapters/node/request.mjs} +2 -13
- package/dist/adapters/node/request.mjs.map +1 -0
- package/dist/client.cjs +8 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +12 -13
- package/dist/client.d.mts +53 -0
- package/dist/client.mjs +14 -0
- package/dist/client.mjs.map +1 -0
- package/dist/context.cjs +102 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.d.cts +340 -0
- package/dist/context.d.mts +340 -0
- package/dist/context.mjs +102 -0
- package/dist/context.mjs.map +1 -0
- package/dist/cookies.cjs +87 -0
- package/dist/cookies.cjs.map +1 -0
- package/dist/cookies.d.cts +103 -0
- package/dist/cookies.d.mts +103 -0
- package/dist/cookies.mjs +84 -0
- package/dist/cookies.mjs.map +1 -0
- package/dist/crypto.cjs +39 -0
- package/dist/crypto.cjs.map +1 -0
- package/dist/crypto.mjs +36 -0
- package/dist/crypto.mjs.map +1 -0
- package/dist/endpoint.cjs +70 -0
- package/dist/endpoint.cjs.map +1 -0
- package/dist/endpoint.d.cts +428 -0
- package/dist/endpoint.d.mts +428 -0
- package/dist/endpoint.mjs +70 -0
- package/dist/endpoint.mjs.map +1 -0
- package/dist/error.cjs +141 -0
- package/dist/error.cjs.map +1 -0
- package/dist/error.d.cts +103 -0
- package/dist/error.d.mts +103 -0
- package/dist/error.mjs +135 -0
- package/dist/error.mjs.map +1 -0
- package/dist/helper.d.cts +12 -0
- package/dist/helper.d.mts +12 -0
- package/dist/index.cjs +26 -968
- package/dist/index.d.cts +11 -14
- package/dist/index.d.mts +11 -0
- package/dist/index.mjs +10 -0
- package/dist/middleware.cjs +39 -0
- package/dist/middleware.cjs.map +1 -0
- package/dist/middleware.d.cts +123 -0
- package/dist/middleware.d.mts +123 -0
- package/dist/middleware.mjs +39 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/node.cjs +4 -151
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +2 -13
- package/dist/node.d.mts +9 -0
- package/dist/node.mjs +15 -0
- package/dist/node.mjs.map +1 -0
- package/dist/openapi.cjs +191 -0
- package/dist/openapi.cjs.map +1 -0
- package/dist/openapi.d.cts +113 -0
- package/dist/openapi.d.mts +113 -0
- package/dist/openapi.mjs +189 -0
- package/dist/openapi.mjs.map +1 -0
- package/dist/router.cjs +117 -0
- package/dist/router.cjs.map +1 -0
- package/dist/router.d.cts +4 -1242
- package/dist/router.d.mts +97 -0
- package/dist/router.mjs +116 -0
- package/dist/router.mjs.map +1 -0
- package/dist/standard-schema.d.cts +59 -0
- package/dist/standard-schema.d.mts +59 -0
- package/dist/to-response.cjs +96 -0
- package/dist/to-response.cjs.map +1 -0
- package/dist/to-response.d.cts +12 -0
- package/dist/to-response.d.mts +12 -0
- package/dist/to-response.mjs +96 -0
- package/dist/to-response.mjs.map +1 -0
- package/dist/utils.cjs +77 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.mjs +74 -0
- package/dist/utils.mjs.map +1 -0
- package/dist/validator.cjs +58 -0
- package/dist/validator.cjs.map +1 -0
- package/dist/validator.mjs +57 -0
- package/dist/validator.mjs.map +1 -0
- package/package.json +23 -13
- package/dist/client.d.ts +0 -54
- package/dist/client.js +0 -13
- package/dist/client.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.ts +0 -14
- package/dist/index.js +0 -951
- package/dist/index.js.map +0 -1
- package/dist/node.js.map +0 -1
- package/dist/router.d.ts +0 -1335
package/dist/context.mjs
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { APIError, ValidationError } from "./error.mjs";
|
|
2
|
+
import { runValidation } from "./validator.mjs";
|
|
3
|
+
import { getCryptoKey, verifySignature } from "./crypto.mjs";
|
|
4
|
+
import { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from "./cookies.mjs";
|
|
5
|
+
|
|
6
|
+
//#region src/context.ts
|
|
7
|
+
const createInternalContext = async (context, { options, path }) => {
|
|
8
|
+
const headers = new Headers();
|
|
9
|
+
let responseStatus = void 0;
|
|
10
|
+
const { data, error } = await runValidation(options, context);
|
|
11
|
+
if (error) throw new ValidationError(error.message, error.issues);
|
|
12
|
+
const requestHeaders = "headers" in context ? context.headers instanceof Headers ? context.headers : new Headers(context.headers) : "request" in context && context.request instanceof Request ? context.request.headers : null;
|
|
13
|
+
const requestCookies = requestHeaders?.get("cookie");
|
|
14
|
+
const parsedCookies = requestCookies ? parseCookies(requestCookies) : void 0;
|
|
15
|
+
const internalContext = {
|
|
16
|
+
...context,
|
|
17
|
+
body: data.body,
|
|
18
|
+
query: data.query,
|
|
19
|
+
path: context.path || path || "virtual:",
|
|
20
|
+
context: "context" in context && context.context ? context.context : {},
|
|
21
|
+
returned: void 0,
|
|
22
|
+
headers: context?.headers,
|
|
23
|
+
request: context?.request,
|
|
24
|
+
params: "params" in context ? context.params : void 0,
|
|
25
|
+
method: context.method ?? (Array.isArray(options.method) ? options.method[0] : options.method === "*" ? "GET" : options.method),
|
|
26
|
+
setHeader: (key, value) => {
|
|
27
|
+
headers.set(key, value);
|
|
28
|
+
},
|
|
29
|
+
getHeader: (key) => {
|
|
30
|
+
if (!requestHeaders) return null;
|
|
31
|
+
return requestHeaders.get(key);
|
|
32
|
+
},
|
|
33
|
+
getCookie: (key, prefix) => {
|
|
34
|
+
const finalKey = getCookieKey(key, prefix);
|
|
35
|
+
if (!finalKey) return null;
|
|
36
|
+
return parsedCookies?.get(finalKey) || null;
|
|
37
|
+
},
|
|
38
|
+
getSignedCookie: async (key, secret, prefix) => {
|
|
39
|
+
const finalKey = getCookieKey(key, prefix);
|
|
40
|
+
if (!finalKey) return null;
|
|
41
|
+
const value = parsedCookies?.get(finalKey);
|
|
42
|
+
if (!value) return null;
|
|
43
|
+
const signatureStartPos = value.lastIndexOf(".");
|
|
44
|
+
if (signatureStartPos < 1) return null;
|
|
45
|
+
const signedValue = value.substring(0, signatureStartPos);
|
|
46
|
+
const signature = value.substring(signatureStartPos + 1);
|
|
47
|
+
if (signature.length !== 44 || !signature.endsWith("=")) return null;
|
|
48
|
+
return await verifySignature(signature, signedValue, await getCryptoKey(secret)) ? signedValue : false;
|
|
49
|
+
},
|
|
50
|
+
setCookie: (key, value, options$1) => {
|
|
51
|
+
const cookie = serializeCookie(key, value, options$1);
|
|
52
|
+
headers.append("set-cookie", cookie);
|
|
53
|
+
return cookie;
|
|
54
|
+
},
|
|
55
|
+
setSignedCookie: async (key, value, secret, options$1) => {
|
|
56
|
+
const cookie = await serializeSignedCookie(key, value, secret, options$1);
|
|
57
|
+
headers.append("set-cookie", cookie);
|
|
58
|
+
return cookie;
|
|
59
|
+
},
|
|
60
|
+
redirect: (url) => {
|
|
61
|
+
headers.set("location", url);
|
|
62
|
+
return new APIError("FOUND", void 0, headers);
|
|
63
|
+
},
|
|
64
|
+
error: (status, body, headers$1) => {
|
|
65
|
+
return new APIError(status, body, headers$1);
|
|
66
|
+
},
|
|
67
|
+
setStatus: (status) => {
|
|
68
|
+
responseStatus = status;
|
|
69
|
+
},
|
|
70
|
+
json: (json, routerResponse) => {
|
|
71
|
+
if (!context.asResponse) return json;
|
|
72
|
+
return {
|
|
73
|
+
body: routerResponse?.body || json,
|
|
74
|
+
routerResponse,
|
|
75
|
+
_flag: "json"
|
|
76
|
+
};
|
|
77
|
+
},
|
|
78
|
+
responseHeaders: headers,
|
|
79
|
+
get responseStatus() {
|
|
80
|
+
return responseStatus;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
for (const middleware of options.use || []) {
|
|
84
|
+
const response = await middleware({
|
|
85
|
+
...internalContext,
|
|
86
|
+
returnHeaders: true,
|
|
87
|
+
asResponse: false
|
|
88
|
+
});
|
|
89
|
+
if (response.response) Object.assign(internalContext.context, response.response);
|
|
90
|
+
/**
|
|
91
|
+
* Apply headers from the middleware to the endpoint headers
|
|
92
|
+
*/
|
|
93
|
+
if (response.headers) response.headers.forEach((value, key) => {
|
|
94
|
+
internalContext.responseHeaders.set(key, value);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return internalContext;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
//#endregion
|
|
101
|
+
export { createInternalContext };
|
|
102
|
+
//# sourceMappingURL=context.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.mjs","names":["responseStatus: Status | undefined","requestHeaders: Headers | null","options","headers"],"sources":["../src/context.ts"],"sourcesContent":["import type { EndpointOptions } from \"./endpoint\";\nimport { type statusCodes, APIError, ValidationError, type Status } from \"./error\";\nimport type {\n\tInferParamPath,\n\tInferParamWildCard,\n\tIsEmptyObject,\n\tPrettify,\n\tUnionToIntersection,\n} from \"./helper\";\nimport type { Middleware, MiddlewareContext, MiddlewareOptions } from \"./middleware\";\nimport { runValidation } from \"./validator\";\nimport {\n\tgetCookieKey,\n\tparseCookies,\n\tserializeCookie,\n\tserializeSignedCookie,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookies\";\nimport { getCryptoKey, verifySignature } from \"./crypto\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\n\nexport type HTTPMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\nexport type Method = HTTPMethod | \"*\";\n\nexport type InferBodyInput<\n\tOptions extends EndpointOptions | MiddlewareOptions,\n\tBody = Options[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer B;\n\t\t};\n\t}\n\t\t? B\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"body\"]>\n\t\t\t: undefined,\n> = undefined extends Body\n\t? {\n\t\t\tbody?: Body;\n\t\t}\n\t: {\n\t\t\tbody: Body;\n\t\t};\n\nexport type InferBody<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer Body;\n\t\t};\n\t}\n\t\t? Body\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"body\"]>\n\t\t\t: any;\n\nexport type InferQueryInput<\n\tOptions extends EndpointOptions | MiddlewareOptions,\n\tQuery = Options[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined,\n> = undefined extends Query\n\t? {\n\t\t\tquery?: Query;\n\t\t}\n\t: {\n\t\t\tquery: Query;\n\t\t};\n\nexport type InferQuery<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined;\n\nexport type InferMethod<Options extends EndpointOptions> = Options[\"method\"] extends Array<Method>\n\t? Options[\"method\"][number]\n\t: Options[\"method\"] extends \"*\"\n\t\t? HTTPMethod\n\t\t: Options[\"method\"];\n\nexport type InferInputMethod<\n\tOptions extends EndpointOptions,\n\tMethod = Options[\"method\"] extends Array<any>\n\t\t? Options[\"method\"][number] | undefined\n\t\t: Options[\"method\"] extends \"*\"\n\t\t\t? HTTPMethod\n\t\t\t: Options[\"method\"] | undefined,\n> = undefined extends Method\n\t? {\n\t\t\tmethod?: Method;\n\t\t}\n\t: {\n\t\t\tmethod: Method;\n\t\t};\n\nexport type InferParam<Path extends string> = [Path] extends [never]\n\t? Record<string, any> | undefined\n\t: IsEmptyObject<InferParamPath<Path> & InferParamWildCard<Path>> extends true\n\t\t? Record<string, any> | undefined\n\t\t: Prettify<InferParamPath<Path> & InferParamWildCard<Path>>;\n\nexport type InferParamInput<Path extends string> = [Path] extends [never]\n\t? { params?: Record<string, any> }\n\t: IsEmptyObject<InferParamPath<Path> & InferParamWildCard<Path>> extends true\n\t\t? {\n\t\t\t\tparams?: Record<string, any>;\n\t\t\t}\n\t\t: {\n\t\t\t\tparams: Prettify<InferParamPath<Path> & InferParamWildCard<Path>>;\n\t\t\t};\n\nexport type InferRequest<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireRequest\"] extends true ? Request : Request | undefined;\n\nexport type InferRequestInput<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireRequest\"] extends true\n\t\t? {\n\t\t\t\trequest: Request;\n\t\t\t}\n\t\t: {\n\t\t\t\trequest?: Request;\n\t\t\t};\n\nexport type InferHeaders<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireHeaders\"] extends true ? Headers : Headers | undefined;\n\nexport type InferHeadersInput<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireHeaders\"] extends true\n\t\t? {\n\t\t\t\theaders: HeadersInit;\n\t\t\t}\n\t\t: {\n\t\t\t\theaders?: HeadersInit;\n\t\t\t};\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = Opts extends Middleware[]\n\t? UnionToIntersection<Awaited<ReturnType<Opts[number]>>>\n\t: {};\n\nexport type InferMiddlewareBody<Options extends MiddlewareOptions> =\n\tOptions[\"body\"] extends StandardSchemaV1<infer T> ? T : any;\n\nexport type InferMiddlewareQuery<Options extends MiddlewareOptions> =\n\tOptions[\"query\"] extends StandardSchemaV1<infer T> ? T : Record<string, any> | undefined;\n\nexport type InputContext<\n\tPath extends string,\n\tOptions extends EndpointOptions,\n> = InferBodyInput<Options> &\n\tInferInputMethod<Options> &\n\tInferQueryInput<Options> &\n\tInferParamInput<Path> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\treturnStatus?: boolean;\n\t\tuse?: Middleware[];\n\t\tpath?: string;\n\t};\n\nexport const createInternalContext = async (\n\tcontext: InputContext<any, any>,\n\t{\n\t\toptions,\n\t\tpath,\n\t}: {\n\t\toptions: EndpointOptions;\n\t\tpath?: string;\n\t},\n) => {\n\tconst headers = new Headers();\n\tlet responseStatus: Status | undefined = undefined;\n\n\tconst { data, error } = await runValidation(options, context);\n\tif (error) {\n\t\tthrow new ValidationError(error.message, error.issues);\n\t}\n\tconst requestHeaders: Headers | null =\n\t\t\"headers\" in context\n\t\t\t? context.headers instanceof Headers\n\t\t\t\t? context.headers\n\t\t\t\t: new Headers(context.headers)\n\t\t\t: \"request\" in context && context.request instanceof Request\n\t\t\t\t? context.request.headers\n\t\t\t\t: null;\n\tconst requestCookies = requestHeaders?.get(\"cookie\");\n\tconst parsedCookies = requestCookies ? parseCookies(requestCookies) : undefined;\n\n\tconst internalContext = {\n\t\t...context,\n\t\tbody: data.body,\n\t\tquery: data.query,\n\t\tpath: context.path || path || \"virtual:\",\n\t\tcontext: \"context\" in context && context.context ? context.context : {},\n\t\treturned: undefined as any,\n\t\theaders: context?.headers,\n\t\trequest: context?.request,\n\t\tparams: \"params\" in context ? context.params : undefined,\n\t\tmethod:\n\t\t\tcontext.method ??\n\t\t\t(Array.isArray(options.method)\n\t\t\t\t? options.method[0]\n\t\t\t\t: options.method === \"*\"\n\t\t\t\t\t? \"GET\"\n\t\t\t\t\t: options.method),\n\t\tsetHeader: (key: string, value: string) => {\n\t\t\theaders.set(key, value);\n\t\t},\n\t\tgetHeader: (key: string) => {\n\t\t\tif (!requestHeaders) return null;\n\t\t\treturn requestHeaders.get(key);\n\t\t},\n\t\tgetCookie: (key: string, prefix?: CookiePrefixOptions) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn parsedCookies?.get(finalKey) || null;\n\t\t},\n\t\tgetSignedCookie: async (key: string, secret: string, prefix?: CookiePrefixOptions) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst value = parsedCookies?.get(finalKey);\n\t\t\tif (!value) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\t\tif (signatureStartPos < 1) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst secretKey = await getCryptoKey(secret);\n\t\t\tconst isVerified = await verifySignature(signature, signedValue, secretKey);\n\t\t\treturn isVerified ? signedValue : false;\n\t\t},\n\t\tsetCookie: (key: string, value: string, options?: CookieOptions) => {\n\t\t\tconst cookie = serializeCookie(key, value, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tsetSignedCookie: async (\n\t\t\tkey: string,\n\t\t\tvalue: string,\n\t\t\tsecret: string,\n\t\t\toptions?: CookieOptions,\n\t\t) => {\n\t\t\tconst cookie = await serializeSignedCookie(key, value, secret, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tredirect: (url: string) => {\n\t\t\theaders.set(\"location\", url);\n\t\t\treturn new APIError(\"FOUND\", undefined, headers);\n\t\t},\n\t\terror: (\n\t\t\tstatus: keyof typeof statusCodes | Status,\n\t\t\tbody?:\n\t\t\t\t| {\n\t\t\t\t\t\tmessage?: string;\n\t\t\t\t\t\tcode?: string;\n\t\t\t\t }\n\t\t\t\t| undefined,\n\t\t\theaders?: HeadersInit,\n\t\t) => {\n\t\t\treturn new APIError(status, body, headers);\n\t\t},\n\t\tsetStatus: (status: Status) => {\n\t\t\tresponseStatus = status;\n\t\t},\n\t\tjson: (\n\t\t\tjson: Record<string, any>,\n\t\t\trouterResponse?:\n\t\t\t\t| {\n\t\t\t\t\t\tstatus?: number;\n\t\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\t\tresponse?: Response;\n\t\t\t\t\t\tbody?: Record<string, any>;\n\t\t\t\t }\n\t\t\t\t| Response,\n\t\t) => {\n\t\t\tif (!context.asResponse) {\n\t\t\t\treturn json;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbody: routerResponse?.body || json,\n\t\t\t\trouterResponse,\n\t\t\t\t_flag: \"json\",\n\t\t\t};\n\t\t},\n\t\tresponseHeaders: headers,\n\t\tget responseStatus() {\n\t\t\treturn responseStatus;\n\t\t},\n\t};\n\t//if context was shimmed through the input we want to apply it\n\tfor (const middleware of options.use || []) {\n\t\tconst response = (await middleware({\n\t\t\t...internalContext,\n\t\t\treturnHeaders: true,\n\t\t\tasResponse: false,\n\t\t})) as {\n\t\t\tresponse?: any;\n\t\t\theaders?: Headers;\n\t\t};\n\t\tif (response.response) {\n\t\t\tObject.assign(internalContext.context, response.response);\n\t\t}\n\t\t/**\n\t\t * Apply headers from the middleware to the endpoint headers\n\t\t */\n\t\tif (response.headers) {\n\t\t\tresponse.headers.forEach((value, key) => {\n\t\t\t\tinternalContext.responseHeaders.set(key, value);\n\t\t\t});\n\t\t}\n\t}\n\treturn internalContext;\n};\n"],"mappings":";;;;;;AA4KA,MAAa,wBAAwB,OACpC,SACA,EACC,SACA,WAKG;CACJ,MAAM,UAAU,IAAI,SAAS;CAC7B,IAAIA,iBAAqC;CAEzC,MAAM,EAAE,MAAM,UAAU,MAAM,cAAc,SAAS,QAAQ;AAC7D,KAAI,MACH,OAAM,IAAI,gBAAgB,MAAM,SAAS,MAAM,OAAO;CAEvD,MAAMC,iBACL,aAAa,UACV,QAAQ,mBAAmB,UAC1B,QAAQ,UACR,IAAI,QAAQ,QAAQ,QAAQ,GAC7B,aAAa,WAAW,QAAQ,mBAAmB,UAClD,QAAQ,QAAQ,UAChB;CACL,MAAM,iBAAiB,gBAAgB,IAAI,SAAS;CACpD,MAAM,gBAAgB,iBAAiB,aAAa,eAAe,GAAG;CAEtE,MAAM,kBAAkB;EACvB,GAAG;EACH,MAAM,KAAK;EACX,OAAO,KAAK;EACZ,MAAM,QAAQ,QAAQ,QAAQ;EAC9B,SAAS,aAAa,WAAW,QAAQ,UAAU,QAAQ,UAAU,EAAE;EACvE,UAAU;EACV,SAAS,SAAS;EAClB,SAAS,SAAS;EAClB,QAAQ,YAAY,UAAU,QAAQ,SAAS;EAC/C,QACC,QAAQ,WACP,MAAM,QAAQ,QAAQ,OAAO,GAC3B,QAAQ,OAAO,KACf,QAAQ,WAAW,MAClB,QACA,QAAQ;EACb,YAAY,KAAa,UAAkB;AAC1C,WAAQ,IAAI,KAAK,MAAM;;EAExB,YAAY,QAAgB;AAC3B,OAAI,CAAC,eAAgB,QAAO;AAC5B,UAAO,eAAe,IAAI,IAAI;;EAE/B,YAAY,KAAa,WAAiC;GACzD,MAAM,WAAW,aAAa,KAAK,OAAO;AAC1C,OAAI,CAAC,SACJ,QAAO;AAER,UAAO,eAAe,IAAI,SAAS,IAAI;;EAExC,iBAAiB,OAAO,KAAa,QAAgB,WAAiC;GACrF,MAAM,WAAW,aAAa,KAAK,OAAO;AAC1C,OAAI,CAAC,SACJ,QAAO;GAER,MAAM,QAAQ,eAAe,IAAI,SAAS;AAC1C,OAAI,CAAC,MACJ,QAAO;GAER,MAAM,oBAAoB,MAAM,YAAY,IAAI;AAChD,OAAI,oBAAoB,EACvB,QAAO;GAER,MAAM,cAAc,MAAM,UAAU,GAAG,kBAAkB;GACzD,MAAM,YAAY,MAAM,UAAU,oBAAoB,EAAE;AACxD,OAAI,UAAU,WAAW,MAAM,CAAC,UAAU,SAAS,IAAI,CACtD,QAAO;AAIR,UADmB,MAAM,gBAAgB,WAAW,aADlC,MAAM,aAAa,OAAO,CAC+B,GACvD,cAAc;;EAEnC,YAAY,KAAa,OAAe,cAA4B;GACnE,MAAM,SAAS,gBAAgB,KAAK,OAAOC,UAAQ;AACnD,WAAQ,OAAO,cAAc,OAAO;AACpC,UAAO;;EAER,iBAAiB,OAChB,KACA,OACA,QACA,cACI;GACJ,MAAM,SAAS,MAAM,sBAAsB,KAAK,OAAO,QAAQA,UAAQ;AACvE,WAAQ,OAAO,cAAc,OAAO;AACpC,UAAO;;EAER,WAAW,QAAgB;AAC1B,WAAQ,IAAI,YAAY,IAAI;AAC5B,UAAO,IAAI,SAAS,SAAS,QAAW,QAAQ;;EAEjD,QACC,QACA,MAMA,cACI;AACJ,UAAO,IAAI,SAAS,QAAQ,MAAMC,UAAQ;;EAE3C,YAAY,WAAmB;AAC9B,oBAAiB;;EAElB,OACC,MACA,mBAQI;AACJ,OAAI,CAAC,QAAQ,WACZ,QAAO;AAER,UAAO;IACN,MAAM,gBAAgB,QAAQ;IAC9B;IACA,OAAO;IACP;;EAEF,iBAAiB;EACjB,IAAI,iBAAiB;AACpB,UAAO;;EAER;AAED,MAAK,MAAM,cAAc,QAAQ,OAAO,EAAE,EAAE;EAC3C,MAAM,WAAY,MAAM,WAAW;GAClC,GAAG;GACH,eAAe;GACf,YAAY;GACZ,CAAC;AAIF,MAAI,SAAS,SACZ,QAAO,OAAO,gBAAgB,SAAS,SAAS,SAAS;;;;AAK1D,MAAI,SAAS,QACZ,UAAS,QAAQ,SAAS,OAAO,QAAQ;AACxC,mBAAgB,gBAAgB,IAAI,KAAK,MAAM;IAC9C;;AAGJ,QAAO"}
|
package/dist/cookies.cjs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
const require_utils = require('./utils.cjs');
|
|
2
|
+
const require_crypto = require('./crypto.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/cookies.ts
|
|
5
|
+
const getCookieKey = (key, prefix) => {
|
|
6
|
+
let finalKey = key;
|
|
7
|
+
if (prefix) if (prefix === "secure") finalKey = "__Secure-" + key;
|
|
8
|
+
else if (prefix === "host") finalKey = "__Host-" + key;
|
|
9
|
+
else return;
|
|
10
|
+
return finalKey;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Parse an HTTP Cookie header string and returning an object of all cookie
|
|
14
|
+
* name-value pairs.
|
|
15
|
+
*
|
|
16
|
+
* Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts
|
|
17
|
+
*
|
|
18
|
+
* @param str the string representing a `Cookie` header value
|
|
19
|
+
*/
|
|
20
|
+
function parseCookies(str) {
|
|
21
|
+
if (typeof str !== "string") throw new TypeError("argument str must be a string");
|
|
22
|
+
const cookies = /* @__PURE__ */ new Map();
|
|
23
|
+
let index = 0;
|
|
24
|
+
while (index < str.length) {
|
|
25
|
+
const eqIdx = str.indexOf("=", index);
|
|
26
|
+
if (eqIdx === -1) break;
|
|
27
|
+
let endIdx = str.indexOf(";", index);
|
|
28
|
+
if (endIdx === -1) endIdx = str.length;
|
|
29
|
+
else if (endIdx < eqIdx) {
|
|
30
|
+
index = str.lastIndexOf(";", eqIdx - 1) + 1;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const key = str.slice(index, eqIdx).trim();
|
|
34
|
+
if (!cookies.has(key)) {
|
|
35
|
+
let val = str.slice(eqIdx + 1, endIdx).trim();
|
|
36
|
+
if (val.codePointAt(0) === 34) val = val.slice(1, -1);
|
|
37
|
+
cookies.set(key, require_utils.tryDecode(val));
|
|
38
|
+
}
|
|
39
|
+
index = endIdx + 1;
|
|
40
|
+
}
|
|
41
|
+
return cookies;
|
|
42
|
+
}
|
|
43
|
+
const _serialize = (key, value, opt = {}) => {
|
|
44
|
+
let cookie;
|
|
45
|
+
if (opt?.prefix === "secure") cookie = `${`__Secure-${key}`}=${value}`;
|
|
46
|
+
else if (opt?.prefix === "host") cookie = `${`__Host-${key}`}=${value}`;
|
|
47
|
+
else cookie = `${key}=${value}`;
|
|
48
|
+
if (key.startsWith("__Secure-") && !opt.secure) opt.secure = true;
|
|
49
|
+
if (key.startsWith("__Host-")) {
|
|
50
|
+
if (!opt.secure) opt.secure = true;
|
|
51
|
+
if (opt.path !== "/") opt.path = "/";
|
|
52
|
+
if (opt.domain) opt.domain = void 0;
|
|
53
|
+
}
|
|
54
|
+
if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) {
|
|
55
|
+
if (opt.maxAge > 3456e4) throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");
|
|
56
|
+
cookie += `; Max-Age=${Math.floor(opt.maxAge)}`;
|
|
57
|
+
}
|
|
58
|
+
if (opt.domain && opt.prefix !== "host") cookie += `; Domain=${opt.domain}`;
|
|
59
|
+
if (opt.path) cookie += `; Path=${opt.path}`;
|
|
60
|
+
if (opt.expires) {
|
|
61
|
+
if (opt.expires.getTime() - Date.now() > 3456e7) throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");
|
|
62
|
+
cookie += `; Expires=${opt.expires.toUTCString()}`;
|
|
63
|
+
}
|
|
64
|
+
if (opt.httpOnly) cookie += "; HttpOnly";
|
|
65
|
+
if (opt.secure) cookie += "; Secure";
|
|
66
|
+
if (opt.sameSite) cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;
|
|
67
|
+
if (opt.partitioned) {
|
|
68
|
+
if (!opt.secure) opt.secure = true;
|
|
69
|
+
cookie += "; Partitioned";
|
|
70
|
+
}
|
|
71
|
+
return cookie;
|
|
72
|
+
};
|
|
73
|
+
const serializeCookie = (key, value, opt) => {
|
|
74
|
+
value = encodeURIComponent(value);
|
|
75
|
+
return _serialize(key, value, opt);
|
|
76
|
+
};
|
|
77
|
+
const serializeSignedCookie = async (key, value, secret, opt) => {
|
|
78
|
+
value = await require_crypto.signCookieValue(value, secret);
|
|
79
|
+
return _serialize(key, value, opt);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
//#endregion
|
|
83
|
+
exports.getCookieKey = getCookieKey;
|
|
84
|
+
exports.parseCookies = parseCookies;
|
|
85
|
+
exports.serializeCookie = serializeCookie;
|
|
86
|
+
exports.serializeSignedCookie = serializeSignedCookie;
|
|
87
|
+
//# sourceMappingURL=cookies.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cookies.cjs","names":["cookies: Map<string, string>","tryDecode","cookie: string","signCookieValue"],"sources":["../src/cookies.ts"],"sourcesContent":["import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map<string, string> = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (key: string, value: string, opt?: CookieOptions) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n"],"mappings":";;;;AA4FA,MAAa,gBAAgB,KAAa,WAAiC;CAC1E,IAAI,WAAW;AACf,KAAI,OACH,KAAI,WAAW,SACd,YAAW,cAAc;UACf,WAAW,OACrB,YAAW,YAAY;KAEvB;AAGF,QAAO;;;;;;;;;;AAWR,SAAgB,aAAa,KAAa;AACzC,KAAI,OAAO,QAAQ,SAClB,OAAM,IAAI,UAAU,gCAAgC;CAGrD,MAAMA,0BAA+B,IAAI,KAAK;CAE9C,IAAI,QAAQ;AACZ,QAAO,QAAQ,IAAI,QAAQ;EAC1B,MAAM,QAAQ,IAAI,QAAQ,KAAK,MAAM;AAErC,MAAI,UAAU,GACb;EAGD,IAAI,SAAS,IAAI,QAAQ,KAAK,MAAM;AAEpC,MAAI,WAAW,GACd,UAAS,IAAI;WACH,SAAS,OAAO;AAC1B,WAAQ,IAAI,YAAY,KAAK,QAAQ,EAAE,GAAG;AAC1C;;EAGD,MAAM,MAAM,IAAI,MAAM,OAAO,MAAM,CAAC,MAAM;AAC1C,MAAI,CAAC,QAAQ,IAAI,IAAI,EAAE;GACtB,IAAI,MAAM,IAAI,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM;AAC7C,OAAI,IAAI,YAAY,EAAE,KAAK,GAC1B,OAAM,IAAI,MAAM,GAAG,GAAG;AAEvB,WAAQ,IAAI,KAAKC,wBAAU,IAAI,CAAC;;AAGjC,UAAQ,SAAS;;AAGlB,QAAO;;AAGR,MAAM,cAAc,KAAa,OAAe,MAAqB,EAAE,KAAK;CAC3E,IAAIC;AAEJ,KAAI,KAAK,WAAW,SACnB,UAAS,GAAG,YAAY,MAAM,GAAG;UACvB,KAAK,WAAW,OAC1B,UAAS,GAAG,UAAU,MAAM,GAAG;KAE/B,UAAS,GAAG,IAAI,GAAG;AAGpB,KAAI,IAAI,WAAW,YAAY,IAAI,CAAC,IAAI,OACvC,KAAI,SAAS;AAGd,KAAI,IAAI,WAAW,UAAU,EAAE;AAC9B,MAAI,CAAC,IAAI,OACR,KAAI,SAAS;AAGd,MAAI,IAAI,SAAS,IAChB,KAAI,OAAO;AAGZ,MAAI,IAAI,OACP,KAAI,SAAS;;AAIf,KAAI,OAAO,OAAO,IAAI,WAAW,YAAY,IAAI,UAAU,GAAG;AAC7D,MAAI,IAAI,SAAS,OAChB,OAAM,IAAI,MACT,sFACA;AAEF,YAAU,aAAa,KAAK,MAAM,IAAI,OAAO;;AAG9C,KAAI,IAAI,UAAU,IAAI,WAAW,OAChC,WAAU,YAAY,IAAI;AAG3B,KAAI,IAAI,KACP,WAAU,UAAU,IAAI;AAGzB,KAAI,IAAI,SAAS;AAChB,MAAI,IAAI,QAAQ,SAAS,GAAG,KAAK,KAAK,GAAG,OACxC,OAAM,IAAI,MACT,wFACA;AAEF,YAAU,aAAa,IAAI,QAAQ,aAAa;;AAGjD,KAAI,IAAI,SACP,WAAU;AAGX,KAAI,IAAI,OACP,WAAU;AAGX,KAAI,IAAI,SACP,WAAU,cAAc,IAAI,SAAS,OAAO,EAAE,CAAC,aAAa,GAAG,IAAI,SAAS,MAAM,EAAE;AAGrF,KAAI,IAAI,aAAa;AACpB,MAAI,CAAC,IAAI,OACR,KAAI,SAAS;AAEd,YAAU;;AAGX,QAAO;;AAGR,MAAa,mBAAmB,KAAa,OAAe,QAAwB;AACnF,SAAQ,mBAAmB,MAAM;AACjC,QAAO,WAAW,KAAK,OAAO,IAAI;;AAGnC,MAAa,wBAAwB,OACpC,KACA,OACA,QACA,QACI;AACJ,SAAQ,MAAMC,+BAAgB,OAAO,OAAO;AAC5C,QAAO,WAAW,KAAK,OAAO,IAAI"}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
//#region src/cookies.d.ts
|
|
2
|
+
type CookiePrefixOptions = "host" | "secure";
|
|
3
|
+
type CookieOptions = {
|
|
4
|
+
/**
|
|
5
|
+
* Domain of the cookie
|
|
6
|
+
*
|
|
7
|
+
* The Domain attribute specifies which server can receive a cookie. If specified, cookies are
|
|
8
|
+
* available on the specified server and its subdomains. If the it is not
|
|
9
|
+
* specified, the cookies are available on the server that sets it but not on
|
|
10
|
+
* its subdomains.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* `domain: "example.com"`
|
|
14
|
+
*/
|
|
15
|
+
domain?: string;
|
|
16
|
+
/**
|
|
17
|
+
* A lifetime of a cookie. Permanent cookies are deleted after the date specified in the
|
|
18
|
+
* Expires attribute:
|
|
19
|
+
*
|
|
20
|
+
* Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and
|
|
21
|
+
* takes precedence when both are set. The rationale behind this is that when you set an
|
|
22
|
+
* Expires date and time, they're relative to the client the cookie is being set on. If the
|
|
23
|
+
* server is set to a different time, this could cause errors
|
|
24
|
+
*/
|
|
25
|
+
expires?: Date;
|
|
26
|
+
/**
|
|
27
|
+
* Forbids JavaScript from accessing the cookie, for example, through the Document.cookie
|
|
28
|
+
* property. Note that a cookie that has been created with HttpOnly will still be sent with
|
|
29
|
+
* JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().
|
|
30
|
+
* This mitigates attacks against cross-site scripting
|
|
31
|
+
*/
|
|
32
|
+
httpOnly?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Indicates the number of seconds until the cookie expires. A zero or negative number will
|
|
35
|
+
* expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.
|
|
36
|
+
*
|
|
37
|
+
* @example 604800 - 7 days
|
|
38
|
+
*/
|
|
39
|
+
maxAge?: number;
|
|
40
|
+
/**
|
|
41
|
+
* Indicates the path that must exist in the requested URL for the browser to send the Cookie
|
|
42
|
+
* header.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* "/docs"
|
|
46
|
+
* // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.
|
|
47
|
+
*/
|
|
48
|
+
path?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Indicates that the cookie is sent to the server only when a request is made with the https:
|
|
51
|
+
* scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.
|
|
52
|
+
*/
|
|
53
|
+
secure?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Controls whether or not a cookie is sent with cross-site requests, providing some protection
|
|
56
|
+
* against cross-site request forgery attacks (CSRF).
|
|
57
|
+
*
|
|
58
|
+
* Strict - Means that the browser sends the cookie only for same-site requests, that is,
|
|
59
|
+
* requests originating from the same site that set the cookie. If a request originates from a
|
|
60
|
+
* different domain or scheme (even with the same domain), no cookies with the SameSite=Strict
|
|
61
|
+
* attribute are sent.
|
|
62
|
+
*
|
|
63
|
+
* Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load
|
|
64
|
+
* images or frames, but is sent when a user is navigating to the origin site from an external
|
|
65
|
+
* site (for example, when following a link). This is the default behavior if the SameSite
|
|
66
|
+
* attribute is not specified.
|
|
67
|
+
*
|
|
68
|
+
* None - Means that the browser sends the cookie with both cross-site and same-site requests.
|
|
69
|
+
* The Secure attribute must also be set when setting this value.
|
|
70
|
+
*/
|
|
71
|
+
sameSite?: "Strict" | "Lax" | "None" | "strict" | "lax" | "none";
|
|
72
|
+
/**
|
|
73
|
+
* Indicates that the cookie should be stored using partitioned storage. Note that if this is
|
|
74
|
+
* set, the Secure directive must also be set.
|
|
75
|
+
*
|
|
76
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies
|
|
77
|
+
*/
|
|
78
|
+
partitioned?: boolean;
|
|
79
|
+
/**
|
|
80
|
+
* Cooke Prefix
|
|
81
|
+
*
|
|
82
|
+
* - secure: `__Secure-` -> `__Secure-cookie-name`
|
|
83
|
+
* - host: `__Host-` -> `__Host-cookie-name`
|
|
84
|
+
*
|
|
85
|
+
* `secure` must be set to true to use prefixes
|
|
86
|
+
*/
|
|
87
|
+
prefix?: CookiePrefixOptions;
|
|
88
|
+
};
|
|
89
|
+
declare const getCookieKey: (key: string, prefix?: CookiePrefixOptions) => string | undefined;
|
|
90
|
+
/**
|
|
91
|
+
* Parse an HTTP Cookie header string and returning an object of all cookie
|
|
92
|
+
* name-value pairs.
|
|
93
|
+
*
|
|
94
|
+
* Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts
|
|
95
|
+
*
|
|
96
|
+
* @param str the string representing a `Cookie` header value
|
|
97
|
+
*/
|
|
98
|
+
declare function parseCookies(str: string): Map<string, string>;
|
|
99
|
+
declare const serializeCookie: (key: string, value: string, opt?: CookieOptions) => string;
|
|
100
|
+
declare const serializeSignedCookie: (key: string, value: string, secret: string, opt?: CookieOptions) => Promise<string>;
|
|
101
|
+
//#endregion
|
|
102
|
+
export { CookieOptions, CookiePrefixOptions, getCookieKey, parseCookies, serializeCookie, serializeSignedCookie };
|
|
103
|
+
//# sourceMappingURL=cookies.d.cts.map
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
//#region src/cookies.d.ts
|
|
2
|
+
type CookiePrefixOptions = "host" | "secure";
|
|
3
|
+
type CookieOptions = {
|
|
4
|
+
/**
|
|
5
|
+
* Domain of the cookie
|
|
6
|
+
*
|
|
7
|
+
* The Domain attribute specifies which server can receive a cookie. If specified, cookies are
|
|
8
|
+
* available on the specified server and its subdomains. If the it is not
|
|
9
|
+
* specified, the cookies are available on the server that sets it but not on
|
|
10
|
+
* its subdomains.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* `domain: "example.com"`
|
|
14
|
+
*/
|
|
15
|
+
domain?: string;
|
|
16
|
+
/**
|
|
17
|
+
* A lifetime of a cookie. Permanent cookies are deleted after the date specified in the
|
|
18
|
+
* Expires attribute:
|
|
19
|
+
*
|
|
20
|
+
* Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and
|
|
21
|
+
* takes precedence when both are set. The rationale behind this is that when you set an
|
|
22
|
+
* Expires date and time, they're relative to the client the cookie is being set on. If the
|
|
23
|
+
* server is set to a different time, this could cause errors
|
|
24
|
+
*/
|
|
25
|
+
expires?: Date;
|
|
26
|
+
/**
|
|
27
|
+
* Forbids JavaScript from accessing the cookie, for example, through the Document.cookie
|
|
28
|
+
* property. Note that a cookie that has been created with HttpOnly will still be sent with
|
|
29
|
+
* JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().
|
|
30
|
+
* This mitigates attacks against cross-site scripting
|
|
31
|
+
*/
|
|
32
|
+
httpOnly?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Indicates the number of seconds until the cookie expires. A zero or negative number will
|
|
35
|
+
* expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.
|
|
36
|
+
*
|
|
37
|
+
* @example 604800 - 7 days
|
|
38
|
+
*/
|
|
39
|
+
maxAge?: number;
|
|
40
|
+
/**
|
|
41
|
+
* Indicates the path that must exist in the requested URL for the browser to send the Cookie
|
|
42
|
+
* header.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* "/docs"
|
|
46
|
+
* // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.
|
|
47
|
+
*/
|
|
48
|
+
path?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Indicates that the cookie is sent to the server only when a request is made with the https:
|
|
51
|
+
* scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.
|
|
52
|
+
*/
|
|
53
|
+
secure?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Controls whether or not a cookie is sent with cross-site requests, providing some protection
|
|
56
|
+
* against cross-site request forgery attacks (CSRF).
|
|
57
|
+
*
|
|
58
|
+
* Strict - Means that the browser sends the cookie only for same-site requests, that is,
|
|
59
|
+
* requests originating from the same site that set the cookie. If a request originates from a
|
|
60
|
+
* different domain or scheme (even with the same domain), no cookies with the SameSite=Strict
|
|
61
|
+
* attribute are sent.
|
|
62
|
+
*
|
|
63
|
+
* Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load
|
|
64
|
+
* images or frames, but is sent when a user is navigating to the origin site from an external
|
|
65
|
+
* site (for example, when following a link). This is the default behavior if the SameSite
|
|
66
|
+
* attribute is not specified.
|
|
67
|
+
*
|
|
68
|
+
* None - Means that the browser sends the cookie with both cross-site and same-site requests.
|
|
69
|
+
* The Secure attribute must also be set when setting this value.
|
|
70
|
+
*/
|
|
71
|
+
sameSite?: "Strict" | "Lax" | "None" | "strict" | "lax" | "none";
|
|
72
|
+
/**
|
|
73
|
+
* Indicates that the cookie should be stored using partitioned storage. Note that if this is
|
|
74
|
+
* set, the Secure directive must also be set.
|
|
75
|
+
*
|
|
76
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies
|
|
77
|
+
*/
|
|
78
|
+
partitioned?: boolean;
|
|
79
|
+
/**
|
|
80
|
+
* Cooke Prefix
|
|
81
|
+
*
|
|
82
|
+
* - secure: `__Secure-` -> `__Secure-cookie-name`
|
|
83
|
+
* - host: `__Host-` -> `__Host-cookie-name`
|
|
84
|
+
*
|
|
85
|
+
* `secure` must be set to true to use prefixes
|
|
86
|
+
*/
|
|
87
|
+
prefix?: CookiePrefixOptions;
|
|
88
|
+
};
|
|
89
|
+
declare const getCookieKey: (key: string, prefix?: CookiePrefixOptions) => string | undefined;
|
|
90
|
+
/**
|
|
91
|
+
* Parse an HTTP Cookie header string and returning an object of all cookie
|
|
92
|
+
* name-value pairs.
|
|
93
|
+
*
|
|
94
|
+
* Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts
|
|
95
|
+
*
|
|
96
|
+
* @param str the string representing a `Cookie` header value
|
|
97
|
+
*/
|
|
98
|
+
declare function parseCookies(str: string): Map<string, string>;
|
|
99
|
+
declare const serializeCookie: (key: string, value: string, opt?: CookieOptions) => string;
|
|
100
|
+
declare const serializeSignedCookie: (key: string, value: string, secret: string, opt?: CookieOptions) => Promise<string>;
|
|
101
|
+
//#endregion
|
|
102
|
+
export { CookieOptions, CookiePrefixOptions, getCookieKey, parseCookies, serializeCookie, serializeSignedCookie };
|
|
103
|
+
//# sourceMappingURL=cookies.d.mts.map
|
package/dist/cookies.mjs
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { tryDecode } from "./utils.mjs";
|
|
2
|
+
import { signCookieValue } from "./crypto.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/cookies.ts
|
|
5
|
+
const getCookieKey = (key, prefix) => {
|
|
6
|
+
let finalKey = key;
|
|
7
|
+
if (prefix) if (prefix === "secure") finalKey = "__Secure-" + key;
|
|
8
|
+
else if (prefix === "host") finalKey = "__Host-" + key;
|
|
9
|
+
else return;
|
|
10
|
+
return finalKey;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Parse an HTTP Cookie header string and returning an object of all cookie
|
|
14
|
+
* name-value pairs.
|
|
15
|
+
*
|
|
16
|
+
* Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts
|
|
17
|
+
*
|
|
18
|
+
* @param str the string representing a `Cookie` header value
|
|
19
|
+
*/
|
|
20
|
+
function parseCookies(str) {
|
|
21
|
+
if (typeof str !== "string") throw new TypeError("argument str must be a string");
|
|
22
|
+
const cookies = /* @__PURE__ */ new Map();
|
|
23
|
+
let index = 0;
|
|
24
|
+
while (index < str.length) {
|
|
25
|
+
const eqIdx = str.indexOf("=", index);
|
|
26
|
+
if (eqIdx === -1) break;
|
|
27
|
+
let endIdx = str.indexOf(";", index);
|
|
28
|
+
if (endIdx === -1) endIdx = str.length;
|
|
29
|
+
else if (endIdx < eqIdx) {
|
|
30
|
+
index = str.lastIndexOf(";", eqIdx - 1) + 1;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const key = str.slice(index, eqIdx).trim();
|
|
34
|
+
if (!cookies.has(key)) {
|
|
35
|
+
let val = str.slice(eqIdx + 1, endIdx).trim();
|
|
36
|
+
if (val.codePointAt(0) === 34) val = val.slice(1, -1);
|
|
37
|
+
cookies.set(key, tryDecode(val));
|
|
38
|
+
}
|
|
39
|
+
index = endIdx + 1;
|
|
40
|
+
}
|
|
41
|
+
return cookies;
|
|
42
|
+
}
|
|
43
|
+
const _serialize = (key, value, opt = {}) => {
|
|
44
|
+
let cookie;
|
|
45
|
+
if (opt?.prefix === "secure") cookie = `${`__Secure-${key}`}=${value}`;
|
|
46
|
+
else if (opt?.prefix === "host") cookie = `${`__Host-${key}`}=${value}`;
|
|
47
|
+
else cookie = `${key}=${value}`;
|
|
48
|
+
if (key.startsWith("__Secure-") && !opt.secure) opt.secure = true;
|
|
49
|
+
if (key.startsWith("__Host-")) {
|
|
50
|
+
if (!opt.secure) opt.secure = true;
|
|
51
|
+
if (opt.path !== "/") opt.path = "/";
|
|
52
|
+
if (opt.domain) opt.domain = void 0;
|
|
53
|
+
}
|
|
54
|
+
if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) {
|
|
55
|
+
if (opt.maxAge > 3456e4) throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");
|
|
56
|
+
cookie += `; Max-Age=${Math.floor(opt.maxAge)}`;
|
|
57
|
+
}
|
|
58
|
+
if (opt.domain && opt.prefix !== "host") cookie += `; Domain=${opt.domain}`;
|
|
59
|
+
if (opt.path) cookie += `; Path=${opt.path}`;
|
|
60
|
+
if (opt.expires) {
|
|
61
|
+
if (opt.expires.getTime() - Date.now() > 3456e7) throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");
|
|
62
|
+
cookie += `; Expires=${opt.expires.toUTCString()}`;
|
|
63
|
+
}
|
|
64
|
+
if (opt.httpOnly) cookie += "; HttpOnly";
|
|
65
|
+
if (opt.secure) cookie += "; Secure";
|
|
66
|
+
if (opt.sameSite) cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;
|
|
67
|
+
if (opt.partitioned) {
|
|
68
|
+
if (!opt.secure) opt.secure = true;
|
|
69
|
+
cookie += "; Partitioned";
|
|
70
|
+
}
|
|
71
|
+
return cookie;
|
|
72
|
+
};
|
|
73
|
+
const serializeCookie = (key, value, opt) => {
|
|
74
|
+
value = encodeURIComponent(value);
|
|
75
|
+
return _serialize(key, value, opt);
|
|
76
|
+
};
|
|
77
|
+
const serializeSignedCookie = async (key, value, secret, opt) => {
|
|
78
|
+
value = await signCookieValue(value, secret);
|
|
79
|
+
return _serialize(key, value, opt);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
//#endregion
|
|
83
|
+
export { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie };
|
|
84
|
+
//# sourceMappingURL=cookies.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cookies.mjs","names":["cookies: Map<string, string>","cookie: string"],"sources":["../src/cookies.ts"],"sourcesContent":["import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map<string, string> = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (key: string, value: string, opt?: CookieOptions) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n"],"mappings":";;;;AA4FA,MAAa,gBAAgB,KAAa,WAAiC;CAC1E,IAAI,WAAW;AACf,KAAI,OACH,KAAI,WAAW,SACd,YAAW,cAAc;UACf,WAAW,OACrB,YAAW,YAAY;KAEvB;AAGF,QAAO;;;;;;;;;;AAWR,SAAgB,aAAa,KAAa;AACzC,KAAI,OAAO,QAAQ,SAClB,OAAM,IAAI,UAAU,gCAAgC;CAGrD,MAAMA,0BAA+B,IAAI,KAAK;CAE9C,IAAI,QAAQ;AACZ,QAAO,QAAQ,IAAI,QAAQ;EAC1B,MAAM,QAAQ,IAAI,QAAQ,KAAK,MAAM;AAErC,MAAI,UAAU,GACb;EAGD,IAAI,SAAS,IAAI,QAAQ,KAAK,MAAM;AAEpC,MAAI,WAAW,GACd,UAAS,IAAI;WACH,SAAS,OAAO;AAC1B,WAAQ,IAAI,YAAY,KAAK,QAAQ,EAAE,GAAG;AAC1C;;EAGD,MAAM,MAAM,IAAI,MAAM,OAAO,MAAM,CAAC,MAAM;AAC1C,MAAI,CAAC,QAAQ,IAAI,IAAI,EAAE;GACtB,IAAI,MAAM,IAAI,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM;AAC7C,OAAI,IAAI,YAAY,EAAE,KAAK,GAC1B,OAAM,IAAI,MAAM,GAAG,GAAG;AAEvB,WAAQ,IAAI,KAAK,UAAU,IAAI,CAAC;;AAGjC,UAAQ,SAAS;;AAGlB,QAAO;;AAGR,MAAM,cAAc,KAAa,OAAe,MAAqB,EAAE,KAAK;CAC3E,IAAIC;AAEJ,KAAI,KAAK,WAAW,SACnB,UAAS,GAAG,YAAY,MAAM,GAAG;UACvB,KAAK,WAAW,OAC1B,UAAS,GAAG,UAAU,MAAM,GAAG;KAE/B,UAAS,GAAG,IAAI,GAAG;AAGpB,KAAI,IAAI,WAAW,YAAY,IAAI,CAAC,IAAI,OACvC,KAAI,SAAS;AAGd,KAAI,IAAI,WAAW,UAAU,EAAE;AAC9B,MAAI,CAAC,IAAI,OACR,KAAI,SAAS;AAGd,MAAI,IAAI,SAAS,IAChB,KAAI,OAAO;AAGZ,MAAI,IAAI,OACP,KAAI,SAAS;;AAIf,KAAI,OAAO,OAAO,IAAI,WAAW,YAAY,IAAI,UAAU,GAAG;AAC7D,MAAI,IAAI,SAAS,OAChB,OAAM,IAAI,MACT,sFACA;AAEF,YAAU,aAAa,KAAK,MAAM,IAAI,OAAO;;AAG9C,KAAI,IAAI,UAAU,IAAI,WAAW,OAChC,WAAU,YAAY,IAAI;AAG3B,KAAI,IAAI,KACP,WAAU,UAAU,IAAI;AAGzB,KAAI,IAAI,SAAS;AAChB,MAAI,IAAI,QAAQ,SAAS,GAAG,KAAK,KAAK,GAAG,OACxC,OAAM,IAAI,MACT,wFACA;AAEF,YAAU,aAAa,IAAI,QAAQ,aAAa;;AAGjD,KAAI,IAAI,SACP,WAAU;AAGX,KAAI,IAAI,OACP,WAAU;AAGX,KAAI,IAAI,SACP,WAAU,cAAc,IAAI,SAAS,OAAO,EAAE,CAAC,aAAa,GAAG,IAAI,SAAS,MAAM,EAAE;AAGrF,KAAI,IAAI,aAAa;AACpB,MAAI,CAAC,IAAI,OACR,KAAI,SAAS;AAEd,YAAU;;AAGX,QAAO;;AAGR,MAAa,mBAAmB,KAAa,OAAe,QAAwB;AACnF,SAAQ,mBAAmB,MAAM;AACjC,QAAO,WAAW,KAAK,OAAO,IAAI;;AAGnC,MAAa,wBAAwB,OACpC,KACA,OACA,QACA,QACI;AACJ,SAAQ,MAAM,gBAAgB,OAAO,OAAO;AAC5C,QAAO,WAAW,KAAK,OAAO,IAAI"}
|
package/dist/crypto.cjs
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let __better_auth_utils = require("@better-auth/utils");
|
|
3
|
+
|
|
4
|
+
//#region src/crypto.ts
|
|
5
|
+
const algorithm = {
|
|
6
|
+
name: "HMAC",
|
|
7
|
+
hash: "SHA-256"
|
|
8
|
+
};
|
|
9
|
+
const getCryptoKey = async (secret) => {
|
|
10
|
+
const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
|
|
11
|
+
return await (0, __better_auth_utils.getWebcryptoSubtle)().importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]);
|
|
12
|
+
};
|
|
13
|
+
const verifySignature = async (base64Signature, value, secret) => {
|
|
14
|
+
try {
|
|
15
|
+
const signatureBinStr = atob(base64Signature);
|
|
16
|
+
const signature = new Uint8Array(signatureBinStr.length);
|
|
17
|
+
for (let i = 0, len = signatureBinStr.length; i < len; i++) signature[i] = signatureBinStr.charCodeAt(i);
|
|
18
|
+
return await (0, __better_auth_utils.getWebcryptoSubtle)().verify(algorithm, secret, signature, new TextEncoder().encode(value));
|
|
19
|
+
} catch (e) {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
const makeSignature = async (value, secret) => {
|
|
24
|
+
const key = await getCryptoKey(secret);
|
|
25
|
+
const signature = await (0, __better_auth_utils.getWebcryptoSubtle)().sign(algorithm.name, key, new TextEncoder().encode(value));
|
|
26
|
+
return btoa(String.fromCharCode(...new Uint8Array(signature)));
|
|
27
|
+
};
|
|
28
|
+
const signCookieValue = async (value, secret) => {
|
|
29
|
+
const signature = await makeSignature(value, secret);
|
|
30
|
+
value = `${value}.${signature}`;
|
|
31
|
+
value = encodeURIComponent(value);
|
|
32
|
+
return value;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
//#endregion
|
|
36
|
+
exports.getCryptoKey = getCryptoKey;
|
|
37
|
+
exports.signCookieValue = signCookieValue;
|
|
38
|
+
exports.verifySignature = verifySignature;
|
|
39
|
+
//# sourceMappingURL=crypto.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crypto.cjs","names":[],"sources":["../src/crypto.ts"],"sourcesContent":["import { getWebcryptoSubtle } from \"@better-auth/utils\";\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nexport const getCryptoKey = async (secret: string | BufferSource) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await getWebcryptoSubtle().importKey(\"raw\", secretBuf, algorithm, false, [\n\t\t\"sign\",\n\t\t\"verify\",\n\t]);\n};\n\nexport const verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await getWebcryptoSubtle().verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await getWebcryptoSubtle().sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nexport const signCookieValue = async (value: string, secret: string | BufferSource) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\n};\n"],"mappings":";;;;AACA,MAAM,YAAY;CAAE,MAAM;CAAQ,MAAM;CAAW;AAEnD,MAAa,eAAe,OAAO,WAAkC;CACpE,MAAM,YAAY,OAAO,WAAW,WAAW,IAAI,aAAa,CAAC,OAAO,OAAO,GAAG;AAClF,QAAO,mDAA0B,CAAC,UAAU,OAAO,WAAW,WAAW,OAAO,CAC/E,QACA,SACA,CAAC;;AAGH,MAAa,kBAAkB,OAC9B,iBACA,OACA,WACsB;AACtB,KAAI;EACH,MAAM,kBAAkB,KAAK,gBAAgB;EAC7C,MAAM,YAAY,IAAI,WAAW,gBAAgB,OAAO;AACxD,OAAK,IAAI,IAAI,GAAG,MAAM,gBAAgB,QAAQ,IAAI,KAAK,IACtD,WAAU,KAAK,gBAAgB,WAAW,EAAE;AAE7C,SAAO,mDAA0B,CAAC,OACjC,WACA,QACA,WACA,IAAI,aAAa,CAAC,OAAO,MAAM,CAC/B;UACO,GAAG;AACX,SAAO;;;AAIT,MAAM,gBAAgB,OAAO,OAAe,WAAmD;CAC9F,MAAM,MAAM,MAAM,aAAa,OAAO;CACtC,MAAM,YAAY,mDAA0B,CAAC,KAC5C,UAAU,MACV,KACA,IAAI,aAAa,CAAC,OAAO,MAAM,CAC/B;AAED,QAAO,KAAK,OAAO,aAAa,GAAG,IAAI,WAAW,UAAU,CAAC,CAAC;;AAG/D,MAAa,kBAAkB,OAAO,OAAe,WAAkC;CACtF,MAAM,YAAY,MAAM,cAAc,OAAO,OAAO;AACpD,SAAQ,GAAG,MAAM,GAAG;AACpB,SAAQ,mBAAmB,MAAM;AACjC,QAAO"}
|
package/dist/crypto.mjs
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { getWebcryptoSubtle } from "@better-auth/utils";
|
|
2
|
+
|
|
3
|
+
//#region src/crypto.ts
|
|
4
|
+
const algorithm = {
|
|
5
|
+
name: "HMAC",
|
|
6
|
+
hash: "SHA-256"
|
|
7
|
+
};
|
|
8
|
+
const getCryptoKey = async (secret) => {
|
|
9
|
+
const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
|
|
10
|
+
return await getWebcryptoSubtle().importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]);
|
|
11
|
+
};
|
|
12
|
+
const verifySignature = async (base64Signature, value, secret) => {
|
|
13
|
+
try {
|
|
14
|
+
const signatureBinStr = atob(base64Signature);
|
|
15
|
+
const signature = new Uint8Array(signatureBinStr.length);
|
|
16
|
+
for (let i = 0, len = signatureBinStr.length; i < len; i++) signature[i] = signatureBinStr.charCodeAt(i);
|
|
17
|
+
return await getWebcryptoSubtle().verify(algorithm, secret, signature, new TextEncoder().encode(value));
|
|
18
|
+
} catch (e) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
const makeSignature = async (value, secret) => {
|
|
23
|
+
const key = await getCryptoKey(secret);
|
|
24
|
+
const signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value));
|
|
25
|
+
return btoa(String.fromCharCode(...new Uint8Array(signature)));
|
|
26
|
+
};
|
|
27
|
+
const signCookieValue = async (value, secret) => {
|
|
28
|
+
const signature = await makeSignature(value, secret);
|
|
29
|
+
value = `${value}.${signature}`;
|
|
30
|
+
value = encodeURIComponent(value);
|
|
31
|
+
return value;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
export { getCryptoKey, signCookieValue, verifySignature };
|
|
36
|
+
//# sourceMappingURL=crypto.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crypto.mjs","names":[],"sources":["../src/crypto.ts"],"sourcesContent":["import { getWebcryptoSubtle } from \"@better-auth/utils\";\nconst algorithm = { name: \"HMAC\", hash: \"SHA-256\" };\n\nexport const getCryptoKey = async (secret: string | BufferSource) => {\n\tconst secretBuf = typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\treturn await getWebcryptoSubtle().importKey(\"raw\", secretBuf, algorithm, false, [\n\t\t\"sign\",\n\t\t\"verify\",\n\t]);\n};\n\nexport const verifySignature = async (\n\tbase64Signature: string,\n\tvalue: string,\n\tsecret: CryptoKey,\n): Promise<boolean> => {\n\ttry {\n\t\tconst signatureBinStr = atob(base64Signature);\n\t\tconst signature = new Uint8Array(signatureBinStr.length);\n\t\tfor (let i = 0, len = signatureBinStr.length; i < len; i++) {\n\t\t\tsignature[i] = signatureBinStr.charCodeAt(i);\n\t\t}\n\t\treturn await getWebcryptoSubtle().verify(\n\t\t\talgorithm,\n\t\t\tsecret,\n\t\t\tsignature,\n\t\t\tnew TextEncoder().encode(value),\n\t\t);\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\n\nconst makeSignature = async (value: string, secret: string | BufferSource): Promise<string> => {\n\tconst key = await getCryptoKey(secret);\n\tconst signature = await getWebcryptoSubtle().sign(\n\t\talgorithm.name,\n\t\tkey,\n\t\tnew TextEncoder().encode(value),\n\t);\n\t// the returned base64 encoded signature will always be 44 characters long and end with one or two equal signs\n\treturn btoa(String.fromCharCode(...new Uint8Array(signature)));\n};\n\nexport const signCookieValue = async (value: string, secret: string | BufferSource) => {\n\tconst signature = await makeSignature(value, secret);\n\tvalue = `${value}.${signature}`;\n\tvalue = encodeURIComponent(value);\n\treturn value;\n};\n"],"mappings":";;;AACA,MAAM,YAAY;CAAE,MAAM;CAAQ,MAAM;CAAW;AAEnD,MAAa,eAAe,OAAO,WAAkC;CACpE,MAAM,YAAY,OAAO,WAAW,WAAW,IAAI,aAAa,CAAC,OAAO,OAAO,GAAG;AAClF,QAAO,MAAM,oBAAoB,CAAC,UAAU,OAAO,WAAW,WAAW,OAAO,CAC/E,QACA,SACA,CAAC;;AAGH,MAAa,kBAAkB,OAC9B,iBACA,OACA,WACsB;AACtB,KAAI;EACH,MAAM,kBAAkB,KAAK,gBAAgB;EAC7C,MAAM,YAAY,IAAI,WAAW,gBAAgB,OAAO;AACxD,OAAK,IAAI,IAAI,GAAG,MAAM,gBAAgB,QAAQ,IAAI,KAAK,IACtD,WAAU,KAAK,gBAAgB,WAAW,EAAE;AAE7C,SAAO,MAAM,oBAAoB,CAAC,OACjC,WACA,QACA,WACA,IAAI,aAAa,CAAC,OAAO,MAAM,CAC/B;UACO,GAAG;AACX,SAAO;;;AAIT,MAAM,gBAAgB,OAAO,OAAe,WAAmD;CAC9F,MAAM,MAAM,MAAM,aAAa,OAAO;CACtC,MAAM,YAAY,MAAM,oBAAoB,CAAC,KAC5C,UAAU,MACV,KACA,IAAI,aAAa,CAAC,OAAO,MAAM,CAC/B;AAED,QAAO,KAAK,OAAO,aAAa,GAAG,IAAI,WAAW,UAAU,CAAC,CAAC;;AAG/D,MAAa,kBAAkB,OAAO,OAAe,WAAkC;CACtF,MAAM,YAAY,MAAM,cAAc,OAAO,OAAO;AACpD,SAAQ,GAAG,MAAM,GAAG;AACpB,SAAQ,mBAAmB,MAAM;AACjC,QAAO"}
|