unjwt 0.5.37 → 0.5.39

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 (41) hide show
  1. package/README.md +142 -663
  2. package/dist/_chunks/chunk.mjs +13 -0
  3. package/dist/_chunks/h3v1.mjs +598 -0
  4. package/dist/_chunks/index.d.mts +250 -0
  5. package/dist/_chunks/index2.d.mts +108 -0
  6. package/dist/_chunks/jwe.d.mts +43 -0
  7. package/dist/_chunks/jwe.mjs +132 -0
  8. package/dist/_chunks/jwk.d.mts +575 -0
  9. package/dist/_chunks/jwk.mjs +1592 -0
  10. package/dist/_chunks/jws.d.mts +46 -0
  11. package/dist/_chunks/jws.mjs +2069 -0
  12. package/dist/_chunks/utils.mjs +374 -0
  13. package/dist/adapters/h3.d.mts +3 -265
  14. package/dist/adapters/h3.mjs +3 -706
  15. package/dist/adapters/h3v1.d.mts +3 -8
  16. package/dist/adapters/h3v1.mjs +3 -7
  17. package/dist/adapters/h3v2.d.mts +145 -146
  18. package/dist/adapters/h3v2.mjs +505 -596
  19. package/dist/index.d.mts +6 -8
  20. package/dist/index.mjs +5 -4
  21. package/dist/jwe.d.mts +3 -4
  22. package/dist/jwe.mjs +4 -3
  23. package/dist/jwk.d.mts +3 -2
  24. package/dist/jwk.mjs +3 -2
  25. package/dist/jws.d.mts +3 -3
  26. package/dist/jws.mjs +4 -3
  27. package/dist/utils.d.mts +3 -3
  28. package/dist/utils.mjs +2 -1
  29. package/package.json +33 -31
  30. package/dist/shared/unjwt.4JQCoID_.d.mts +0 -161
  31. package/dist/shared/unjwt.B-v62plj.mjs +0 -249
  32. package/dist/shared/unjwt.BCi3FEWr.d.mts +0 -328
  33. package/dist/shared/unjwt.BYDTEWa-.d.mts +0 -269
  34. package/dist/shared/unjwt.Be8NxwFK.mjs +0 -438
  35. package/dist/shared/unjwt.BqdNUKDr.d.mts +0 -64
  36. package/dist/shared/unjwt.CMNtw8ek.d.mts +0 -155
  37. package/dist/shared/unjwt.Cy2MlkUe.d.mts +0 -174
  38. package/dist/shared/unjwt.D0_ccT7g.d.mts +0 -166
  39. package/dist/shared/unjwt.DdLN9vwI.mjs +0 -163
  40. package/dist/shared/unjwt.Dpl__ZAR.mjs +0 -2121
  41. package/dist/shared/unjwt.JdKqVANs.d.mts +0 -5
@@ -0,0 +1,250 @@
1
+ import { M as JWKSet, X as JWK_Private, Z as JWK_Public, _ as JWSProtectedHeader, c as JWEHeaderParameters, d as StrictOmit, g as ExpiresIn, it as JWK_Symmetric, m as JWTClaims, p as JWTClaimValidationOptions, s as JWEEncryptOptions, v as JWSSignOptions } from "./jwk.mjs";
2
+ import { H3Event } from "h3";
3
+ import { CookieSerializeOptions } from "cookie-es";
4
+
5
+ //#region src/adapters/h3v1/session/types.d.ts
6
+ interface SessionClaims extends Required<Pick<JWTClaims, "jti" | "iat">>, StrictOmit<JWTClaims, "jti" | "iat"> {}
7
+ type SessionData<T extends Record<string, any> = SessionClaims> = StrictOmit<T, "jti" | "iat" | "exp">;
8
+ type SessionUpdate<T extends Record<string, any> = SessionClaims> = Partial<SessionData<T>> | ((oldData: SessionData<T>) => Partial<SessionData<T>> | undefined);
9
+ interface SessionManager<T extends Record<string, any> = SessionClaims, ConfigMaxAge extends ExpiresIn | undefined = ExpiresIn | undefined> {
10
+ readonly id: string | undefined;
11
+ readonly createdAt: number;
12
+ readonly expiresAt: ConfigMaxAge extends ExpiresIn ? number : "exp" extends keyof T ? T["exp"] : number | undefined;
13
+ readonly data: SessionData<T>;
14
+ readonly token: string | undefined;
15
+ update: (update: SessionUpdate<T>) => Promise<SessionManager<T, ConfigMaxAge> & {
16
+ readonly id: string;
17
+ }>;
18
+ clear: () => Promise<SessionManager<T, ConfigMaxAge>>;
19
+ }
20
+ //#endregion
21
+ //#region src/adapters/h3v1/session/jwe.d.ts
22
+ declare const kGetSessionPromise$1: unique symbol;
23
+ interface SessionJWE<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined> {
24
+ id: string | undefined;
25
+ createdAt: number;
26
+ expiresAt: MaxAge extends ExpiresIn ? number : T["exp"];
27
+ data: SessionData<T>;
28
+ [kGetSessionPromise$1]?: Promise<SessionJWE<T, MaxAge>>;
29
+ }
30
+ interface SessionHooksJWE<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined> {
31
+ onRead?: (args: {
32
+ session: SessionJWE<T, MaxAge>;
33
+ event: H3Event;
34
+ config: SessionConfigJWE<T, MaxAge>;
35
+ }) => void | Promise<void>;
36
+ onUpdate?: (args: {
37
+ session: SessionJWE<T, MaxAge>;
38
+ oldSession: SessionJWE<T, MaxAge>;
39
+ event: H3Event;
40
+ config: SessionConfigJWE<T, MaxAge>;
41
+ }) => void | Promise<void>;
42
+ onClear?: (args: {
43
+ session: SessionJWE<T, MaxAge> | undefined;
44
+ event: H3Event;
45
+ config: Partial<SessionConfigJWE<T, MaxAge>>;
46
+ }) => void | Promise<void>;
47
+ onExpire?: (args: {
48
+ event: H3Event;
49
+ error: Error;
50
+ config: SessionConfigJWE<T, MaxAge>;
51
+ }) => void | Promise<void>;
52
+ onError?: (args: {
53
+ event: H3Event;
54
+ error: any;
55
+ config: SessionConfigJWE<T, MaxAge>;
56
+ }) => void | Promise<void>;
57
+ onUnsealKeyLookup?: (args: {
58
+ header: JWEHeaderParameters;
59
+ event: H3Event;
60
+ config: SessionConfigJWE<T, MaxAge>;
61
+ }) => JWK_Symmetric | JWK_Private | Promise<JWK_Symmetric | JWK_Private>;
62
+ }
63
+ interface SessionConfigJWE<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined> {
64
+ /** @deprecated use `key` instead */
65
+ secret?: string | JWK_Symmetric | {
66
+ privateKey: JWK_Private | JWK_Symmetric;
67
+ publicKey?: JWK_Public;
68
+ };
69
+ /** Shared key used, string for PBES2 or Json Web Key (JWK) */
70
+ key: string | JWK_Symmetric | JWK_Private | {
71
+ privateKey: JWK_Private | JWK_Symmetric;
72
+ publicKey?: JWK_Public;
73
+ };
74
+ /** Session lifetime in seconds (used to derive exp from iat) */
75
+ maxAge?: MaxAge;
76
+ /** Default is "h3" */
77
+ name?: string;
78
+ /** Default is secure, httpOnly, path="/" */
79
+ cookie?: false | CookieSerializeOptions;
80
+ /** Default is x-h3-session / x-{name}-session */
81
+ sessionHeader?: false | string;
82
+ /** Default is crypto.randomUUID */
83
+ generateId?: () => string;
84
+ /** JWE configuration overrides */
85
+ jwe?: {
86
+ encryptOptions?: Omit<JWEEncryptOptions, "expiresIn">;
87
+ decryptOptions?: JWTClaimValidationOptions;
88
+ };
89
+ hooks?: SessionHooksJWE<T, MaxAge>;
90
+ }
91
+ /**
92
+ * @deprecated use `SessionConfigJWE` instead
93
+ */
94
+ type SessionJWEConfig = SessionConfigJWE;
95
+ type CompatEvent$1 = {
96
+ request: {
97
+ headers: Headers;
98
+ };
99
+ context: any;
100
+ } | {
101
+ headers: Headers;
102
+ context: any;
103
+ };
104
+ /**
105
+ * Create a session manager for the current request.
106
+ */
107
+ declare function useJWESession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent$1, config: SessionConfigJWE<T, MaxAge>): Promise<SessionManager<T, MaxAge>>;
108
+ /**
109
+ * Get (and lazily initialize) the session for the current request.
110
+ */
111
+ declare function getJWESession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent$1, config: SessionConfigJWE<T, MaxAge>): Promise<SessionJWE<T, MaxAge>>;
112
+ declare function getJWESessionToken<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent$1, config: SessionConfigJWE<T, MaxAge>): string | undefined;
113
+ /**
114
+ * Update the session (optionally mutating the session data) and re-issue the JWE token.
115
+ */
116
+ declare function updateJWESession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event, config: SessionConfigJWE<T, MaxAge>, update?: SessionUpdate<T>): Promise<SessionJWE<T, MaxAge>>;
117
+ /**
118
+ * Produce a JWE for the current session.
119
+ * Payload structure:
120
+ * {
121
+ * jti: string;
122
+ * iat: number; (seconds)
123
+ * exp?: number; (seconds)
124
+ * data: Record<string, any>;
125
+ * }
126
+ */
127
+ declare function sealJWESession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent$1, config: SessionConfigJWE<T, MaxAge>): Promise<string>;
128
+ /**
129
+ * Decrypt the JWE and return a Session-compatible object.
130
+ */
131
+ declare function unsealJWESession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent$1, config: SessionConfigJWE<T, MaxAge>, sealed: string): Promise<Partial<SessionJWE<T, MaxAge>>>;
132
+ /**
133
+ * Clear the session (delete from context and drop cookie).
134
+ */
135
+ declare function clearJWESession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event, config: Partial<SessionConfigJWE<T, MaxAge>>): Promise<void>;
136
+ //#endregion
137
+ //#region src/adapters/h3v1/session/jws.d.ts
138
+ declare const kGetSessionPromise: unique symbol;
139
+ interface SessionJWS<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined> {
140
+ id: string | undefined;
141
+ createdAt: number;
142
+ expiresAt: MaxAge extends ExpiresIn ? number : T["exp"];
143
+ data: SessionData<T>;
144
+ [kGetSessionPromise]?: Promise<SessionJWS<T, MaxAge>>;
145
+ }
146
+ interface SessionHooksJWS<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined> {
147
+ onRead?: (args: {
148
+ session: SessionJWS<T, MaxAge>;
149
+ event: H3Event;
150
+ config: SessionConfigJWS<T, MaxAge>;
151
+ }) => void | Promise<void>;
152
+ onUpdate?: (args: {
153
+ session: SessionJWS<T, MaxAge>;
154
+ oldSession: SessionJWS<T, MaxAge>;
155
+ event: H3Event;
156
+ config: SessionConfigJWS<T, MaxAge>;
157
+ }) => void | Promise<void>;
158
+ onClear?: (args: {
159
+ session: SessionJWS<T, MaxAge> | undefined;
160
+ event: H3Event;
161
+ config: Partial<SessionConfigJWS<T, MaxAge>>;
162
+ }) => void | Promise<void>;
163
+ onExpire?: (args: {
164
+ event: H3Event;
165
+ error: Error;
166
+ config: SessionConfigJWS<T, MaxAge>;
167
+ }) => void | Promise<void>;
168
+ onError?: (args: {
169
+ event: H3Event;
170
+ error: any;
171
+ config: SessionConfigJWS<T, MaxAge>;
172
+ }) => void | Promise<void>;
173
+ onVerifyKeyLookup?: (args: {
174
+ header: JWSProtectedHeader;
175
+ event: H3Event;
176
+ config: SessionConfigJWS<T, MaxAge>;
177
+ }) => JWKSet | JWK_Symmetric | JWK_Public | Promise<JWKSet | JWK_Symmetric | JWK_Public>;
178
+ }
179
+ interface SessionConfigJWS<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined> {
180
+ /**
181
+ * JWK (private for signing with RS/ES/PS, or symmetric oct) used for signing.
182
+ */
183
+ key: JWK_Symmetric | {
184
+ privateKey: JWK_Private;
185
+ publicKey: JWK_Public | JWK_Public[] | JWKSet;
186
+ };
187
+ /** Session lifetime in seconds (sets exp = iat + maxAge) */
188
+ maxAge?: MaxAge;
189
+ /** Default cookie / header name base */
190
+ name?: string;
191
+ /** Cookie options (false to disable cookies) */
192
+ cookie?: false | CookieSerializeOptions;
193
+ /** Custom header (false to disable header lookup) */
194
+ sessionHeader?: false | string;
195
+ /** Custom ID generator (defaults to crypto.randomUUID) */
196
+ generateId?: () => string;
197
+ /** JWS customization */
198
+ jws?: {
199
+ signOptions?: Omit<JWSSignOptions, "expiresIn">;
200
+ verifyOptions?: JWTClaimValidationOptions;
201
+ };
202
+ hooks?: SessionHooksJWS<T, MaxAge>;
203
+ }
204
+ /**
205
+ * @deprecated use `SessionConfigJWS` instead
206
+ */
207
+ type SessionJWSConfig = SessionConfigJWS;
208
+ type CompatEvent = {
209
+ request: {
210
+ headers: Headers;
211
+ };
212
+ context: any;
213
+ } | {
214
+ headers: Headers;
215
+ context: any;
216
+ };
217
+ /**
218
+ * Create a session manager for the current request using JWS (signed only, not encrypted).
219
+ * NOTE: Contents are visible to clients (Base64URL-decoded JSON). Do not store secrets in session data.
220
+ */
221
+ declare function useJWSSession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent, config: SessionConfigJWS<T, MaxAge>): Promise<SessionManager<T, MaxAge>>;
222
+ /**
223
+ * Retrieve (and lazily initialize) the session.
224
+ */
225
+ declare function getJWSSession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent, config: SessionConfigJWS<T, MaxAge>): Promise<SessionJWS<T, MaxAge>>;
226
+ /**
227
+ * Update session data (if provided) and reissue JWS.
228
+ */
229
+ declare function updateJWSSession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event, config: SessionConfigJWS<T, MaxAge>, update?: SessionUpdate<T>): Promise<SessionJWS<T, MaxAge>>;
230
+ /**
231
+ * Sign current session as a compact JWS.
232
+ * Payload claims:
233
+ * jti, iat, exp?, data, plus optional extraClaims (cannot override reserved)
234
+ */
235
+ declare function signJWSSession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent, config: SessionConfigJWS<T, MaxAge>): Promise<string>;
236
+ /**
237
+ * Verify and parse a compact JWS into a Session structure.
238
+ * Performs:
239
+ * - cryptographic signature verification
240
+ * - (optional) standard claim checks if validateJWT true
241
+ * - ensures jti & iat presence
242
+ * - enforces maxAge if provided
243
+ */
244
+ declare function verifyJWSSession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event | CompatEvent, config: SessionConfigJWS<T, MaxAge>, token: string): Promise<Partial<SessionJWS<T, MaxAge>>>;
245
+ /**
246
+ * Destroy the session (context + cookie).
247
+ */
248
+ declare function clearJWSSession<T extends Record<string, any> = SessionClaims, MaxAge extends ExpiresIn | undefined = ExpiresIn | undefined>(event: H3Event, config: Partial<SessionConfigJWS<T, MaxAge>>): Promise<void>;
249
+ //#endregion
250
+ export { SessionData as C, SessionClaims as S, SessionUpdate as T, getJWESessionToken as _, clearJWSSession as a, updateJWESession as b, updateJWSSession as c, SessionConfigJWE as d, SessionHooksJWE as f, getJWESession as g, clearJWESession as h, SessionJWSConfig as i, useJWSSession as l, SessionJWEConfig as m, SessionHooksJWS as n, getJWSSession as o, SessionJWE as p, SessionJWS as r, signJWSSession as s, SessionConfigJWS as t, verifyJWSSession as u, sealJWESession as v, SessionManager as w, useJWESession as x, unsealJWESession as y };
@@ -0,0 +1,108 @@
1
+ import { $ as JWK_Public, A as JWK, P as JWKSet, Q as JWK_Private, ct as JWK_oct, l as StrictOmit, t as ExpiresIn, v as JWTClaimValidationOptions, y as JWTClaims } from "./index.mjs";
2
+
3
+ //#region src/core/utils/jwt.d.ts
4
+ /**
5
+ * Apply default typ/cty semantics shared by JWS & JWE.
6
+ * - If typ is undefined and payload is a non-Uint8Array object, set typ="JWT".
7
+ * - If typ is "JWT" and payload is a non-Uint8Array object, ensure cty defaults to "application/json".
8
+ */
9
+ declare function applyTypCtyDefaults<T extends {
10
+ typ?: string;
11
+ cty?: string;
12
+ }>(header: T, payload: unknown): T;
13
+ /** Returns true when headers indicate JSON content. */
14
+ declare function isJWTContent(header: {
15
+ typ?: string;
16
+ cty?: string;
17
+ } | undefined): boolean;
18
+ /**
19
+ * Given a decoded string and JOSE headers, return an object if JSON, otherwise the string.
20
+ */
21
+ declare function decodeMaybeJWTString<T = unknown>(decodedString: string, header: {
22
+ typ?: string;
23
+ cty?: string;
24
+ } | undefined): T | string;
25
+ /**
26
+ * Decode a payload that is represented as raw bytes into T | string, honoring forceUint8Array and headers.
27
+ */
28
+ declare function decodePayloadFromBytes<T = unknown>(bytes: Uint8Array<ArrayBuffer>, header: {
29
+ typ?: string;
30
+ cty?: string;
31
+ } | undefined, forceUint8Array?: boolean): T | Uint8Array<ArrayBuffer> | string;
32
+ /**
33
+ * Decode a payload that is a Base64URL segment into T | string | Uint8Array based on flags and headers.
34
+ */
35
+ declare function decodePayloadFromB64UrlSegment<T = unknown>(payloadEncoded: string, header: {
36
+ typ?: string;
37
+ cty?: string;
38
+ } | undefined, forceUint8Array?: boolean): T | Uint8Array<ArrayBuffer> | string;
39
+ /** Convert plaintext input to bytes, shared by JWS & JWE when preparing payload. */
40
+ declare function getPlaintextBytes(payload: string | Uint8Array<ArrayBuffer> | Record<string, any>): Uint8Array<ArrayBuffer>;
41
+ declare function computeExpiresInSeconds(expiresIn: ExpiresIn): number;
42
+ declare const computeMaxTokenAgeSeconds: (expiresIn: ExpiresIn) => number;
43
+ /** Optionally compute iat/exp when signing JWTs. */
44
+ declare function computeJwtTimeClaims(payload: unknown, headerTyp: string | undefined, expiresIn?: ExpiresIn, currentDate?: Date): JWTClaims | undefined;
45
+ /** Validate JWT claims under JWS verification rules (or custom JWE implementations). */
46
+ declare function validateJwtClaims(jwtClaims: JWTClaims, options?: JWTClaimValidationOptions): void;
47
+ /** Validate critical headers in JWS semantics. */
48
+ declare function validateCriticalHeadersJWS(protectedHeader: {
49
+ crit?: string[];
50
+ } & Record<string, any>, requiredHeaders?: string[]): void;
51
+ /** Validate critical headers in JWE semantics. */
52
+ declare function validateCriticalHeadersJWE(protectedHeader: {
53
+ crit?: string[];
54
+ } & Record<string, any>, understoodFromOptions?: string[]): void;
55
+ //#endregion
56
+ //#region src/core/utils/sanitize.d.ts
57
+ /**
58
+ * Forked from unsecure@0.0.4
59
+ * Licensed under the MIT License.
60
+ *
61
+ * Source: https://github.com/sandros94/unsecure/blob/913ed5580c551153a19154b4916c67a8efb2be85/src/sanitize.ts
62
+ */
63
+ /**
64
+ * Remove prototype-pollution vectors from a plain record in-place.
65
+ * This strips __proto__, prototype, and constructor own properties.
66
+ * Returns the same reference for convenience.
67
+ */
68
+ declare function sanitizeObject<T extends Record<string, unknown> | undefined>(obj: T): T;
69
+ declare namespace index_d_exports {
70
+ export { StrictOmit, applyTypCtyDefaults, assertCryptoKey, base64Decode, base64Encode, base64UrlDecode, base64UrlEncode, computeExpiresInSeconds, computeJwtTimeClaims, computeMaxTokenAgeSeconds, concatUint8Arrays, decodeMaybeJWTString, decodePayloadFromB64UrlSegment, decodePayloadFromBytes, getPlaintextBytes, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTContent, isPrivateJWK, isPublicJWK, isSymmetricJWK, maybeArray, randomBytes, sanitizeObject, textDecoder, textEncoder, validateCriticalHeadersJWE, validateCriticalHeadersJWS, validateJwtClaims };
71
+ }
72
+ declare const textEncoder: TextEncoder;
73
+ declare const textDecoder: TextDecoder;
74
+ declare function base64Encode(data: Uint8Array<ArrayBuffer> | string): string;
75
+ declare function base64UrlEncode(data: Uint8Array<ArrayBuffer> | string): string;
76
+ declare function base64Decode(str: string | undefined): string;
77
+ declare function base64Decode<T extends boolean | undefined>(str?: string | undefined, toString?: T): T extends false ? Uint8Array<ArrayBuffer> : string;
78
+ declare function base64UrlDecode(str: string | undefined): string;
79
+ declare function base64UrlDecode<T extends boolean | undefined>(str?: string | undefined, toString?: T): T extends false ? Uint8Array<ArrayBuffer> : string;
80
+ declare function randomBytes(length: Readonly<number>): Uint8Array<ArrayBuffer>;
81
+ /**
82
+ * Concatenates multiple Uint8Arrays
83
+ * @param arrays Arrays to concatenate
84
+ * @returns Concatenated array
85
+ */
86
+ declare function concatUint8Arrays(...arrays: Readonly<Uint8Array<ArrayBuffer>[]>): Uint8Array<ArrayBuffer>;
87
+ declare function maybeArray<T>(item: T | T[]): T[];
88
+ declare function isJWK(key: any): key is JWK;
89
+ declare function isJWKSet(key: any): key is JWKSet;
90
+ declare function assertCryptoKey(key: unknown): asserts key is CryptoKey;
91
+ declare function isCryptoKey(key: unknown): key is CryptoKey;
92
+ declare const isCryptoKeyPair: (key: any) => key is CryptoKeyPair;
93
+ /** Returns true if the JWK is a symmetric (oct) key. */
94
+ declare function isSymmetricJWK(key: unknown): key is Extract<JWK, JWK_oct>;
95
+ /** Returns true if the JWK is an asymmetric (RSA, EC, OKP) key. */
96
+ declare function isAsymmetricJWK(key: unknown): key is Exclude<JWK, JWK_oct>;
97
+ /**
98
+ * Type guard that checks if the provided JWK contains private key material.
99
+ * It relies purely on the presence of private components (e.g. "d"), not on the alg value.
100
+ */
101
+ declare function isPrivateJWK(key: unknown): key is JWK_Private;
102
+ /**
103
+ * Type guard that checks if the provided JWK is a public (asymmetric) key.
104
+ * This checks for the presence of public components and absence of private material.
105
+ */
106
+ declare function isPublicJWK(key: unknown): key is JWK_Public;
107
+ //#endregion
108
+ export { validateCriticalHeadersJWE as A, computeJwtTimeClaims as C, decodePayloadFromBytes as D, decodePayloadFromB64UrlSegment as E, validateJwtClaims as M, getPlaintextBytes as O, computeExpiresInSeconds as S, decodeMaybeJWTString as T, randomBytes as _, base64UrlEncode as a, sanitizeObject as b, isAsymmetricJWK as c, isJWK as d, isJWKSet as f, maybeArray as g, isSymmetricJWK as h, base64UrlDecode as i, validateCriticalHeadersJWS as j, isJWTContent as k, isCryptoKey as l, isPublicJWK as m, base64Decode as n, concatUint8Arrays as o, isPrivateJWK as p, base64Encode as r, index_d_exports as s, assertCryptoKey as t, isCryptoKeyPair as u, textDecoder as v, computeMaxTokenAgeSeconds as w, applyTypCtyDefaults as x, textEncoder as y };
@@ -0,0 +1,43 @@
1
+ import { $ as JWK_Public, A as JWK, B as JWK_Asymmetric_Algorithm, C as DeriveKeyOptions, D as GenerateKeyAlgorithm, E as GenerateJWKReturn, F as JWK_AES_CBC_HMAC, G as JWK_EC_Public, H as JWK_ECDH_ES, I as JWK_AES_GCM, J as JWK_OKP_Private, K as JWK_HMAC, L as JWK_AES_GCM_KW, M as JWKPEMAlgorithm, N as JWKParameters, O as GenerateKeyOptions, P as JWKSet, Q as JWK_Private, R as JWK_AES_KW, S as ContentEncryptionAlgorithm, T as GenerateJWKOptions, U as JWK_ECDSA, V as JWK_EC, W as JWK_EC_Private, X as JWK_OKP_SIGN, Y as JWK_OKP_Public, Z as JWK_PBES2, _ as JWT, a as JWEEncryptOptions, at as JWK_RSA_SIGN, b as JoseHeaderParameters, c as JWEKeyManagementHeaderParameters, ct as JWK_oct, dt as WrapKeyOptions, et as JWK_RSA, ft as WrapKeyResult, i as JWEDecryptResult, it as JWK_RSA_Public, j as JWKAlgorithm, k as GenerateKeyReturn, lt as KeyManagementAlgorithm, nt as JWK_RSA_PSS, o as JWEHeaderParameters, ot as JWK_Symmetric, q as JWK_OKP, r as JWEDecryptOptions, rt as JWK_RSA_Private, s as JWEKeyLookupFunction, st as JWK_Symmetric_Algorithm, tt as JWK_RSA_ENC, ut as UnwrapKeyOptions, v as JWTClaimValidationOptions, w as DeriveKeyReturn, x as CompositeKey, y as JWTClaims, z as JWK_Asymmetric } from "./index.mjs";
2
+
3
+ //#region src/core/jwe.d.ts
4
+ declare namespace jwe_d_exports {
5
+ export { CompositeKey, ContentEncryptionAlgorithm, DeriveKeyOptions, DeriveKeyReturn, GenerateJWKOptions, GenerateJWKReturn, GenerateKeyAlgorithm, GenerateKeyOptions, GenerateKeyReturn, JWEDecryptOptions, JWEDecryptResult, JWEEncryptOptions, JWEHeaderParameters, JWEKeyLookupFunction, JWEKeyManagementHeaderParameters, JWK, JWKAlgorithm, 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_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, JWT, JWTClaimValidationOptions, JWTClaims, JoseHeaderParameters, KeyManagementAlgorithm, UnwrapKeyOptions, WrapKeyOptions, WrapKeyResult, decrypt, encrypt };
6
+ }
7
+ /**
8
+ * Encrypts a payload to produce a JWE Compact Serialization string.
9
+ *
10
+ * @param payload The payload to encrypt. Can be a string, Uint8Array, or a JSON-serializable object.
11
+ * @param key The key encryption key (KEK). Can be a CryptoKey, JWK, or for PBES2, a password string/Uint8Array.
12
+ * @param options JWE encryption options, including `alg` (key management algorithm) and `enc` (content encryption algorithm).
13
+ * @returns A Promise resolving to the JWE Compact Serialization string.
14
+ */
15
+ declare function encrypt(payload: JWTClaims, key: JWK | string | Uint8Array<ArrayBuffer>, options?: JWEEncryptOptions): Promise<string>;
16
+ declare function encrypt(payload: string | Uint8Array<ArrayBuffer> | Record<string, any>, key: JWK | string | Uint8Array<ArrayBuffer>, options?: JWEEncryptOptions): Promise<string>;
17
+ declare function encrypt(payload: JWTClaims, key: CryptoKey, options: JWEEncryptOptions & {
18
+ alg: KeyManagementAlgorithm;
19
+ enc: ContentEncryptionAlgorithm;
20
+ }): Promise<string>;
21
+ declare function encrypt(payload: string | Uint8Array<ArrayBuffer> | Record<string, any>, key: CryptoKey, options: JWEEncryptOptions & {
22
+ alg: KeyManagementAlgorithm;
23
+ enc: ContentEncryptionAlgorithm;
24
+ }): Promise<string>;
25
+ declare function encrypt(payload: string | Uint8Array<ArrayBuffer> | Record<string, any>, key: CryptoKey | JWK | string | Uint8Array<ArrayBuffer>, options: JWEEncryptOptions & {
26
+ alg: KeyManagementAlgorithm;
27
+ enc: ContentEncryptionAlgorithm;
28
+ }): Promise<string>;
29
+ /**
30
+ * Decrypts a JWE Compact Serialization string.
31
+ *
32
+ * @param jwe The JWE Compact Serialization string.
33
+ * @param key The key decryption key (KEK) or a function to look up the key.
34
+ * @param options JWE decryption options.
35
+ * @returns A Promise resolving to an object containing the decrypted plaintext, protected header, CEK, and AAD.
36
+ * @throws If JWE is invalid, decryption fails, or options are not met.
37
+ */
38
+ declare function decrypt<T extends JWTClaims | Uint8Array<ArrayBuffer> | string>(jwe: string, key: CryptoKey | JWK_Symmetric | JWK_Private | string | Uint8Array<ArrayBuffer> | JWEKeyLookupFunction, options?: JWEDecryptOptions): Promise<JWEDecryptResult<T>>;
39
+ declare function decrypt(jwe: string, key: CryptoKey | JWK_Symmetric | JWK_Private | string | Uint8Array<ArrayBuffer> | JWEKeyLookupFunction, options: JWEDecryptOptions & {
40
+ forceUint8Array: true;
41
+ }): Promise<JWEDecryptResult<Uint8Array<ArrayBuffer>>>;
42
+ //#endregion
43
+ export { encrypt as n, jwe_d_exports as r, decrypt as t };
@@ -0,0 +1,132 @@
1
+ import { t as __exportAll } from "./chunk.mjs";
2
+ import { A as validateCriticalHeadersJWE, C as computeJwtTimeClaims, D as decodePayloadFromBytes, M as validateJwtClaims, O as getPlaintextBytes, a as base64UrlEncode, b as sanitizeObject, c as isCryptoKey, g as randomBytes, i as base64UrlDecode, l as isCryptoKeyPair, u as isJWK, v as textEncoder, x as applyTypCtyDefaults } from "./utils.mjs";
3
+ import { d as unwrapKey, g as generateIV, h as encrypt$1, l as importKey, m as decrypt$1, p as encryptKey } from "./jwk.mjs";
4
+ //#region src/core/jwe.ts
5
+ var jwe_exports = /* @__PURE__ */ __exportAll({
6
+ decrypt: () => decrypt,
7
+ encrypt: () => encrypt
8
+ });
9
+ async function encrypt(payload, key, options = {}) {
10
+ const { protectedHeader: additionalProtectedHeader, cek: providedCek, contentEncryptionIV: providedContentIV, keyManagementIV, p2s, p2c, ecdh } = options;
11
+ let { alg, enc } = options;
12
+ if (!alg) {
13
+ if (typeof key === "string" || key instanceof Uint8Array) alg = "PBES2-HS256+A128KW";
14
+ else if (isJWK(key)) alg = key.alg === "A128GCM" || key.alg === "A192GCM" || key.alg === "A256GCM" ? `${key.alg}KW` : key.alg;
15
+ }
16
+ if (!alg) throw new TypeError("JWE \"alg\" (Key Management Algorithm) must be provided in options or inferable from the key");
17
+ if (!enc) enc = isJWK(key) && "enc" in key ? key.enc : "A128GCM";
18
+ const jweKeyManagementParams = {};
19
+ if (keyManagementIV) jweKeyManagementParams.iv = keyManagementIV;
20
+ if (p2s) jweKeyManagementParams.p2s = p2s;
21
+ else if (alg?.startsWith("PBES2")) jweKeyManagementParams.p2s = randomBytes(16);
22
+ if (p2c) jweKeyManagementParams.p2c = p2c;
23
+ else if (alg?.startsWith("PBES2")) jweKeyManagementParams.p2c = 2048;
24
+ if (ecdh?.partyUInfo) jweKeyManagementParams.apu = ecdh.partyUInfo;
25
+ if (ecdh?.partyVInfo) jweKeyManagementParams.apv = ecdh.partyVInfo;
26
+ if (ecdh?.ephemeralKey) {
27
+ const { epk, epkPrivateKey } = parseEphemeralKey(ecdh.ephemeralKey);
28
+ jweKeyManagementParams.epk = epk;
29
+ jweKeyManagementParams.epkPrivateKey = epkPrivateKey;
30
+ }
31
+ const wrappingKeyMaterial = await importKey(key, alg);
32
+ const { cek: finalCek, encryptedKey: jweEncryptedKey, parameters: keyManagementHeaderParams } = await encryptKey(alg, enc, wrappingKeyMaterial, providedCek, jweKeyManagementParams);
33
+ const jweProtectedHeader = {
34
+ ...additionalProtectedHeader,
35
+ ...keyManagementHeaderParams,
36
+ alg,
37
+ enc
38
+ };
39
+ if (isJWK(key) && key.kid) jweProtectedHeader.kid = key.kid;
40
+ const protectedHeader = applyTypCtyDefaults(jweProtectedHeader, payload);
41
+ const plaintextBytes = getPlaintextBytes(computeJwtTimeClaims(payload, protectedHeader.typ, options.expiresIn, options.currentDate) || payload);
42
+ const protectedHeaderEncoded = base64UrlEncode(JSON.stringify(protectedHeader));
43
+ const aadBytes = textEncoder.encode(protectedHeaderEncoded);
44
+ const contentIVBytes = providedContentIV ?? generateIV(enc);
45
+ const { ciphertext: contentCiphertext, tag: contentAuthTag, iv: actualContentIV } = await encrypt$1(enc, plaintextBytes, finalCek, contentIVBytes, aadBytes);
46
+ if (!actualContentIV) throw new Error("Content encryption IV was not generated or returned.");
47
+ if (!contentAuthTag) throw new Error("Content encryption auth tag was not generated or returned.");
48
+ return [
49
+ protectedHeaderEncoded,
50
+ jweEncryptedKey ? base64UrlEncode(jweEncryptedKey) : "",
51
+ base64UrlEncode(actualContentIV),
52
+ base64UrlEncode(contentCiphertext),
53
+ base64UrlEncode(contentAuthTag)
54
+ ].join(".");
55
+ }
56
+ async function decrypt(jwe, key, options = {}) {
57
+ const parts = jwe.split(".");
58
+ if (parts.length !== 5) throw new Error("Invalid JWE: Must contain five sections (RFC7516, section-3).");
59
+ const [protectedHeaderEncoded, encryptedKeyEncoded, ivEncoded, ciphertextEncoded, authTagEncoded] = parts;
60
+ let protectedHeader;
61
+ try {
62
+ const protectedHeaderJson = base64UrlDecode(protectedHeaderEncoded);
63
+ protectedHeader = sanitizeObject(JSON.parse(protectedHeaderJson));
64
+ } catch {
65
+ throw new Error("Invalid JWE: Protected header could not be decoded.");
66
+ }
67
+ if (!protectedHeader || typeof protectedHeader !== "object" || !protectedHeader.alg || !protectedHeader.enc) throw new Error("Invalid JWE: Protected header must be an object with \"alg\" and \"enc\" properties.");
68
+ const alg = protectedHeader.alg;
69
+ const enc = protectedHeader.enc;
70
+ if (options?.algorithms && !options.algorithms.includes(alg)) throw new Error(`Key management algorithm not allowed: ${alg}`);
71
+ if (options?.encryptionAlgorithms && !options.encryptionAlgorithms.includes(enc)) throw new Error(`Content encryption algorithm not allowed: ${enc}`);
72
+ const unwrappingKey = await importKey(typeof key === "function" ? await key(protectedHeader, jwe) : key, alg);
73
+ const encryptedKeyBytes = base64UrlDecode(encryptedKeyEncoded, false);
74
+ const contentIVBytes = base64UrlDecode(ivEncoded, false);
75
+ const contentAuthTagBytes = base64UrlDecode(authTagEncoded, false);
76
+ const ciphertextBytes = base64UrlDecode(ciphertextEncoded, false);
77
+ const unwrapKeyOpts = {
78
+ enc,
79
+ returnAs: enc.includes("GCM"),
80
+ keyUsage: options?.keyUsage || ["decrypt"]
81
+ };
82
+ if (protectedHeader.iv) unwrapKeyOpts.iv = protectedHeader.iv;
83
+ if (protectedHeader.tag) unwrapKeyOpts.tag = protectedHeader.tag;
84
+ if (protectedHeader.p2s) unwrapKeyOpts.p2s = protectedHeader.p2s;
85
+ if (protectedHeader.p2c) unwrapKeyOpts.p2c = protectedHeader.p2c;
86
+ if (protectedHeader.epk) unwrapKeyOpts.epk = protectedHeader.epk;
87
+ if (protectedHeader.apu) unwrapKeyOpts.apu = protectedHeader.apu;
88
+ if (protectedHeader.apv) unwrapKeyOpts.apv = protectedHeader.apv;
89
+ if (options?.unwrappedKeyAlgorithm) unwrapKeyOpts.unwrappedKeyAlgorithm = options.unwrappedKeyAlgorithm;
90
+ if (options?.extractable) unwrapKeyOpts.extractable = options.extractable;
91
+ const cek = await unwrapKey(alg, encryptedKeyBytes, unwrappingKey, unwrapKeyOpts);
92
+ const aadBytes = textEncoder.encode(protectedHeaderEncoded);
93
+ const payload = decodePayloadFromBytes(await decrypt$1(enc, cek, ciphertextBytes, contentIVBytes, contentAuthTagBytes, aadBytes), protectedHeader, options?.forceUint8Array);
94
+ if (protectedHeader.crit || options?.critical?.length || options?.requiredHeaders?.length) validateCriticalHeadersJWE(protectedHeader, [...options?.critical || [], ...options?.requiredHeaders || []]);
95
+ if (payload && typeof payload === "object" && options.validateJWT !== false && (options.validateJWT === true || protectedHeader.typ?.toLowerCase().includes("jwt")) && !options.forceUint8Array && !(payload instanceof Uint8Array)) validateJwtClaims(payload, options);
96
+ const result = {
97
+ payload,
98
+ protectedHeader
99
+ };
100
+ if (options.returnCek) {
101
+ result.cek = isCryptoKey(cek) ? new Uint8Array(await crypto.subtle.exportKey("raw", cek)) : cek;
102
+ result.aad = aadBytes;
103
+ }
104
+ return result;
105
+ }
106
+ function parseEphemeralKey(ephemeralKey) {
107
+ let epk;
108
+ let epkPrivateKey;
109
+ if (isCryptoKeyPair(ephemeralKey)) {
110
+ epk = ephemeralKey.publicKey;
111
+ epkPrivateKey = ephemeralKey.privateKey;
112
+ } else if (typeof ephemeralKey === "object" && ephemeralKey !== null && "publicKey" in ephemeralKey && "privateKey" in ephemeralKey) {
113
+ const candidate = ephemeralKey;
114
+ if (!candidate.publicKey || !candidate.privateKey) throw new TypeError("ECDH-ES custom ephemeral key must include both publicKey and privateKey.");
115
+ epk = candidate.publicKey;
116
+ epkPrivateKey = candidate.privateKey;
117
+ } else if (isCryptoKey(ephemeralKey)) {
118
+ if (ephemeralKey.type !== "private") throw new TypeError("ECDH-ES custom ephemeral CryptoKey must include private key material.");
119
+ epk = ephemeralKey;
120
+ epkPrivateKey = ephemeralKey;
121
+ } else if (isJWK(ephemeralKey)) {
122
+ if (!("d" in ephemeralKey) || typeof ephemeralKey.d !== "string") throw new TypeError("ECDH-ES custom ephemeral JWK must include private parameter \"d\".");
123
+ epk = ephemeralKey;
124
+ epkPrivateKey = ephemeralKey;
125
+ } else throw new TypeError("Unsupported ECDH-ES ephemeral key material provided in options.");
126
+ return {
127
+ epk,
128
+ epkPrivateKey
129
+ };
130
+ }
131
+ //#endregion
132
+ export { encrypt as n, jwe_exports as r, decrypt as t };