unjwt 0.8.1 → 0.8.3

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.
Files changed (37) hide show
  1. package/README.md +4 -4
  2. package/dist/THIRD-PARTY-LICENSES.md.gz +0 -0
  3. package/dist/_chunks/_codec-jwe.d.mts +101 -22
  4. package/dist/_chunks/_codec-jws.mjs +306 -232
  5. package/dist/_chunks/_cookie-attributes.d.mts +12 -0
  6. package/dist/_chunks/_jwt-internal.mjs +9 -6
  7. package/dist/_chunks/digest.d.mts +8 -0
  8. package/dist/_chunks/{algorithms.mjs → digest.mjs} +78 -8
  9. package/dist/_chunks/index.d.mts +313 -268
  10. package/dist/_chunks/index2.d.mts +2 -1
  11. package/dist/_chunks/index3.d.mts +1 -0
  12. package/dist/_chunks/jwe.d.mts +4 -4
  13. package/dist/_chunks/jwe.mjs +21 -3
  14. package/dist/_chunks/jwk.mjs +219 -173
  15. package/dist/_chunks/jws.d.mts +10 -10
  16. package/dist/_chunks/jws.mjs +18 -6
  17. package/dist/_chunks/jwt.d.mts +2 -1
  18. package/dist/_chunks/libs/cookie-es.mjs +255 -0
  19. package/dist/adapters/elysia/index.d.mts +32 -15
  20. package/dist/adapters/elysia/index.mjs +46 -67
  21. package/dist/adapters/h3/index.d.mts +135 -0
  22. package/dist/adapters/h3/index.mjs +119 -0
  23. package/dist/adapters/h3v1/index.d.mts +100 -27
  24. package/dist/adapters/h3v1/index.mjs +59 -76
  25. package/dist/core/jwe.d.mts +2 -2
  26. package/dist/core/jwk.d.mts +22 -14
  27. package/dist/core/jwk.mjs +2 -2
  28. package/dist/core/jws.d.mts +2 -2
  29. package/dist/core/utils/index.d.mts +2 -1
  30. package/dist/core/utils/index.mjs +2 -2
  31. package/dist/index.d.mts +4 -3
  32. package/dist/index.mjs +3 -3
  33. package/dist/session/index.d.mts +44 -0
  34. package/dist/session/index.mjs +113 -0
  35. package/package.json +37 -18
  36. package/dist/adapters/h3v2/index.d.mts +0 -65
  37. package/dist/adapters/h3v2/index.mjs +0 -139
@@ -1,4 +1,4 @@
1
- import { JOSEPayload, JOSEPayloadMode, JWKLookupFunction, JWKSet, JWSAlgorithm, JWSFlattenedSerialization, JWSGeneralSerialization, JWSMultiSignOptions, JWSMultiSigner, JWSMultiVerifyAllOptions, JWSMultiVerifyOptions, JWSMultiVerifyOutcome, JWSMultiVerifyResult, JWSSignJWK, JWSSignOptions, JWSVerifyJWK, JWSVerifyOptions, JWSVerifyResult, JWTClaims, PayloadOf } from "./index.mjs";
1
+ import { JOSEPayload, JOSEPayloadMode, JWKSet, JWSAlgorithm, JWSFlattenedSerialization, JWSGeneralSerialization, JWSKeyLookup, JWSMultiSignOptions, JWSMultiSigner, JWSMultiVerifyAllOptions, JWSMultiVerifyOptions, JWSMultiVerifyOutcome, JWSMultiVerifyResult, JWSSignJWK, JWSSignOptions, JWSVerifyJWK, JWSVerifyOptions, JWSVerifyResult, JWTClaims, PayloadOf } from "./index.mjs";
2
2
  import "./_internal.mjs";
3
3
  /**
4
4
  * Signs a payload with multiple signers as a JWS General JSON Serialization (RFC 7515 §7.2.1).
@@ -11,14 +11,14 @@ export declare function signMulti(payload: JOSEPayload, signers: JWSMultiSigner[
11
11
  * Per-signature failures are collected and the last one is thrown when none verifies.
12
12
  * The payload type follows `options.payload`, as in `verify`.
13
13
  */
14
- export declare function verifyMulti<T extends object = JWTClaims>(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyOrLookup: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWKLookupFunction, options?: JWSMultiVerifyOptions<"json"> & {
14
+ export declare function verifyMulti<T extends object = JWTClaims>(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyOrLookup: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWSKeyLookup, options?: JWSMultiVerifyOptions<"json"> & {
15
15
  forceUint8Array?: false;
16
16
  }): Promise<JWSMultiVerifyResult<T>>;
17
17
  /** @deprecated `forceUint8Array` is replaced by `payload: "bytes"`; removed in v0.9.0. */
18
- export declare function verifyMulti(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyOrLookup: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWKLookupFunction, options: JWSMultiVerifyOptions & {
18
+ export declare function verifyMulti(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyOrLookup: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWSKeyLookup, options: JWSMultiVerifyOptions & {
19
19
  forceUint8Array: true;
20
20
  }): Promise<JWSMultiVerifyResult<Uint8Array<ArrayBuffer>>>;
21
- export declare function verifyMulti<Mode extends JOSEPayloadMode = JOSEPayloadMode>(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyOrLookup: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWKLookupFunction, options?: JWSMultiVerifyOptions<Mode>): Promise<JWSMultiVerifyResult<PayloadOf<Mode>>>;
21
+ export declare function verifyMulti<Mode extends JOSEPayloadMode = JOSEPayloadMode>(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyOrLookup: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWSKeyLookup, options?: JWSMultiVerifyOptions<Mode>): Promise<JWSMultiVerifyResult<PayloadOf<Mode>>>;
22
22
  /**
23
23
  * Verifies every signature independently and returns one outcome per signature; only
24
24
  * a malformed envelope throws (`ERR_JWS_INVALID_SERIALIZATION`). The payload type follows `options.payload`.
@@ -27,14 +27,14 @@ export declare function verifyMulti<Mode extends JOSEPayloadMode = JOSEPayloadMo
27
27
  * const outcomes = await verifyMultiAll(jws, (header) => jwkSet);
28
28
  * if (!outcomes.every((o) => o.verified)) throw new Error("not all signatures verified");
29
29
  */
30
- export declare function verifyMultiAll<T extends object = JWTClaims>(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyResolver: JWKLookupFunction, options?: JWSMultiVerifyAllOptions<"json"> & {
30
+ export declare function verifyMultiAll<T extends object = JWTClaims>(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyResolver: JWSKeyLookup, options?: JWSMultiVerifyAllOptions<"json"> & {
31
31
  forceUint8Array?: false;
32
32
  }): Promise<JWSMultiVerifyOutcome<T>[]>;
33
33
  /** @deprecated `forceUint8Array` is replaced by `payload: "bytes"`; removed in v0.9.0. */
34
- export declare function verifyMultiAll(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyResolver: JWKLookupFunction, options: JWSMultiVerifyAllOptions & {
34
+ export declare function verifyMultiAll(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyResolver: JWSKeyLookup, options: JWSMultiVerifyAllOptions & {
35
35
  forceUint8Array: true;
36
36
  }): Promise<JWSMultiVerifyOutcome<Uint8Array<ArrayBuffer>>[]>;
37
- export declare function verifyMultiAll<Mode extends JOSEPayloadMode = JOSEPayloadMode>(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyResolver: JWKLookupFunction, options?: JWSMultiVerifyAllOptions<Mode>): Promise<JWSMultiVerifyOutcome<PayloadOf<Mode>>[]>;
37
+ export declare function verifyMultiAll<Mode extends JOSEPayloadMode = JOSEPayloadMode>(jws: JWSGeneralSerialization | JWSFlattenedSerialization, keyResolver: JWSKeyLookup, options?: JWSMultiVerifyAllOptions<Mode>): Promise<JWSMultiVerifyOutcome<PayloadOf<Mode>>[]>;
38
38
  /** Converts a single-signature General JWS to Flattened form (RFC 7515 §7.2.2); otherwise `ERR_JWS_INVALID_SERIALIZATION`. */
39
39
  export declare function generalToFlattenedJWS(jws: JWSGeneralSerialization): JWSFlattenedSerialization;
40
40
  /** Creates a JWS Compact Serialization; an object payload is JSON-serialized, `alg` is required unless the JWK carries one. */
@@ -46,11 +46,11 @@ export declare function sign(payload: JOSEPayload, key: CryptoKey | Uint8Array<A
46
46
  * Verifies a JWS Compact Serialization against a key, JWK Set or key resolver.
47
47
  * The payload type follows `options.payload`: claims `T` for `"json"` (default), `string`, or `Uint8Array`.
48
48
  */
49
- export declare function verify<T extends object = JWTClaims>(jws: string, key: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWKLookupFunction, options?: JWSVerifyOptions<"json"> & {
49
+ export declare function verify<T extends object = JWTClaims>(jws: string, key: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWSKeyLookup, options?: JWSVerifyOptions<"json"> & {
50
50
  forceUint8Array?: false;
51
51
  }): Promise<JWSVerifyResult<T>>;
52
52
  /** @deprecated `forceUint8Array` is replaced by `payload: "bytes"`; removed in v0.9.0. */
53
- export declare function verify(jws: string, key: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWKLookupFunction, options: JWSVerifyOptions & {
53
+ export declare function verify(jws: string, key: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWSKeyLookup, options: JWSVerifyOptions & {
54
54
  forceUint8Array: true;
55
55
  }): Promise<JWSVerifyResult<Uint8Array<ArrayBuffer>>>;
56
- export declare function verify<Mode extends JOSEPayloadMode = JOSEPayloadMode>(jws: string, key: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWKLookupFunction, options?: JWSVerifyOptions<Mode>): Promise<JWSVerifyResult<PayloadOf<Mode>>>;
56
+ export declare function verify<Mode extends JOSEPayloadMode = JOSEPayloadMode>(jws: string, key: CryptoKey | JWKSet | JWSVerifyJWK | Uint8Array<ArrayBuffer> | JWSKeyLookup, options?: JWSVerifyOptions<Mode>): Promise<JWSVerifyResult<PayloadOf<Mode>>>;
@@ -1,7 +1,7 @@
1
1
  import { sanitizeObjectCopy, textEncoder } from "./libs/unsecure.mjs";
2
2
  import { JWTError, applyTypDefault, base64UrlStringify, computeJwtTimeClaims, getPlaintextBytes, isJWK, isJWKSet, parsePayloadText, validateCriticalHeadersJWS } from "./_jwt-internal.mjs";
3
- import { inferJWSAllowedAlgorithms } from "./algorithms.mjs";
4
- import { JWS_ALG_CTX, applyB64Header, asJWTError, asKeyLookupError, asKeyUsageError, assertB64Option, assertCompactToken, assertConsumerOptions, assertEntryLimit, assertJWKSetCandidates, assertNotStringKey, assertOptionEntry, assertProducerCrit, assertProtectedOnlyOption, assertSerializationObject, buildJWKSetFilter, checkAlgAllowed, checkJWSAlgSupported, checkJWSB64, checkProtectedTyp, checkSerializationEntry, decodeJWSPayload, decodeProtectedHeader, decodeSegment, getJWKsFromSet, importKey, keyMatchesHeader, resolveKeyInput, resolveLimit, resolvePayloadMode, resolveSigningKey, serializeProtectedHeader, sign as sign$1, stringKeyError, validateClaimsIfJson, verify as verify$1 } from "./jwk.mjs";
3
+ import { inferJWSAllowedAlgorithms } from "./digest.mjs";
4
+ import { JWS_ALG_CTX, applyB64Header, asJWTError, asKeyLookupError, asKeyUsageError, assertB64Option, assertCompactToken, assertConsumerOptions, assertEntryLimit, assertJWKSetCandidates, assertJWSAlgSupported, assertNotStringKey, assertOptionEntry, assertProducerConfirmation, assertProducerCrit, assertProducerKeyHeaders, assertProtectedOnlyOption, assertSerializationObject, buildJWKSetFilter, checkAlgAllowed, checkJWSAlgSupported, checkJWSB64, checkProtectedTyp, checkSerializationEntry, decodeJWSPayload, decodeProtectedHeader, decodeSegment, getJWKsFromSet, importKey, keyMatchesHeader, resolveKeyInput, resolveLimit, resolvePayloadMode, resolveSigningKey, serializeProtectedHeader, sign as sign$1, stringKeyError, validateClaimsIfJson, verify as verify$1 } from "./jwk.mjs";
5
5
  function buildJWSProtectedHeader(alg, key, userHeader, options) {
6
6
  const safeHeader = sanitizeObjectCopy(userHeader);
7
7
  const header = {};
@@ -66,8 +66,17 @@ async function signMulti(payload, signers, options = {}) {
66
66
  tier: "unprotected",
67
67
  family: "JWS"
68
68
  });
69
+ assertProducerKeyHeaders(signer.protectedHeader, {
70
+ tier: "protected",
71
+ family: "JWS"
72
+ });
73
+ assertProducerKeyHeaders(signer.unprotectedHeader, {
74
+ tier: "unprotected",
75
+ family: "JWS"
76
+ });
69
77
  assertB64Option(signer.protectedHeader);
70
78
  }
79
+ assertProducerConfirmation(payload);
71
80
  const resolvedAlgs = signers.map((s, i) => _resolveSignerAlg(s, i));
72
81
  const b64 = _resolveB64(signers);
73
82
  const computedPayload = computeJwtTimeClaims(payload, options);
@@ -449,13 +458,17 @@ async function sign(payload, key, options = {}) {
449
458
  });
450
459
  assertNotStringKey(key);
451
460
  const { protectedHeader: userHeader } = options;
461
+ assertProducerKeyHeaders(userHeader, {
462
+ tier: "protected",
463
+ family: "JWS"
464
+ });
465
+ assertProducerConfirmation(payload);
452
466
  let { alg } = options;
453
467
  if (!alg) {
454
468
  if (isJWK(key) && key.alg) alg = key.alg;
455
469
  else throw new JWTError("JWS \"alg\" (Algorithm) must be provided in options", "ERR_JWS_ALG_MISSING");
456
470
  }
457
- const algSupportError = checkJWSAlgSupported(alg);
458
- if (algSupportError) throw algSupportError;
471
+ assertJWSAlgSupported(alg);
459
472
  let signingKey;
460
473
  try {
461
474
  signingKey = await resolveSigningKey(alg, await importKey(key, {
@@ -498,8 +511,7 @@ async function verify(jws, key, options = {}) {
498
511
  const protectedHeader = decodeProtectedHeader(protectedHeaderEncoded, "JWS");
499
512
  if (!protectedHeader.alg) throw new JWTError("Invalid JWS: Protected header must be an object with an \"alg\" property.", "ERR_JWS_INVALID");
500
513
  const alg = protectedHeader.alg;
501
- const algSupportError = checkJWSAlgSupported(alg);
502
- if (algSupportError) throw algSupportError;
514
+ assertJWSAlgSupported(alg);
503
515
  const headerError = checkJWSB64(protectedHeader) ?? checkProtectedTyp(options.typ, protectedHeader, { family: "JWS" });
504
516
  if (headerError) throw headerError;
505
517
  const signatureBytes = decodeSegment(signatureEncoded, {
@@ -24,7 +24,8 @@ export declare function getPlaintextBytes(payload: JOSEPayload): Uint8Array<Arra
24
24
  export type ComputeJwtTimeClaimsOptions = JWTTimeClaimOptions;
25
25
  /**
26
26
  * Return a copy of an object payload with `iat` and the requested `exp` / `nbf`, or `undefined` when none applies.
27
- * Both members of `expiresIn`/`expiresAt` or `notBeforeIn`/`notBeforeAt` throw `ERR_JWT_CLAIM_INVALID`.
27
+ * `currentDate` is the clock: `iat` when written, and the base of `expiresIn` / `notBeforeIn`;
28
+ * `issuedAt` writes `iat` alone, a `Date` as that instant. Both members of `expiresIn`/`expiresAt` or `notBeforeIn`/`notBeforeAt` throw `ERR_JWT_CLAIM_INVALID`.
28
29
  */
29
30
  export declare function computeJwtTimeClaims(payload: unknown, options?: ComputeJwtTimeClaimsOptions): JWTClaims | undefined;
30
31
  /** Validate critical headers in JWS semantics. */
@@ -0,0 +1,255 @@
1
+ const COOKIE_MAX_AGE_LIMIT = 3456e4;
2
+ function endIndex(str, min, len) {
3
+ const index = str.indexOf(";", min);
4
+ return index === -1 ? len : index;
5
+ }
6
+ function eqIndex(str, min, max) {
7
+ const index = str.indexOf("=", min);
8
+ return index < max ? index : -1;
9
+ }
10
+ function valueSlice(str, min, max) {
11
+ if (min === max) return "";
12
+ let start = min;
13
+ let end = max;
14
+ do {
15
+ const code = str.charCodeAt(start);
16
+ if (code !== 32 && code !== 9) break;
17
+ } while (++start < end);
18
+ while (end > start) {
19
+ const code = str.charCodeAt(end - 1);
20
+ if (code !== 32 && code !== 9) break;
21
+ end--;
22
+ }
23
+ return str.slice(start, end);
24
+ }
25
+ const NullObject = /* @__PURE__ */ (() => {
26
+ const C = function() {};
27
+ C.prototype = Object.create(null);
28
+ return C;
29
+ })();
30
+ function parse(str, options) {
31
+ const obj = new NullObject();
32
+ const len = str.length;
33
+ if (len < 2) return obj;
34
+ const dec = options?.decode || decode;
35
+ const allowMultiple = options?.allowMultiple || false;
36
+ let index = 0;
37
+ do {
38
+ const eqIdx = eqIndex(str, index, len);
39
+ if (eqIdx === -1) break;
40
+ const endIdx = endIndex(str, index, len);
41
+ if (eqIdx > endIdx) {
42
+ index = str.lastIndexOf(";", eqIdx - 1) + 1;
43
+ continue;
44
+ }
45
+ const key = valueSlice(str, index, eqIdx);
46
+ if (options?.filter && !options.filter(key)) {
47
+ index = endIdx + 1;
48
+ continue;
49
+ }
50
+ const val = dec(valueSlice(str, eqIdx + 1, endIdx));
51
+ if (allowMultiple) {
52
+ const existing = obj[key];
53
+ if (existing === void 0) obj[key] = val;
54
+ else if (Array.isArray(existing)) existing.push(val);
55
+ else obj[key] = [existing, val];
56
+ } else if (obj[key] === void 0) obj[key] = val;
57
+ index = endIdx + 1;
58
+ } while (index < len);
59
+ return obj;
60
+ }
61
+ function decode(str) {
62
+ if (!str.includes("%")) return str;
63
+ try {
64
+ return decodeURIComponent(str);
65
+ } catch {
66
+ return str;
67
+ }
68
+ }
69
+ const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
70
+ const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
71
+ const domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
72
+ const pathValueRegExp = /^[\u0020-\u003A\u003C-\u007E]*$/;
73
+ const __toString = Object.prototype.toString;
74
+ function serialize(_a0, _a1, _a2) {
75
+ const isObj = typeof _a0 === "object" && _a0 !== null;
76
+ const options = isObj ? _a1 : _a2;
77
+ const stringify = options?.stringify || JSON.stringify;
78
+ const cookie = isObj ? _a0 : {
79
+ ..._a2,
80
+ name: _a0,
81
+ value: _a1 == void 0 ? "" : typeof _a1 === "string" ? _a1 : stringify(_a1)
82
+ };
83
+ const enc = options?.encode || encodeURIComponent;
84
+ if (!cookieNameRegExp.test(cookie.name)) throw new TypeError(`argument name is invalid: ${cookie.name}`);
85
+ const value = cookie.value ? enc(cookie.value) : "";
86
+ if (!cookieValueRegExp.test(value)) throw new TypeError(`argument val is invalid: ${cookie.value}`);
87
+ if (!cookie.secure) {
88
+ if (cookie.partitioned) throw new TypeError(`Partitioned cookies must have the Secure attribute`);
89
+ if (cookie.sameSite && String(cookie.sameSite).toLowerCase() === "none") throw new TypeError(`SameSite=None cookies must have the Secure attribute`);
90
+ if (cookie.name.length > 9 && cookie.name.charCodeAt(0) === 95 && cookie.name.charCodeAt(1) === 95) {
91
+ const nameLower = cookie.name.toLowerCase();
92
+ if (nameLower.startsWith("__secure-") || nameLower.startsWith("__host-")) throw new TypeError(`${cookie.name} cookies must have the Secure attribute`);
93
+ }
94
+ }
95
+ if (cookie.name.length > 7 && cookie.name.charCodeAt(0) === 95 && cookie.name.charCodeAt(1) === 95 && cookie.name.toLowerCase().startsWith("__host-")) {
96
+ if (cookie.path !== "/") throw new TypeError(`__Host- cookies must have Path=/`);
97
+ if (cookie.domain) throw new TypeError(`__Host- cookies must not have a Domain attribute`);
98
+ }
99
+ let str = cookie.name + "=" + value;
100
+ if (cookie.maxAge !== void 0) {
101
+ if (!Number.isInteger(cookie.maxAge)) throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);
102
+ str += "; Max-Age=" + Math.max(0, Math.min(cookie.maxAge, COOKIE_MAX_AGE_LIMIT));
103
+ }
104
+ if (cookie.domain) {
105
+ if (!domainValueRegExp.test(cookie.domain)) throw new TypeError(`option domain is invalid: ${cookie.domain}`);
106
+ str += "; Domain=" + cookie.domain;
107
+ }
108
+ if (cookie.path) {
109
+ if (!pathValueRegExp.test(cookie.path)) throw new TypeError(`option path is invalid: ${cookie.path}`);
110
+ str += "; Path=" + cookie.path;
111
+ }
112
+ if (cookie.expires) {
113
+ if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) throw new TypeError(`option expires is invalid: ${cookie.expires}`);
114
+ str += "; Expires=" + cookie.expires.toUTCString();
115
+ }
116
+ if (cookie.httpOnly) str += "; HttpOnly";
117
+ if (cookie.secure) str += "; Secure";
118
+ if (cookie.partitioned) str += "; Partitioned";
119
+ if (cookie.priority) switch (typeof cookie.priority === "string" ? cookie.priority.toLowerCase() : void 0) {
120
+ case "low":
121
+ str += "; Priority=Low";
122
+ break;
123
+ case "medium":
124
+ str += "; Priority=Medium";
125
+ break;
126
+ case "high":
127
+ str += "; Priority=High";
128
+ break;
129
+ default: throw new TypeError(`option priority is invalid: ${cookie.priority}`);
130
+ }
131
+ if (cookie.sameSite) switch (typeof cookie.sameSite === "string" ? cookie.sameSite.toLowerCase() : cookie.sameSite) {
132
+ case true:
133
+ case "strict":
134
+ str += "; SameSite=Strict";
135
+ break;
136
+ case "lax":
137
+ str += "; SameSite=Lax";
138
+ break;
139
+ case "none":
140
+ str += "; SameSite=None";
141
+ break;
142
+ default: throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);
143
+ }
144
+ return str;
145
+ }
146
+ function isDate(val) {
147
+ return __toString.call(val) === "[object Date]";
148
+ }
149
+ const maxAgeRegExp = /^-?\d+$/;
150
+ const _nullProto = /* @__PURE__ */ Object.getPrototypeOf({});
151
+ function parseSetCookie(str, options) {
152
+ const len = str.length;
153
+ let _endIdx = len;
154
+ let eqIdx = -1;
155
+ for (let i = 0; i < len; i++) {
156
+ const c = str.charCodeAt(i);
157
+ if (c === 59) {
158
+ _endIdx = i;
159
+ break;
160
+ }
161
+ if (c === 61 && eqIdx === -1) eqIdx = i;
162
+ }
163
+ if (eqIdx >= _endIdx) eqIdx = -1;
164
+ const name = eqIdx === -1 ? "" : _trim(str, 0, eqIdx);
165
+ if (name && name in _nullProto) return void 0;
166
+ let value = eqIdx === -1 ? _trim(str, 0, _endIdx) : _trim(str, eqIdx + 1, _endIdx);
167
+ if (!name && !value) return void 0;
168
+ if (name.length + value.length > 4096) return void 0;
169
+ if (options?.decode !== false) value = _decode(value, options?.decode);
170
+ const setCookie = {
171
+ name,
172
+ value
173
+ };
174
+ let index = _endIdx + 1;
175
+ while (index < len) {
176
+ let endIdx = len;
177
+ let attrEqIdx = -1;
178
+ for (let i = index; i < len; i++) {
179
+ const c = str.charCodeAt(i);
180
+ if (c === 59) {
181
+ endIdx = i;
182
+ break;
183
+ }
184
+ if (c === 61 && attrEqIdx === -1) attrEqIdx = i;
185
+ }
186
+ if (attrEqIdx >= endIdx) attrEqIdx = -1;
187
+ const attr = attrEqIdx === -1 ? _trim(str, index, endIdx) : _trim(str, index, attrEqIdx);
188
+ const val = attrEqIdx === -1 ? void 0 : _trim(str, attrEqIdx + 1, endIdx);
189
+ if (val === void 0 || val.length <= 1024) switch (attr.toLowerCase()) {
190
+ case "httponly":
191
+ setCookie.httpOnly = true;
192
+ break;
193
+ case "secure":
194
+ setCookie.secure = true;
195
+ break;
196
+ case "partitioned":
197
+ setCookie.partitioned = true;
198
+ break;
199
+ case "domain":
200
+ if (val) setCookie.domain = (val.charCodeAt(0) === 46 ? val.slice(1) : val).toLowerCase();
201
+ break;
202
+ case "path":
203
+ setCookie.path = val;
204
+ break;
205
+ case "max-age":
206
+ if (val && maxAgeRegExp.test(val)) setCookie.maxAge = Math.min(Number(val), COOKIE_MAX_AGE_LIMIT);
207
+ break;
208
+ case "expires": {
209
+ if (!val) break;
210
+ const date = new Date(val);
211
+ if (Number.isFinite(date.valueOf())) {
212
+ const maxDate = new Date(Date.now() + COOKIE_MAX_AGE_LIMIT * 1e3);
213
+ setCookie.expires = date > maxDate ? maxDate : date;
214
+ }
215
+ break;
216
+ }
217
+ case "priority": {
218
+ if (!val) break;
219
+ const priority = val.toLowerCase();
220
+ if (priority === "low" || priority === "medium" || priority === "high") setCookie.priority = priority;
221
+ break;
222
+ }
223
+ case "samesite": {
224
+ if (!val) break;
225
+ const sameSite = val.toLowerCase();
226
+ if (sameSite === "lax" || sameSite === "strict" || sameSite === "none") setCookie.sameSite = sameSite;
227
+ else setCookie.sameSite = "lax";
228
+ break;
229
+ }
230
+ default: {
231
+ const attrLower = attr.toLowerCase();
232
+ if (attrLower && !(attrLower in _nullProto)) setCookie[attrLower] = val;
233
+ }
234
+ }
235
+ index = endIdx + 1;
236
+ }
237
+ return setCookie;
238
+ }
239
+ function _trim(str, start, end) {
240
+ if (start === end) return "";
241
+ let s = start;
242
+ let e = end;
243
+ while (s < e && (str.charCodeAt(s) === 32 || str.charCodeAt(s) === 9)) s++;
244
+ while (e > s && (str.charCodeAt(e - 1) === 32 || str.charCodeAt(e - 1) === 9)) e--;
245
+ return str.slice(s, e);
246
+ }
247
+ function _decode(value, decode) {
248
+ if (!decode && !value.includes("%")) return value;
249
+ try {
250
+ return (decode || decodeURIComponent)(value);
251
+ } catch {
252
+ return value;
253
+ }
254
+ }
255
+ export { parse, parseSetCookie, serialize };
@@ -1,19 +1,9 @@
1
- import { CompositeKey, ContentEncryptionAlgorithm, DeriveKeyOptions, DeriveKeyReturn, Duration, ECDHEphemeralKeyInput, ExpiresIn, GenerateJWKOptions, GenerateJWKReturn, GenerateKeyAlgorithm, GenerateKeyOptions, GenerateKeyReturn, GeneratedJWKMap, GeneratedKeyMap, ImportedKey, ImportedKeyMap, JOSEConsumerOptions, JOSELimits, JOSEPayload, JOSEPayloadMode, JOSEPayloadTypeMap, JWEAsymmetricPrivateJWK, JWEAsymmetricPublicJWK, JWEDecryptJWK, JWEDecryptOptions, JWEDecryptResult, JWEEncryptJWK, JWEEncryptOptions, JWEFlattenedSerialization, JWEGeneralRecipient, JWEGeneralSerialization, JWEHeaderParameters, JWEKeyManagementHeaderParameters, JWELibraryHeaderName, JWEMultiDecryptKey, JWEMultiDecryptOptions, JWEMultiDecryptResult, JWEMultiEncryptOptions, JWEMultiRecipient, JWEProtectedHeader, JWK, JWKAlgorithm, JWKCacheAdapter, JWKLookupFunction, JWKLookupFunctionHeader, JWKMetadata, JWKPEMAlgorithm, JWKParameters, JWKSet, JWK_AES_CBC_HMAC, JWK_AES_GCM, JWK_AES_GCM_KW, JWK_AES_KW, JWK_Asymmetric, JWK_Asymmetric_Algorithm, JWK_EC, JWK_ECDH_ES, JWK_ECDSA, JWK_EC_Private, JWK_EC_Public, JWK_HMAC, JWK_OKP, JWK_OKP_Private, JWK_OKP_Public, JWK_OKP_SIGN, JWK_PBES2, JWK_Pair, JWK_Private, JWK_Public, JWK_RSA, JWK_RSA_ENC, JWK_RSA_PSS, JWK_RSA_Private, JWK_RSA_Public, JWK_RSA_SIGN, JWK_Symmetric, JWK_Symmetric_Algorithm, JWK_oct, JWSAlgorithm, JWSAsymmetricPrivateJWK, JWSAsymmetricPublicJWK, JWSFlattenedSerialization, JWSGeneralSerialization, JWSGeneralSignature, JWSHeaderParameters, JWSMultiSignOptions, JWSMultiSigner, JWSMultiVerifyAllOptions, JWSMultiVerifyOptions, JWSMultiVerifyOutcome, JWSMultiVerifyResult, JWSProtectedHeader, JWSSignJWK, JWSSignOptions, JWSVerifyJWK, JWSVerifyOptions, JWSVerifyResult, JWT, JWTClaimValidationOptions, JWTClaims, JWTTimeClaimOptions, JoseHeaderParameters, KeyManagementAlgorithm, MaxTokenAge, NotBeforeIn, PayloadOf, UnwrapKeyOptions, UnwrapKeyResult, UnwrappingKeyFor, WrapKeyOptions, WrapKeyResult, WrappingKeyFor } from "../../_chunks/index.mjs";
2
- import { JWESessionConfig, JWESessionHooks, JWSSessionConfig, JWSSessionHooks, SessionClaims, SessionData, SessionDecryptOptions, SessionEncryptOptions, SessionIssueOptions, SessionManager, SessionRecord, SessionSignOptions, SessionState, SessionUpdate, SessionUpdateTrigger, SessionVerifyOptions } from "../../_chunks/_codec-jwe.mjs";
1
+ import { JWESessionConfig, JWESessionHooks, JWSSessionConfig, JWSSessionHooks, OpenedSessionState, SessionClaims, SessionData, SessionDecryptOptions, SessionDefinition, SessionEncryptOptions, SessionIssueOptions, SessionManager, SessionRecord, SessionSignOptions, SessionState, SessionUpdate, SessionUpdateTrigger, SessionVerifyOptions } from "../../_chunks/_codec-jwe.mjs";
2
+ import { CookieAttributes } from "../../_chunks/_cookie-attributes.mjs";
3
+ import { CompositeKey, ContentEncryptionAlgorithm, DeriveJWKOptions, DeriveJWKReturn, DeriveKeyOptions, DeriveKeyReturn, Duration, ECDHEphemeralKeyInput, ExpiresIn, GenerateJWKOptions, GenerateJWKReturn, GenerateKeyAlgorithm, GenerateKeyOptions, GenerateKeyReturn, GeneratedJWKMap, GeneratedKeyMap, ImportedKey, ImportedKeyMap, ImportedPEMJWK, JOSEConsumerOptions, JOSELimits, JOSEPayload, JOSEPayloadMode, JOSEPayloadTypeMap, JWEAsymmetricPrivateJWK, JWEAsymmetricPublicJWK, JWEDecryptJWK, JWEDecryptOptions, JWEDecryptResult, JWEEncryptJWK, JWEEncryptOptions, JWEFlattenedSerialization, JWEGeneralRecipient, JWEGeneralSerialization, JWEHeaderParameters, JWEKeyLookup, JWEKeyManagementHeaderParameters, JWELibraryHeaderName, JWEMultiDecryptKey, JWEMultiDecryptOptions, JWEMultiDecryptResult, JWEMultiEncryptOptions, JWEMultiRecipient, JWEProtectedHeader, JWK, JWKAlgorithm, JWKCacheAdapter, JWKLookupFunction, JWKLookupFunctionHeader, JWKMetadata, JWKPEMAlgorithm, JWKParameters, JWKSet, JWK_AES_Algorithm, JWK_AES_CBC_HMAC, JWK_AES_GCM, JWK_AES_GCM_KW, JWK_AES_KW, JWK_Asymmetric, JWK_Asymmetric_Algorithm, JWK_EC, JWK_ECDH_ES, JWK_ECDSA, JWK_EC_Private, JWK_EC_Public, JWK_HMAC, JWK_OKP, JWK_OKP_Private, JWK_OKP_Public, JWK_OKP_SIGN, JWK_PBES2, JWK_Pair, JWK_Private, JWK_Public, JWK_RSA, JWK_RSA_ENC, JWK_RSA_PSS, JWK_RSA_Private, JWK_RSA_Public, JWK_RSA_SIGN, JWK_Symmetric, JWK_Symmetric_Algorithm, JWK_oct, JWSAlgorithm, JWSAsymmetricPrivateJWK, JWSAsymmetricPublicJWK, JWSFlattenedSerialization, JWSGeneralSerialization, JWSGeneralSignature, JWSHashedAlgorithm, JWSHeaderParameters, JWSKeyLookup, JWSMultiSignOptions, JWSMultiSigner, JWSMultiVerifyAllOptions, JWSMultiVerifyOptions, JWSMultiVerifyOutcome, JWSMultiVerifyResult, JWSProtectedHeader, JWSSignJWK, JWSSignOptions, JWSVerifyJWK, JWSVerifyOptions, JWSVerifyResult, JWT, JWTClaimValidationOptions, JWTClaims, JWTConfirmation, JWTTimeClaimOptions, JoseHeaderParameters, KeyManagementAlgorithm, KeyWrapAlgorithmOf, KeyWrappingAlgorithm, MaxTokenAge, NotBeforeIn, PEMType, PayloadOf, ToPublicJWKReturn, UnwrapKeyOptions, UnwrapKeyResult, UnwrappingKeyFor, WrapKeyOptions, WrapKeyResult, WrappingKeyFor } from "../../_chunks/index.mjs";
3
4
  import { thumbprint } from "../../_chunks/index2.mjs";
4
- import { deriveJWKFromPassword, exportPEM, generateJWK, importPEM } from "../../core/jwk.mjs";
5
+ import { deriveJWKFromPassword, exportPEM, generateJWK, importPEM, toPublicJWK } from "../../core/jwk.mjs";
5
6
  import { Elysia } from "elysia";
6
- interface CookieAttributes {
7
- domain?: string;
8
- expires?: Date;
9
- httpOnly?: boolean;
10
- maxAge?: number;
11
- path?: string;
12
- priority?: "low" | "medium" | "high";
13
- sameSite?: boolean | "lax" | "strict" | "none";
14
- secure?: boolean;
15
- partitioned?: boolean;
16
- }
17
7
  interface ChunkableCookie {
18
8
  value: unknown;
19
9
  set(config: CookieAttributes & {
@@ -73,6 +63,11 @@ type SessionPlugin<Resolved extends Record<string, unknown>, GuardName extends s
73
63
  standaloneSchema: {};
74
64
  response: {};
75
65
  }>;
66
+ /** A session definition on Elysia, plus the plugin that resolves its manager under `contextKey` (`K`). */
67
+ interface SessionPluginDefinition<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined, K extends string = "session"> extends SessionDefinition<T, MaxAge, SessionContext> {
68
+ /** Resolves the session onto the context under `contextKey`, with the guard macro answering 401 while no session is established. */
69
+ plugin: () => SessionPlugin<{ [P in K]: SessionManager<T, MaxAge>; }, `require${Capitalize<K>}`>;
70
+ }
76
71
  interface SessionJWS<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined> extends SessionState<T, MaxAge> {}
77
72
  interface SessionHooksJWS<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined, TContext extends SessionContext = SessionContext> extends JWSSessionHooks<SessionJWS<T, MaxAge>, SessionManager<T, MaxAge>, {
78
73
  context: TContext;
@@ -82,7 +77,18 @@ interface SessionConfigJWS<T extends SessionRecord = SessionClaims, MaxAge exten
82
77
  contextKey?: string;
83
78
  hooks?: SessionHooksJWS<T, MaxAge, TContext>;
84
79
  }
80
+ /** Defines a JWS (signed, not encrypted) session once: `use`, `token`, `issue` and `open` serve every request, `plugin()` mounts it on an app. */
81
+ export declare function defineJWSSession<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined, K extends string = "session">(config: SessionConfigJWS<T, MaxAge> & (K extends "session" ? {
82
+ contextKey?: K;
83
+ } : {
84
+ contextKey: K;
85
+ })): SessionPluginDefinition<T, MaxAge, K>;
86
+ /**
87
+ * Create a JWS (signed, not encrypted) session manager for the request.
88
+ * @deprecated Use `defineJWSSession(config).use(context)`.
89
+ */
85
90
  export declare function createJWSSession<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined, TContext extends SessionContext = SessionContext>(context: TContext, config: SessionConfigJWS<T, MaxAge, TContext>): Promise<SessionManager<T, MaxAge>>;
91
+ /** The Elysia plugin of a JWS (signed, not encrypted) session: `defineJWSSession(config).plugin()`. */
86
92
  export declare function jwsSession<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined, K extends string = "session">(config: SessionConfigJWS<T, MaxAge> & (K extends "session" ? {
87
93
  contextKey?: K;
88
94
  } : {
@@ -97,10 +103,21 @@ interface SessionConfigJWE<T extends SessionRecord = SessionClaims, MaxAge exten
97
103
  contextKey?: string;
98
104
  hooks?: SessionHooksJWE<T, MaxAge, TContext>;
99
105
  }
106
+ /** Defines a JWE (encrypted) session once: `use`, `token`, `issue` and `open` serve every request, `plugin()` mounts it on an app. */
107
+ export declare function defineJWESession<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined, K extends string = "session">(config: SessionConfigJWE<T, MaxAge> & (K extends "session" ? {
108
+ contextKey?: K;
109
+ } : {
110
+ contextKey: K;
111
+ })): SessionPluginDefinition<T, MaxAge, K>;
112
+ /**
113
+ * Create a JWE (encrypted) session manager for the request.
114
+ * @deprecated Use `defineJWESession(config).use(context)`.
115
+ */
100
116
  export declare function createJWESession<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined, TContext extends SessionContext = SessionContext>(context: TContext, config: SessionConfigJWE<T, MaxAge, TContext>): Promise<SessionManager<T, MaxAge>>;
117
+ /** The Elysia plugin of a JWE (encrypted) session: `defineJWESession(config).plugin()`. */
101
118
  export declare function jweSession<T extends SessionRecord = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined, K extends string = "session">(config: SessionConfigJWE<T, MaxAge> & (K extends "session" ? {
102
119
  contextKey?: K;
103
120
  } : {
104
121
  contextKey: K;
105
122
  })): SessionPlugin<{ [P in K]: SessionManager<T, MaxAge>; }, `require${Capitalize<K>}`>;
106
- export { type ChunkableCookie, type ChunkableCookieJar, type CompositeKey, type ContentEncryptionAlgorithm, type CookieAttributes, type DeriveKeyOptions, type DeriveKeyReturn, type Duration, type ECDHEphemeralKeyInput, type ExpiresIn, type GenerateJWKOptions, type GenerateJWKReturn, type GenerateKeyAlgorithm, type GenerateKeyOptions, type GenerateKeyReturn, type GeneratedJWKMap, type GeneratedKeyMap, type ImportedKey, type ImportedKeyMap, type JOSEConsumerOptions, type JOSELimits, type JOSEPayload, type JOSEPayloadMode, type JOSEPayloadTypeMap, type JWEAsymmetricPrivateJWK, type JWEAsymmetricPublicJWK, type JWEDecryptJWK, type JWEDecryptOptions, type JWEDecryptResult, type JWEEncryptJWK, type JWEEncryptOptions, type JWEFlattenedSerialization, type JWEGeneralRecipient, type JWEGeneralSerialization, type JWEHeaderParameters, type JWEKeyManagementHeaderParameters, type JWELibraryHeaderName, type JWEMultiDecryptKey, type JWEMultiDecryptOptions, type JWEMultiDecryptResult, type JWEMultiEncryptOptions, type JWEMultiRecipient, type JWEProtectedHeader, type JWK, type JWKAlgorithm, type JWKCacheAdapter, type JWKLookupFunction, type JWKLookupFunctionHeader, type JWKMetadata, type JWKPEMAlgorithm, type JWKParameters, type JWKSet, type JWK_AES_CBC_HMAC, type JWK_AES_GCM, type JWK_AES_GCM_KW, type JWK_AES_KW, type JWK_Asymmetric, type JWK_Asymmetric_Algorithm, type JWK_EC, type JWK_ECDH_ES, type JWK_ECDSA, type JWK_EC_Private, type JWK_EC_Public, type JWK_HMAC, type JWK_OKP, type JWK_OKP_Private, type JWK_OKP_Public, type JWK_OKP_SIGN, type JWK_PBES2, type JWK_Pair, type JWK_Private, type JWK_Public, type JWK_RSA, type JWK_RSA_ENC, type JWK_RSA_PSS, type JWK_RSA_Private, type JWK_RSA_Public, type JWK_RSA_SIGN, type JWK_Symmetric, type JWK_Symmetric_Algorithm, type JWK_oct, type JWSAlgorithm, type JWSAsymmetricPrivateJWK, type JWSAsymmetricPublicJWK, type JWSFlattenedSerialization, type JWSGeneralSerialization, type JWSGeneralSignature, type JWSHeaderParameters, type JWSMultiSignOptions, type JWSMultiSigner, type JWSMultiVerifyAllOptions, type JWSMultiVerifyOptions, type JWSMultiVerifyOutcome, type JWSMultiVerifyResult, type JWSProtectedHeader, type JWSSignJWK, type JWSSignOptions, type JWSVerifyJWK, type JWSVerifyOptions, type JWSVerifyResult, type JWT, type JWTClaimValidationOptions, type JWTClaims, type JWTTimeClaimOptions, type JoseHeaderParameters, type KeyManagementAlgorithm, type MaxTokenAge, type NotBeforeIn, type PayloadOf, type SessionClaims, type SessionConfigJWE, type SessionConfigJWS, type SessionContext, type SessionData, type SessionDecryptOptions, type SessionEncryptOptions, type SessionHooksJWE, type SessionHooksJWS, type SessionIssueOptions, type SessionJWE, type SessionJWS, type SessionManager, type SessionPlugin, type SessionSignOptions, type SessionUpdate, type SessionUpdateTrigger, type SessionVerifyOptions, type UnwrapKeyOptions, type UnwrapKeyResult, type UnwrappingKeyFor, type WrapKeyOptions, type WrapKeyResult, type WrappingKeyFor, type WriteChunkedCookieOptions, deriveJWKFromPassword, exportPEM, generateJWK, importPEM, thumbprint };
123
+ export { type ChunkableCookie, type ChunkableCookieJar, type CompositeKey, type ContentEncryptionAlgorithm, type CookieAttributes, type DeriveJWKOptions, type DeriveJWKReturn, type DeriveKeyOptions, type DeriveKeyReturn, type Duration, type ECDHEphemeralKeyInput, type ExpiresIn, type GenerateJWKOptions, type GenerateJWKReturn, type GenerateKeyAlgorithm, type GenerateKeyOptions, type GenerateKeyReturn, type GeneratedJWKMap, type GeneratedKeyMap, type ImportedKey, type ImportedKeyMap, type ImportedPEMJWK, type JOSEConsumerOptions, type JOSELimits, type JOSEPayload, type JOSEPayloadMode, type JOSEPayloadTypeMap, type JWEAsymmetricPrivateJWK, type JWEAsymmetricPublicJWK, type JWEDecryptJWK, type JWEDecryptOptions, type JWEDecryptResult, type JWEEncryptJWK, type JWEEncryptOptions, type JWEFlattenedSerialization, type JWEGeneralRecipient, type JWEGeneralSerialization, type JWEHeaderParameters, type JWEKeyLookup, type JWEKeyManagementHeaderParameters, type JWELibraryHeaderName, type JWEMultiDecryptKey, type JWEMultiDecryptOptions, type JWEMultiDecryptResult, type JWEMultiEncryptOptions, type JWEMultiRecipient, type JWEProtectedHeader, type JWK, type JWKAlgorithm, type JWKCacheAdapter, type JWKLookupFunction, type JWKLookupFunctionHeader, type JWKMetadata, type JWKPEMAlgorithm, type JWKParameters, type JWKSet, type JWK_AES_Algorithm, type JWK_AES_CBC_HMAC, type JWK_AES_GCM, type JWK_AES_GCM_KW, type JWK_AES_KW, type JWK_Asymmetric, type JWK_Asymmetric_Algorithm, type JWK_EC, type JWK_ECDH_ES, type JWK_ECDSA, type JWK_EC_Private, type JWK_EC_Public, type JWK_HMAC, type JWK_OKP, type JWK_OKP_Private, type JWK_OKP_Public, type JWK_OKP_SIGN, type JWK_PBES2, type JWK_Pair, type JWK_Private, type JWK_Public, type JWK_RSA, type JWK_RSA_ENC, type JWK_RSA_PSS, type JWK_RSA_Private, type JWK_RSA_Public, type JWK_RSA_SIGN, type JWK_Symmetric, type JWK_Symmetric_Algorithm, type JWK_oct, type JWSAlgorithm, type JWSAsymmetricPrivateJWK, type JWSAsymmetricPublicJWK, type JWSFlattenedSerialization, type JWSGeneralSerialization, type JWSGeneralSignature, type JWSHashedAlgorithm, type JWSHeaderParameters, type JWSKeyLookup, type JWSMultiSignOptions, type JWSMultiSigner, type JWSMultiVerifyAllOptions, type JWSMultiVerifyOptions, type JWSMultiVerifyOutcome, type JWSMultiVerifyResult, type JWSProtectedHeader, type JWSSignJWK, type JWSSignOptions, type JWSVerifyJWK, type JWSVerifyOptions, type JWSVerifyResult, type JWT, type JWTClaimValidationOptions, type JWTClaims, type JWTConfirmation, type JWTTimeClaimOptions, type JoseHeaderParameters, type KeyManagementAlgorithm, type KeyWrapAlgorithmOf, type KeyWrappingAlgorithm, type MaxTokenAge, type NotBeforeIn, type OpenedSessionState, type PEMType, type PayloadOf, type SessionClaims, type SessionConfigJWE, type SessionConfigJWS, type SessionContext, type SessionData, type SessionDecryptOptions, type SessionDefinition, type SessionEncryptOptions, type SessionHooksJWE, type SessionHooksJWS, type SessionIssueOptions, type SessionJWE, type SessionJWS, type SessionManager, type SessionPlugin, type SessionPluginDefinition, type SessionSignOptions, type SessionUpdate, type SessionUpdateTrigger, type SessionVerifyOptions, type ToPublicJWKReturn, type UnwrapKeyOptions, type UnwrapKeyResult, type UnwrappingKeyFor, type WrapKeyOptions, type WrapKeyResult, type WrappingKeyFor, type WriteChunkedCookieOptions, deriveJWKFromPassword, exportPEM, generateJWK, importPEM, thumbprint, toPublicJWK };
@@ -1,5 +1,5 @@
1
- import { deriveJWKFromPassword, exportPEM, generateJWK, importPEM, thumbprint } from "../../_chunks/jwk.mjs";
2
- import { bindSession, createJWECodec, createJWSCodec, invalidConfigError, loadSession, readChunked, recordSlotStore, removeChunked, resolveSessionToken, sessionActions, sessionManager, writeChunked } from "../../_chunks/_codec-jws.mjs";
1
+ import { deriveJWKFromPassword, exportPEM, generateJWK, importPEM, thumbprint, toPublicJWK } from "../../_chunks/jwk.mjs";
2
+ import { createJWECodec, createJWSCodec, defineSession, invalidConfigError } from "../../_chunks/_codec-jws.mjs";
3
3
  import { Elysia } from "elysia";
4
4
  function sessionPlugin(options) {
5
5
  const contextKey = options.contextKey ?? "session";
@@ -25,21 +25,7 @@ function hasSessionId(session) {
25
25
  return typeof session === "object" && session !== null && "id" in session && Boolean(session.id);
26
26
  }
27
27
  const PREFIX$1 = "[unjwt/elysia]";
28
- function readChunkedCookie(jar, name) {
29
- return readChunked(cookieStore(jar), name);
30
- }
31
- function writeChunkedCookie(jar, name, value, options = {}) {
32
- const { chunkMaxLength, ...attrs } = options;
33
- writeChunked(cookieStore(jar), name, value, {
34
- attrs,
35
- chunkMaxLength,
36
- prefix: PREFIX$1
37
- });
38
- }
39
- function removeChunkedCookie(jar, name, attrs = {}) {
40
- removeChunked(cookieStore(jar), name, { attrs });
41
- }
42
- function cookieStore(jar) {
28
+ function reactiveCookieJar(jar) {
43
29
  return {
44
30
  read: (name) => {
45
31
  const value = jar[name]?.value;
@@ -58,29 +44,12 @@ function reactiveCookie(jar, name) {
58
44
  }
59
45
  const PREFIX = "[unjwt/elysia]";
60
46
  const SESSIONS = /* @__PURE__ */ new WeakMap();
61
- const elysiaSessionPort = {
47
+ const elysiaSessionDriver = {
62
48
  prefix: PREFIX,
63
- carrier: (context) => ({ context }),
64
- store: (context, slot) => recordSlotStore(() => requestSessions(context.request), slot),
65
- readToken: readSessionToken,
66
- scope: (context) => context.request,
67
- writable: () => true,
68
- setCookie: (context, sessionName, token, { attrs, chunkMaxLength }) => {
69
- writeChunkedCookie(context.cookie, sessionName, token, {
70
- ...attrs,
71
- chunkMaxLength
72
- });
73
- },
74
- deleteCookie: (context, sessionName, { attrs }) => {
75
- removeChunkedCookie(context.cookie, sessionName, attrs);
76
- }
49
+ state: (context) => requestSessions(context.request),
50
+ header: (context, name) => context.request.headers.get(name),
51
+ cookies: (context) => reactiveCookieJar(context.cookie)
77
52
  };
78
- function readSessionToken(context, sessionName, source) {
79
- return resolveSessionToken(source, sessionName, {
80
- cookie: (name) => readChunkedCookie(context.cookie, name),
81
- header: (name) => context.request.headers.get(name)
82
- });
83
- }
84
53
  function requestSessions(request) {
85
54
  const existing = SESSIONS.get(request);
86
55
  if (existing) return existing;
@@ -92,48 +61,58 @@ const codec$1 = createJWSCodec({
92
61
  prefix: PREFIX,
93
62
  defaultName: "elysia-jws"
94
63
  });
64
+ function defineJWSSession(config) {
65
+ const definition = define$1(config);
66
+ return {
67
+ ...definition,
68
+ plugin: () => sessionPlugin({
69
+ name: "unjwt/elysia-jws",
70
+ sessionName: config.name || codec$1.defaultName,
71
+ contextKey: config.contextKey,
72
+ create: definition.use
73
+ })
74
+ };
75
+ }
95
76
  async function createJWSSession(context, config) {
96
- const binding = bind$1(context, config);
97
- await loadSession(binding);
98
- return sessionManager(binding);
77
+ return define$1(config).use(context);
99
78
  }
100
79
  function jwsSession(config) {
101
- return sessionPlugin({
102
- name: "unjwt/elysia-jws",
103
- sessionName: config.name || codec$1.defaultName,
104
- contextKey: config.contextKey,
105
- create: (context) => createJWSSession(context, config)
106
- });
80
+ return defineJWSSession(config).plugin();
107
81
  }
108
- function bind$1(context, config) {
109
- return bindSession(context, config, {
110
- port: elysiaSessionPort,
111
- codec: codec$1,
112
- actions: sessionActions()
82
+ function define$1(config) {
83
+ return defineSession(config, {
84
+ driver: elysiaSessionDriver,
85
+ hookArgs: (context) => ({ context }),
86
+ codec: codec$1
113
87
  });
114
88
  }
115
89
  const codec = createJWECodec({
116
90
  prefix: PREFIX,
117
91
  defaultName: "elysia-jwe"
118
92
  });
93
+ function defineJWESession(config) {
94
+ const definition = define(config);
95
+ return {
96
+ ...definition,
97
+ plugin: () => sessionPlugin({
98
+ name: "unjwt/elysia-jwe",
99
+ sessionName: config.name || codec.defaultName,
100
+ contextKey: config.contextKey,
101
+ create: definition.use
102
+ })
103
+ };
104
+ }
119
105
  async function createJWESession(context, config) {
120
- const binding = bind(context, config);
121
- await loadSession(binding);
122
- return sessionManager(binding);
106
+ return define(config).use(context);
123
107
  }
124
108
  function jweSession(config) {
125
- return sessionPlugin({
126
- name: "unjwt/elysia-jwe",
127
- sessionName: config.name || codec.defaultName,
128
- contextKey: config.contextKey,
129
- create: (context) => createJWESession(context, config)
130
- });
109
+ return defineJWESession(config).plugin();
131
110
  }
132
- function bind(context, config) {
133
- return bindSession(context, config, {
134
- port: elysiaSessionPort,
135
- codec,
136
- actions: sessionActions()
111
+ function define(config) {
112
+ return defineSession(config, {
113
+ driver: elysiaSessionDriver,
114
+ hookArgs: (context) => ({ context }),
115
+ codec
137
116
  });
138
117
  }
139
- export { createJWESession, createJWSSession, deriveJWKFromPassword, exportPEM, generateJWK, importPEM, jweSession, jwsSession, thumbprint };
118
+ export { createJWESession, createJWSSession, defineJWESession, defineJWSSession, deriveJWKFromPassword, exportPEM, generateJWK, importPEM, jweSession, jwsSession, thumbprint, toPublicJWK };