unjwt 0.5.38 → 0.5.40

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 +148 -670
  2. package/dist/_chunks/chunk.mjs +13 -0
  3. package/dist/_chunks/index.d.mts +558 -0
  4. package/dist/_chunks/index2.d.mts +108 -0
  5. package/dist/_chunks/jwe.d.mts +43 -0
  6. package/dist/_chunks/jwe.mjs +132 -0
  7. package/dist/_chunks/jwk.d.mts +611 -0
  8. package/dist/_chunks/jwk.mjs +1592 -0
  9. package/dist/_chunks/jws.d.mts +242 -0
  10. package/dist/_chunks/jws.mjs +2070 -0
  11. package/dist/_chunks/jws2.mjs +598 -0
  12. package/dist/_chunks/utils.mjs +375 -0
  13. package/dist/adapters/h3.d.mts +3 -267
  14. package/dist/adapters/h3.mjs +3 -704
  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 -147
  18. package/dist/adapters/h3v2.mjs +501 -594
  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 +2 -3
  23. package/dist/jwk.d.mts +3 -2
  24. package/dist/jwk.mjs +2 -2
  25. package/dist/jws.d.mts +3 -3
  26. package/dist/jws.mjs +2 -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,2070 @@
1
+ //#region src/core/utils/jwt.ts
2
+ /**
3
+ * Apply default typ/cty semantics shared by JWS & JWE.
4
+ * - If typ is undefined and payload is a non-Uint8Array object, set typ="JWT".
5
+ * - If typ is "JWT" and payload is a non-Uint8Array object, ensure cty defaults to "application/json".
6
+ */
7
+ function applyTypCtyDefaults(header, payload) {
8
+ const isObjectPayload = typeof payload === "object" && payload !== null && !(payload instanceof Uint8Array);
9
+ if (header.typ === void 0 && isObjectPayload) header.typ = "JWT";
10
+ if (header.typ?.toLowerCase().includes("jwt") && isObjectPayload) header.cty ||= "application/json";
11
+ return header;
12
+ }
13
+ /** Returns true when headers indicate JSON content. */
14
+ function isJWTContent(header) {
15
+ if (!header) return false;
16
+ if (header.typ?.toLowerCase().includes("jwt")) return true;
17
+ const cty = header.cty?.toLowerCase();
18
+ return cty === "json" || cty === "application/json" || !!cty && cty.endsWith("+json");
19
+ }
20
+ /**
21
+ * Given a decoded string and JOSE headers, return an object if JSON, otherwise the string.
22
+ */
23
+ function decodeMaybeJWTString(decodedString, header) {
24
+ if (isJWTContent(header)) {
25
+ if (decodedString.startsWith("{") && decodedString.endsWith("}") || decodedString.startsWith("[") && decodedString.endsWith("]")) try {
26
+ return sanitizeObject(JSON.parse(decodedString));
27
+ } catch {}
28
+ }
29
+ return decodedString;
30
+ }
31
+ /**
32
+ * Decode a payload that is represented as raw bytes into T | string, honoring forceUint8Array and headers.
33
+ */
34
+ function decodePayloadFromBytes(bytes, header, forceUint8Array) {
35
+ if (forceUint8Array) return bytes;
36
+ return decodeMaybeJWTString(textDecoder.decode(bytes), header);
37
+ }
38
+ /**
39
+ * Decode a payload that is a Base64URL segment into T | string | Uint8Array based on flags and headers.
40
+ */
41
+ function decodePayloadFromB64UrlSegment(payloadEncoded, header, forceUint8Array) {
42
+ if (forceUint8Array) return base64UrlDecode(payloadEncoded, false);
43
+ return decodeMaybeJWTString(base64UrlDecode(payloadEncoded), header);
44
+ }
45
+ /** Convert plaintext input to bytes, shared by JWS & JWE when preparing payload. */
46
+ function getPlaintextBytes(payload) {
47
+ if (payload instanceof Uint8Array) return payload;
48
+ if (typeof payload === "string") return textEncoder.encode(payload);
49
+ if (typeof payload === "object" && payload !== null) return textEncoder.encode(JSON.stringify(payload));
50
+ throw new TypeError("Plaintext must be a string, Uint8Array, or a JSON-serializable object.");
51
+ }
52
+ const TIME_CONSTANTS = Object.freeze({
53
+ s: 1,
54
+ second: 1,
55
+ seconds: 1,
56
+ m: 60,
57
+ minute: 60,
58
+ minutes: 60,
59
+ h: 3600,
60
+ hour: 3600,
61
+ hours: 3600,
62
+ D: 86400,
63
+ day: 86400,
64
+ days: 86400,
65
+ W: 604800,
66
+ week: 604800,
67
+ weeks: 604800,
68
+ M: 2592e3,
69
+ month: 2592e3,
70
+ months: 2592e3,
71
+ Y: 31536e3,
72
+ year: 31536e3,
73
+ years: 31536e3
74
+ });
75
+ const EXPIRES_IN_REGEX = /^(\d+)(s|second|seconds|m|minute|minutes|h|hour|hours|D|day|days|W|week|weeks|M|month|months|Y|year|years)?$/;
76
+ function computeExpiresInSeconds(expiresIn) {
77
+ if (typeof expiresIn === "number") {
78
+ if (!Number.isInteger(expiresIn) || expiresIn <= 0) throw new TypeError("If 'expiresIn' is a number, it must be a positive integer representing seconds.");
79
+ return expiresIn;
80
+ }
81
+ if (typeof expiresIn === "string") {
82
+ const match = expiresIn.match(EXPIRES_IN_REGEX);
83
+ if (!match || !match[1]) throw new TypeError("Invalid 'expiresIn' format. Must be a positive integer or a string like '10m', '2h', '7D', etc.");
84
+ return Number.parseInt(match[1], 10) * TIME_CONSTANTS[match[2] || "s"];
85
+ }
86
+ throw new TypeError("'expiresIn' must be a number or a string representing time duration.");
87
+ }
88
+ const computeMaxTokenAgeSeconds = computeExpiresInSeconds;
89
+ /** Optionally compute iat/exp when signing JWTs. */
90
+ function computeJwtTimeClaims(payload, headerTyp, expiresIn, currentDate = /* @__PURE__ */ new Date()) {
91
+ if (expiresIn === void 0 || !headerTyp?.toLowerCase().includes("jwt") || !(payload && typeof payload === "object") || payload instanceof Uint8Array || payload.exp) return;
92
+ const now = Math.round(currentDate.getTime() / 1e3);
93
+ const claims = { ...payload };
94
+ claims.iat ||= now;
95
+ claims.exp = claims.iat + computeExpiresInSeconds(expiresIn);
96
+ return claims;
97
+ }
98
+ /** Validate JWT claims under JWS verification rules (or custom JWE implementations). */
99
+ function validateJwtClaims(jwtClaims, options = {}) {
100
+ const clockTolerance = options.clockTolerance ?? 0;
101
+ const currentTime = Math.round((options.currentDate ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
102
+ const allRequiredClaims = new Set(options.requiredClaims || []);
103
+ const missingClaims = /* @__PURE__ */ new Set();
104
+ if (options.issuer) allRequiredClaims.add("iss");
105
+ if (options.audience) allRequiredClaims.add("aud");
106
+ if (options.subject) allRequiredClaims.add("sub");
107
+ if (options.maxTokenAge) allRequiredClaims.add("iat");
108
+ for (const claimName of allRequiredClaims) if (!(claimName in jwtClaims)) missingClaims.add(claimName);
109
+ if (missingClaims.size > 0) throw new Error(`Missing required JWT Claims: ${[...missingClaims].join(", ")}`);
110
+ if (options.issuer) {
111
+ const expectedIssuers = maybeArray(options.issuer);
112
+ if (!jwtClaims.iss || !expectedIssuers.includes(jwtClaims.iss)) throw new Error(`Invalid JWT "iss" (Issuer) Claim: Expected ${expectedIssuers.join(" or ")}, got ${jwtClaims.iss}`);
113
+ }
114
+ if (options.subject && jwtClaims.sub !== options.subject) throw new Error(`Invalid JWT "sub" (Subject) Claim: Expected ${options.subject}, got ${jwtClaims.sub}`);
115
+ if (options.audience) {
116
+ const expectedAudiences = maybeArray(options.audience);
117
+ const claimAudience = maybeArray(jwtClaims.aud || []);
118
+ if (!claimAudience.some((aud) => expectedAudiences.includes(aud))) throw new Error(`Invalid JWT "aud" (Audience) Claim: Expected ${expectedAudiences.join(" or ")}, got ${claimAudience.join(", ")}`);
119
+ }
120
+ if (typeof jwtClaims.nbf === "number" && jwtClaims.nbf > currentTime + clockTolerance) throw new Error(`JWT "nbf" (Not Before) Claim validation failed: Token is not yet valid (nbf: ${(/* @__PURE__ */ new Date(jwtClaims.nbf * 1e3)).toISOString()})`);
121
+ if (typeof jwtClaims.exp === "number" && jwtClaims.exp <= currentTime - clockTolerance) throw new Error(`JWT "exp" (Expiration Time) Claim validation failed: Token has expired (exp: ${(/* @__PURE__ */ new Date(jwtClaims.exp * 1e3)).toISOString()})`);
122
+ if (options.maxTokenAge) {
123
+ if (typeof jwtClaims.iat !== "number") throw new TypeError("JWT \"iat\" (Issued At) Claim must be a number when maxTokenAge is set.");
124
+ if (jwtClaims.iat > currentTime + clockTolerance) throw new Error(`JWT "iat" (Issued At) Claim validation failed: Token was issued in the future (iat: ${(/* @__PURE__ */ new Date(jwtClaims.iat * 1e3)).toISOString()})`);
125
+ if (jwtClaims.iat < currentTime - computeMaxTokenAgeSeconds(options.maxTokenAge) - clockTolerance) throw new Error(`JWT "iat" (Issued At) Claim validation failed: Token is too old (maxTokenAge: ${options.maxTokenAge}s, iat: ${(/* @__PURE__ */ new Date(jwtClaims.iat * 1e3)).toISOString()})`);
126
+ }
127
+ }
128
+ const BASE_HEADER_PARAMS = [
129
+ "alg",
130
+ "typ",
131
+ "cty",
132
+ "kid",
133
+ "jwk",
134
+ "jku",
135
+ "x5c",
136
+ "x5t",
137
+ "x5u"
138
+ ];
139
+ /** Validate critical headers in JWS semantics. */
140
+ function validateCriticalHeadersJWS(protectedHeader, requiredHeaders = []) {
141
+ if (!protectedHeader.crit) return;
142
+ const missingHeaderParams = /* @__PURE__ */ new Set();
143
+ const recognizedParams = new Set([
144
+ ...requiredHeaders,
145
+ ...BASE_HEADER_PARAMS,
146
+ "b64"
147
+ ]);
148
+ for (const param of protectedHeader.crit) {
149
+ if (recognizedParams.has(param) && (param in protectedHeader || param === "b64")) continue;
150
+ missingHeaderParams.add(param);
151
+ }
152
+ if (missingHeaderParams.size > 0) throw new Error(`Missing critical header parameters: ${[...missingHeaderParams].join(", ")}`);
153
+ }
154
+ /** Validate critical headers in JWE semantics. */
155
+ function validateCriticalHeadersJWE(protectedHeader, understoodFromOptions) {
156
+ if (protectedHeader.crit && !understoodFromOptions) throw new Error(`Unprocessed critical header parameters: ${protectedHeader.crit.join(", ")}`);
157
+ if (!protectedHeader.crit) return;
158
+ const understoodParams = new Set([
159
+ ...understoodFromOptions || [],
160
+ ...BASE_HEADER_PARAMS,
161
+ "enc",
162
+ "iv",
163
+ "tag",
164
+ "p2s",
165
+ "p2c",
166
+ "epk",
167
+ "apu",
168
+ "apv"
169
+ ]);
170
+ for (const critParam of protectedHeader.crit) {
171
+ if (!Object.prototype.hasOwnProperty.call(protectedHeader, critParam)) throw new Error(`Critical header parameter "${critParam}" listed in "crit" but not present in the protected header.`);
172
+ if (!understoodParams.has(critParam)) throw new Error(`Unprocessed critical header parameters: ${critParam}`);
173
+ }
174
+ }
175
+ //#endregion
176
+ //#region src/core/utils/sanitize.ts
177
+ /**
178
+ * Forked from unsecure@0.0.4
179
+ * Licensed under the MIT License.
180
+ *
181
+ * Source: https://github.com/sandros94/unsecure/blob/913ed5580c551153a19154b4916c67a8efb2be85/src/sanitize.ts
182
+ */
183
+ /**
184
+ * Remove prototype-pollution vectors from a plain record in-place.
185
+ * This strips __proto__, prototype, and constructor own properties.
186
+ * Returns the same reference for convenience.
187
+ */
188
+ function sanitizeObject(obj) {
189
+ if (!obj || typeof obj !== "object") return obj;
190
+ const seen = /* @__PURE__ */ new WeakSet();
191
+ seen.add(obj);
192
+ sanitizeKeys(obj, seen);
193
+ return obj;
194
+ }
195
+ function sanitizeKeys(current, seen) {
196
+ if (Object.prototype.hasOwnProperty.call(current, "__proto__")) delete current["__proto__"];
197
+ if (Object.prototype.hasOwnProperty.call(current, "prototype")) delete current["prototype"];
198
+ if (Object.prototype.hasOwnProperty.call(current, "constructor")) delete current["constructor"];
199
+ const items = Array.isArray(current) ? current : Object.values(current);
200
+ for (const v of items) if (v && typeof v === "object") {
201
+ if (!seen.has(v)) {
202
+ seen.add(v);
203
+ sanitizeKeys(v, seen);
204
+ }
205
+ }
206
+ }
207
+ //#endregion
208
+ //#region src/core/utils/index.ts
209
+ const textEncoder = /* @__PURE__ */ new TextEncoder();
210
+ const textDecoder = /* @__PURE__ */ new TextDecoder();
211
+ const _Buffer = /* @__PURE__ */ (() => {
212
+ try {
213
+ return globalThis.Buffer;
214
+ } catch {
215
+ return;
216
+ }
217
+ })();
218
+ const _hasBuffer = typeof _Buffer?.from === "function";
219
+ const _hasToBase64 = !_hasBuffer && typeof Uint8Array.prototype.toBase64 === "function";
220
+ const _hasFromBase64 = !_hasBuffer && typeof Uint8Array.fromBase64 === "function";
221
+ const _b64UrlEncOpts = /* @__PURE__ */ Object.freeze({
222
+ alphabet: "base64url",
223
+ omitPadding: true
224
+ });
225
+ const _b64UrlDecOpts = /* @__PURE__ */ Object.freeze({ alphabet: "base64url" });
226
+ function _toBuffer(data) {
227
+ return data instanceof Uint8Array ? _Buffer.from(data.buffer, data.byteOffset, data.byteLength) : _Buffer.from(data);
228
+ }
229
+ function base64Encode(data) {
230
+ if (_hasBuffer) return _toBuffer(data).toString("base64");
231
+ const encodedData = data instanceof Uint8Array ? data : textEncoder.encode(data);
232
+ if (_hasToBase64) return encodedData.toBase64();
233
+ return btoa(String.fromCodePoint(...encodedData));
234
+ }
235
+ function base64UrlEncode(data) {
236
+ if (_hasBuffer) return _toBuffer(data).toString("base64url");
237
+ const encodedData = data instanceof Uint8Array ? data : textEncoder.encode(data);
238
+ if (_hasToBase64) return encodedData.toBase64(_b64UrlEncOpts);
239
+ return btoa(String.fromCodePoint(...encodedData)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
240
+ }
241
+ function base64Decode(str, toString) {
242
+ const decodeToString = toString !== false;
243
+ if (!str) return decodeToString ? "" : new Uint8Array(0);
244
+ if (_hasBuffer) {
245
+ const buf = _Buffer.from(str, "base64");
246
+ return decodeToString ? buf.toString("utf8") : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
247
+ }
248
+ const data = _hasFromBase64 ? Uint8Array.fromBase64(str) : Uint8Array.from(atob(str), (b) => b.codePointAt(0));
249
+ return decodeToString ? textDecoder.decode(data) : data;
250
+ }
251
+ function base64UrlDecode(str, toString) {
252
+ const decodeToString = toString !== false;
253
+ if (!str) return decodeToString ? "" : new Uint8Array(0);
254
+ if (_hasBuffer) {
255
+ const buf = _Buffer.from(str, "base64url");
256
+ return decodeToString ? buf.toString("utf8") : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
257
+ }
258
+ let data;
259
+ if (_hasFromBase64) data = Uint8Array.fromBase64(str, _b64UrlDecOpts);
260
+ else {
261
+ str = str.replace(/-/g, "+").replace(/_/g, "/");
262
+ while (str.length % 4) str += "=";
263
+ data = Uint8Array.from(atob(str), (b) => b.codePointAt(0));
264
+ }
265
+ return decodeToString ? textDecoder.decode(data) : data;
266
+ }
267
+ function randomBytes(length) {
268
+ return crypto.getRandomValues(new Uint8Array(length));
269
+ }
270
+ /**
271
+ * Concatenates multiple Uint8Arrays
272
+ * @param arrays Arrays to concatenate
273
+ * @returns Concatenated array
274
+ */
275
+ function concatUint8Arrays(...arrays) {
276
+ const totalLength = arrays.reduce((length, arr) => length + arr.length, 0);
277
+ const result = new Uint8Array(totalLength);
278
+ let offset = 0;
279
+ for (const arr of arrays) {
280
+ result.set(arr, offset);
281
+ offset += arr.length;
282
+ }
283
+ return result;
284
+ }
285
+ function maybeArray(item) {
286
+ return Array.isArray(item) ? item : [item];
287
+ }
288
+ function isJWK(key) {
289
+ return typeof key === "object" && key !== null && "kty" in key && typeof key.kty === "string";
290
+ }
291
+ function isJWKSet(key) {
292
+ return key && typeof key === "object" && "keys" in key && Array.isArray(key.keys);
293
+ }
294
+ function assertCryptoKey(key) {
295
+ if (!isCryptoKey(key)) throw new Error("CryptoKey instance expected");
296
+ }
297
+ function isCryptoKey(key) {
298
+ return key?.[Symbol.toStringTag] === "CryptoKey";
299
+ }
300
+ const isCryptoKeyPair = (key) => key && typeof key === "object" && isCryptoKey(key.publicKey) && isCryptoKey(key.privateKey);
301
+ /** Returns true if the JWK is a symmetric (oct) key. */
302
+ function isSymmetricJWK(key) {
303
+ return isJWK(key) && key.kty === "oct" && typeof key.k === "string";
304
+ }
305
+ /** Returns true if the JWK is an asymmetric (RSA, EC, OKP) key. */
306
+ function isAsymmetricJWK(key) {
307
+ return !isSymmetricJWK(key);
308
+ }
309
+ /**
310
+ * Type guard that checks if the provided JWK contains private key material.
311
+ * It relies purely on the presence of private components (e.g. "d"), not on the alg value.
312
+ */
313
+ function isPrivateJWK(key) {
314
+ if (!isJWK(key)) return false;
315
+ if (key.kty === "EC") return typeof key.d === "string";
316
+ if (key.kty === "OKP") return typeof key.d === "string";
317
+ if (key.kty === "RSA") return typeof key.d === "string";
318
+ return false;
319
+ }
320
+ /**
321
+ * Type guard that checks if the provided JWK is a public (asymmetric) key.
322
+ * This checks for the presence of public components and absence of private material.
323
+ */
324
+ function isPublicJWK(key) {
325
+ if (!isJWK(key)) return false;
326
+ if (key.kty === "EC") {
327
+ const ec = key;
328
+ return typeof ec.x === "string" && typeof ec.y === "string" && typeof ec.d !== "string";
329
+ }
330
+ if (key.kty === "OKP") {
331
+ const okp = key;
332
+ return typeof okp.x === "string" && typeof okp.d !== "string";
333
+ }
334
+ if (key.kty === "RSA") {
335
+ const rsa = key;
336
+ return typeof rsa.n === "string" && typeof rsa.e === "string" && typeof rsa.d !== "string";
337
+ }
338
+ return false;
339
+ }
340
+ //#endregion
341
+ //#region src/core/jose/crypto_key.ts
342
+ /**
343
+ * This is a fork of Jose library's utility functions.
344
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/crypto_key.ts
345
+ * @license MIT https://github.com/panva/jose/blob/69b7960c67e05be55fa2ec31c74b987696c20c60/LICENSE.md
346
+ */
347
+ function unusable(name, prop = "algorithm.name") {
348
+ return /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
349
+ }
350
+ function isAlgorithm(algorithm, name) {
351
+ return algorithm.name === name;
352
+ }
353
+ function getHashLength(hash) {
354
+ return Number.parseInt(hash.name.slice(4), 10);
355
+ }
356
+ function getNamedCurve$1(alg) {
357
+ switch (alg) {
358
+ case "ES256": return "P-256";
359
+ case "ES384": return "P-384";
360
+ case "ES512": return "P-521";
361
+ default: throw new Error("unreachable");
362
+ }
363
+ }
364
+ function checkUsage(key, usage) {
365
+ if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
366
+ }
367
+ function checkSigCryptoKey(key, alg, usage) {
368
+ switch (alg) {
369
+ case "HS256":
370
+ case "HS384":
371
+ case "HS512": {
372
+ if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
373
+ const expected = Number.parseInt(alg.slice(2), 10);
374
+ if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
375
+ break;
376
+ }
377
+ case "RS256":
378
+ case "RS384":
379
+ case "RS512": {
380
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
381
+ const expected = Number.parseInt(alg.slice(2), 10);
382
+ if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
383
+ break;
384
+ }
385
+ case "PS256":
386
+ case "PS384":
387
+ case "PS512": {
388
+ if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
389
+ const expected = Number.parseInt(alg.slice(2), 10);
390
+ if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
391
+ break;
392
+ }
393
+ case "Ed25519":
394
+ case "EdDSA":
395
+ if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
396
+ break;
397
+ case "ES256":
398
+ case "ES384":
399
+ case "ES512": {
400
+ if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
401
+ const expected = getNamedCurve$1(alg);
402
+ if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
403
+ break;
404
+ }
405
+ default: throw new TypeError("CryptoKey does not support this operation");
406
+ }
407
+ checkUsage(key, usage);
408
+ }
409
+ function checkEncCryptoKey(key, alg, usage) {
410
+ switch (alg) {
411
+ case "A128GCM":
412
+ case "A192GCM":
413
+ case "A256GCM": {
414
+ if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM");
415
+ const expected = Number.parseInt(alg.slice(1, 4), 10);
416
+ if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length");
417
+ break;
418
+ }
419
+ case "A128KW":
420
+ case "A192KW":
421
+ case "A256KW": {
422
+ if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW");
423
+ const expected = Number.parseInt(alg.slice(1, 4), 10);
424
+ if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length");
425
+ break;
426
+ }
427
+ case "ECDH":
428
+ switch (key.algorithm.name) {
429
+ case "ECDH":
430
+ case "X25519": break;
431
+ default: throw unusable("ECDH or X25519");
432
+ }
433
+ break;
434
+ case "PBES2-HS256+A128KW":
435
+ case "PBES2-HS384+A192KW":
436
+ case "PBES2-HS512+A256KW":
437
+ if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2");
438
+ break;
439
+ case "RSA-OAEP":
440
+ case "RSA-OAEP-256":
441
+ case "RSA-OAEP-384":
442
+ case "RSA-OAEP-512": {
443
+ if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP");
444
+ const expected = Number.parseInt(alg.slice(9), 10) || 1;
445
+ if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
446
+ break;
447
+ }
448
+ default: throw new TypeError("CryptoKey does not support this operation");
449
+ }
450
+ checkUsage(key, usage);
451
+ }
452
+ //#endregion
453
+ //#region src/core/jose/sign-verify.ts
454
+ /**
455
+ * This is a fork of Jose library's utility functions.
456
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/sign.ts
457
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/verify.ts
458
+ * @license MIT https://github.com/panva/jose/blob/69b7960c67e05be55fa2ec31c74b987696c20c60/LICENSE.md
459
+ */
460
+ async function sign$1(alg, key, data) {
461
+ const cryptoKey = await getSignVerifyKey(alg, key, "sign");
462
+ checkKeyLength(alg, cryptoKey);
463
+ const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
464
+ return new Uint8Array(signature);
465
+ }
466
+ async function verify$1(alg, key, signature, data) {
467
+ const cryptoKey = await getSignVerifyKey(alg, key, "verify");
468
+ checkKeyLength(alg, cryptoKey);
469
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
470
+ try {
471
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
472
+ } catch {
473
+ return false;
474
+ }
475
+ }
476
+ function checkKeyLength(alg, key) {
477
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
478
+ const { modulusLength } = key.algorithm;
479
+ if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
480
+ }
481
+ }
482
+ async function getSignVerifyKey(alg, key, usage) {
483
+ if (key instanceof Uint8Array) {
484
+ if (!alg.startsWith("HS")) throw new TypeError("Key must be of type CryptoKey or JSON Web Key for non-HMAC algorithms");
485
+ return crypto.subtle.importKey("raw", key, {
486
+ hash: `SHA-${alg.slice(-3)}`,
487
+ name: "HMAC"
488
+ }, false, [usage]);
489
+ }
490
+ checkSigCryptoKey(key, alg, usage);
491
+ return key;
492
+ }
493
+ function subtleAlgorithm(alg, algorithm) {
494
+ const hash = `SHA-${alg.slice(-3)}`;
495
+ switch (alg) {
496
+ case "HS256":
497
+ case "HS384":
498
+ case "HS512": return {
499
+ hash,
500
+ name: "HMAC"
501
+ };
502
+ case "PS256":
503
+ case "PS384":
504
+ case "PS512": return {
505
+ hash,
506
+ name: "RSA-PSS",
507
+ saltLength: Number.parseInt(alg.slice(-3), 10) >> 3
508
+ };
509
+ case "RS256":
510
+ case "RS384":
511
+ case "RS512": return {
512
+ hash,
513
+ name: "RSASSA-PKCS1-v1_5"
514
+ };
515
+ case "ES256":
516
+ case "ES384":
517
+ case "ES512": return {
518
+ hash,
519
+ name: "ECDSA",
520
+ namedCurve: algorithm.namedCurve
521
+ };
522
+ case "Ed25519":
523
+ case "EdDSA": return { name: "Ed25519" };
524
+ default: throw new Error(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
525
+ }
526
+ }
527
+ //#endregion
528
+ //#region src/core/jose/buffer_utils.ts
529
+ /**
530
+ * This is a fork of Jose library's utility functions.
531
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/buffer_utils.ts
532
+ * @license MIT https://github.com/panva/jose/blob/69b7960c67e05be55fa2ec31c74b987696c20c60/LICENSE.md
533
+ */
534
+ const MAX_INT32 = 2 ** 32;
535
+ function writeUInt32BE(buf, value, offset) {
536
+ if (value < 0 || value >= MAX_INT32) throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
537
+ buf.set([
538
+ value >>> 24,
539
+ value >>> 16,
540
+ value >>> 8,
541
+ value & 255
542
+ ], offset);
543
+ }
544
+ function uint64be(value) {
545
+ const high = Math.floor(value / MAX_INT32);
546
+ const low = value % MAX_INT32;
547
+ const buf = new Uint8Array(8);
548
+ writeUInt32BE(buf, high, 0);
549
+ writeUInt32BE(buf, low, 4);
550
+ return buf;
551
+ }
552
+ function uint32be(value) {
553
+ const buf = new Uint8Array(4);
554
+ writeUInt32BE(buf, value);
555
+ return buf;
556
+ }
557
+ //#endregion
558
+ //#region src/core/jose/cek-iv.ts
559
+ /**
560
+ * This is a fork of Jose library's utility functions.
561
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/cek.ts
562
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/iv.ts
563
+ * @license MIT https://github.com/panva/jose/blob/69b7960c67e05be55fa2ec31c74b987696c20c60/LICENSE.md
564
+ */
565
+ const IV_BIT_LENGTHS = {
566
+ A128GCM: 96,
567
+ A128GCMKW: 96,
568
+ A192GCM: 96,
569
+ A192GCMKW: 96,
570
+ A256GCM: 96,
571
+ A256GCMKW: 96,
572
+ "A128CBC-HS256": 128,
573
+ "A192CBC-HS384": 128,
574
+ "A256CBC-HS512": 128
575
+ };
576
+ const CEK_BIT_LENGTHS = {
577
+ A128GCM: 128,
578
+ A192GCM: 192,
579
+ A256GCM: 256,
580
+ "A128CBC-HS256": 256,
581
+ "A192CBC-HS384": 384,
582
+ "A256CBC-HS512": 512
583
+ };
584
+ function bitLengthIV(alg) {
585
+ const length = IV_BIT_LENGTHS[alg];
586
+ if (length === void 0) throw new Error(`Unsupported JWE Algorithm: ${alg}`);
587
+ return length;
588
+ }
589
+ function generateIV(alg) {
590
+ return crypto.getRandomValues(new Uint8Array(bitLengthIV(alg) >> 3));
591
+ }
592
+ function checkIvLength(enc, iv) {
593
+ if (iv.length << 3 !== bitLengthIV(enc)) throw new Error("Invalid Initialization Vector length");
594
+ }
595
+ function bitLengthCEK(alg) {
596
+ const length = CEK_BIT_LENGTHS[alg];
597
+ if (length === void 0) throw new Error(`Unsupported JWE Algorithm: ${alg}`);
598
+ return length;
599
+ }
600
+ function generateCEK(alg) {
601
+ return crypto.getRandomValues(new Uint8Array(bitLengthCEK(alg) >> 3));
602
+ }
603
+ function checkCEKLength(cek, expected) {
604
+ const actual = cek.byteLength << 3;
605
+ if (actual !== expected) throw new Error(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
606
+ }
607
+ //#endregion
608
+ //#region src/core/jose/encrypt-decrypt.ts
609
+ /**
610
+ * This is a fork of Jose library's utility functions.
611
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/encrypt.ts
612
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/decrypt.ts
613
+ * @license MIT https://github.com/panva/jose/blob/69b7960c67e05be55fa2ec31c74b987696c20c60/LICENSE.md
614
+ */
615
+ async function importCBCKeys(enc, cek, usage) {
616
+ const keySize = Number.parseInt(enc.slice(1, 4), 10);
617
+ const [encKey, macKey] = await Promise.all([crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]), crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
618
+ hash: `SHA-${keySize << 1}`,
619
+ name: "HMAC"
620
+ }, false, ["sign"])]);
621
+ return {
622
+ encKey,
623
+ macKey,
624
+ keySize
625
+ };
626
+ }
627
+ function cbcMacData(aad, iv, ciphertext) {
628
+ return concatUint8Arrays(aad, iv, ciphertext, uint64be(aad.length << 3));
629
+ }
630
+ async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
631
+ if (!(cek instanceof Uint8Array)) throw new TypeError("CBC key must be of type Uint8Array");
632
+ const { encKey, macKey, keySize } = await importCBCKeys(enc, cek, "encrypt");
633
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
634
+ iv,
635
+ name: "AES-CBC"
636
+ }, encKey, plaintext));
637
+ const macData = cbcMacData(aad, iv, ciphertext);
638
+ return {
639
+ ciphertext,
640
+ tag: new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)),
641
+ iv
642
+ };
643
+ }
644
+ async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
645
+ let encKey;
646
+ if (cek instanceof Uint8Array) encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
647
+ else {
648
+ checkEncCryptoKey(cek, enc, "encrypt");
649
+ encKey = cek;
650
+ }
651
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
652
+ additionalData: aad,
653
+ iv,
654
+ name: "AES-GCM",
655
+ tagLength: 128
656
+ }, encKey, plaintext));
657
+ const tag = encrypted.subarray(-16);
658
+ return {
659
+ ciphertext: encrypted.subarray(0, -16),
660
+ tag,
661
+ iv
662
+ };
663
+ }
664
+ async function encrypt$1(enc, plaintext, cek, iv, aad) {
665
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) throw new TypeError("Key must be one of type: CryptoKey or Uint8Array");
666
+ if (iv) checkIvLength(enc, iv);
667
+ else iv = generateIV(enc);
668
+ switch (enc) {
669
+ case "A128CBC-HS256":
670
+ case "A192CBC-HS384":
671
+ case "A256CBC-HS512":
672
+ if (cek instanceof Uint8Array) checkCEKLength(cek, Number.parseInt(enc.slice(-3), 10));
673
+ return cbcEncrypt(enc, plaintext, cek, iv, aad);
674
+ case "A128GCM":
675
+ case "A192GCM":
676
+ case "A256GCM":
677
+ if (cek instanceof Uint8Array) checkCEKLength(cek, Number.parseInt(enc.slice(1, 4), 10));
678
+ return gcmEncrypt(enc, plaintext, cek, iv, aad);
679
+ default: throw new Error("Unsupported JWE Content Encryption Algorithm");
680
+ }
681
+ }
682
+ /**
683
+ * Decrypt fork
684
+ */
685
+ let _timingSafeKey;
686
+ function getTimingSafeKey() {
687
+ if (!_timingSafeKey) _timingSafeKey = crypto.subtle.generateKey({
688
+ name: "HMAC",
689
+ hash: "SHA-256"
690
+ }, false, ["sign"]);
691
+ return _timingSafeKey;
692
+ }
693
+ async function timingSafeEqual(a, b) {
694
+ if (!(a instanceof Uint8Array)) throw new TypeError("First argument must be a buffer");
695
+ if (!(b instanceof Uint8Array)) throw new TypeError("Second argument must be a buffer");
696
+ const algorithm = {
697
+ name: "HMAC",
698
+ hash: "SHA-256"
699
+ };
700
+ const key = await getTimingSafeKey();
701
+ const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
702
+ const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
703
+ let out = 0;
704
+ let i = -1;
705
+ while (++i < 32) out |= aHmac[i] ^ bHmac[i];
706
+ return out === 0;
707
+ }
708
+ async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
709
+ if (!(cek instanceof Uint8Array)) throw new TypeError("CBC key must be of type Uint8Array");
710
+ const { encKey, macKey, keySize } = await importCBCKeys(enc, cek, "decrypt");
711
+ const macData = cbcMacData(aad, iv, ciphertext);
712
+ const expectedTag = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
713
+ let macCheckPassed;
714
+ try {
715
+ macCheckPassed = await timingSafeEqual(tag, expectedTag);
716
+ } catch {}
717
+ if (!macCheckPassed) throw new Error("JWE Decryption Failed");
718
+ let plaintext;
719
+ try {
720
+ plaintext = new Uint8Array(await crypto.subtle.decrypt({
721
+ iv,
722
+ name: "AES-CBC"
723
+ }, encKey, ciphertext));
724
+ } catch {}
725
+ if (!plaintext) throw new Error("JWE Decryption Failed");
726
+ return plaintext;
727
+ }
728
+ async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
729
+ let encKey;
730
+ if (cek instanceof Uint8Array) encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
731
+ else {
732
+ checkEncCryptoKey(cek, enc, "decrypt");
733
+ encKey = cek;
734
+ }
735
+ try {
736
+ return new Uint8Array(await crypto.subtle.decrypt({
737
+ additionalData: aad,
738
+ iv,
739
+ name: "AES-GCM",
740
+ tagLength: 128
741
+ }, encKey, concatUint8Arrays(ciphertext, tag)));
742
+ } catch {
743
+ throw new Error("JWE Decryption Failed");
744
+ }
745
+ }
746
+ async function decrypt$1(enc, cek, ciphertext, iv, tag, aad) {
747
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) throw new TypeError("Key must be one of type: CryptoKey or Uint8Array");
748
+ if (!iv) throw new Error("JWE Initialization Vector missing");
749
+ if (!tag) throw new Error("JWE Authentication Tag missing");
750
+ checkIvLength(enc, iv);
751
+ switch (enc) {
752
+ case "A128CBC-HS256":
753
+ case "A192CBC-HS384":
754
+ case "A256CBC-HS512":
755
+ if (cek instanceof Uint8Array) checkCEKLength(cek, Number.parseInt(enc.slice(-3), 10));
756
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);
757
+ case "A128GCM":
758
+ case "A192GCM":
759
+ case "A256GCM":
760
+ if (cek instanceof Uint8Array) checkCEKLength(cek, Number.parseInt(enc.slice(1, 4), 10));
761
+ return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);
762
+ default: throw new Error("Unsupported JWE Content Encryption Algorithm");
763
+ }
764
+ }
765
+ //#endregion
766
+ //#region src/core/jose/jwk_to_key.ts
767
+ function subtleMapping(jwk) {
768
+ let algorithm;
769
+ let keyUsages;
770
+ switch (jwk.kty) {
771
+ case "RSA":
772
+ switch (jwk.alg) {
773
+ case "PS256":
774
+ case "PS384":
775
+ case "PS512":
776
+ algorithm = {
777
+ name: "RSA-PSS",
778
+ hash: `SHA-${jwk.alg.slice(-3)}`
779
+ };
780
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
781
+ break;
782
+ case "RS256":
783
+ case "RS384":
784
+ case "RS512":
785
+ algorithm = {
786
+ name: "RSASSA-PKCS1-v1_5",
787
+ hash: `SHA-${jwk.alg.slice(-3)}`
788
+ };
789
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
790
+ break;
791
+ case "RSA-OAEP":
792
+ case "RSA-OAEP-256":
793
+ case "RSA-OAEP-384":
794
+ case "RSA-OAEP-512":
795
+ algorithm = {
796
+ name: "RSA-OAEP",
797
+ hash: `SHA-${Number.parseInt(jwk.alg.slice(-3), 10) || 1}`
798
+ };
799
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
800
+ break;
801
+ default: throw new Error("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
802
+ }
803
+ break;
804
+ case "EC":
805
+ switch (jwk.alg) {
806
+ case "ES256":
807
+ algorithm = {
808
+ name: "ECDSA",
809
+ namedCurve: "P-256"
810
+ };
811
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
812
+ break;
813
+ case "ES384":
814
+ algorithm = {
815
+ name: "ECDSA",
816
+ namedCurve: "P-384"
817
+ };
818
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
819
+ break;
820
+ case "ES512":
821
+ algorithm = {
822
+ name: "ECDSA",
823
+ namedCurve: "P-521"
824
+ };
825
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
826
+ break;
827
+ case "ECDH-ES":
828
+ case "ECDH-ES+A128KW":
829
+ case "ECDH-ES+A192KW":
830
+ case "ECDH-ES+A256KW":
831
+ algorithm = {
832
+ name: "ECDH",
833
+ namedCurve: jwk.crv
834
+ };
835
+ keyUsages = jwk.d ? ["deriveBits"] : [];
836
+ break;
837
+ default: throw new Error("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
838
+ }
839
+ break;
840
+ case "OKP":
841
+ switch (jwk.alg) {
842
+ case "Ed25519":
843
+ case "EdDSA":
844
+ algorithm = { name: "Ed25519" };
845
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
846
+ break;
847
+ case "ECDH-ES":
848
+ case "ECDH-ES+A128KW":
849
+ case "ECDH-ES+A192KW":
850
+ case "ECDH-ES+A256KW":
851
+ algorithm = { name: jwk.crv };
852
+ keyUsages = jwk.d ? ["deriveBits"] : [];
853
+ break;
854
+ default: throw new Error("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
855
+ }
856
+ break;
857
+ default: throw new Error("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
858
+ }
859
+ return {
860
+ algorithm,
861
+ keyUsages
862
+ };
863
+ }
864
+ async function jwkTokey(jwk) {
865
+ if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
866
+ const { algorithm, keyUsages } = subtleMapping(jwk);
867
+ return crypto.subtle.importKey("jwk", jwk, algorithm, jwk.ext ?? (jwk.d ? false : true), jwk.key_ops ?? keyUsages);
868
+ }
869
+ //#endregion
870
+ //#region src/core/jose/key_to_jwk.ts
871
+ async function keyToJWK(key) {
872
+ if (key instanceof Uint8Array) return {
873
+ kty: "oct",
874
+ k: base64UrlEncode(key)
875
+ };
876
+ if (!isCryptoKey(key)) throw new TypeError("Key must be one of type: CryptoKey or Uint8Array");
877
+ if (!key.extractable) throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
878
+ return await crypto.subtle.exportKey("jwk", key);
879
+ }
880
+ //#endregion
881
+ //#region src/core/jose/rsaes.ts
882
+ async function encryptRSAES(alg, key, cek) {
883
+ checkEncCryptoKey(key, alg, "encrypt");
884
+ checkKeyLength(alg, key);
885
+ return new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP", key, cek));
886
+ }
887
+ async function decryptRSAES(alg, key, encryptedKey) {
888
+ checkEncCryptoKey(key, alg, "decrypt");
889
+ checkKeyLength(alg, key);
890
+ return new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP", key, encryptedKey));
891
+ }
892
+ //#endregion
893
+ //#region src/core/jose/aesgcmkw.ts
894
+ /**
895
+ * This is a fork of Jose library's utility functions.
896
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/aesgcmkw.ts
897
+ * @license MIT https://github.com/panva/jose/blob/69b7960c67e05be55fa2ec31c74b987696c20c60/LICENSE.md
898
+ */
899
+ async function encryptIV(alg, key, plaintext, iv) {
900
+ const wrapped = await encrypt$1(alg.slice(0, 7), plaintext, key, iv, new Uint8Array(0));
901
+ return {
902
+ encryptedKey: wrapped.ciphertext,
903
+ iv: base64UrlEncode(wrapped.iv),
904
+ tag: base64UrlEncode(wrapped.tag)
905
+ };
906
+ }
907
+ async function decryptIV(alg, key, ciphertext, iv, tag) {
908
+ return decrypt$1(alg.slice(0, 7), key, ciphertext, iv, tag, new Uint8Array(0));
909
+ }
910
+ //#endregion
911
+ //#region src/core/jose/ecdhes.ts
912
+ function lengthAndInput(input) {
913
+ return concatUint8Arrays(uint32be(input.length), input);
914
+ }
915
+ async function concatKdf(secret, bits, value) {
916
+ const iterations = Math.ceil((bits >> 3) / 32);
917
+ const res = new Uint8Array(iterations * 32);
918
+ for (let iter = 0; iter < iterations; iter++) {
919
+ const buf = new Uint8Array(4 + secret.length + value.length);
920
+ buf.set(uint32be(iter + 1));
921
+ buf.set(secret, 4);
922
+ buf.set(value, 4 + secret.length);
923
+ res.set(await digest("sha256", buf), iter * 32);
924
+ }
925
+ return res.slice(0, bits >> 3);
926
+ }
927
+ async function deriveECDHESKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
928
+ checkEncCryptoKey(publicKey, "ECDH");
929
+ checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
930
+ const value = concatUint8Arrays(lengthAndInput(textEncoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
931
+ const length = publicKey.algorithm.name === "X25519" ? 256 : Math.ceil(Number.parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
932
+ return concatKdf(new Uint8Array(await crypto.subtle.deriveBits({
933
+ name: publicKey.algorithm.name,
934
+ public: publicKey
935
+ }, privateKey, length)), keyLength, value);
936
+ }
937
+ function allowed(key) {
938
+ switch (key.algorithm.namedCurve) {
939
+ case "P-256":
940
+ case "P-384":
941
+ case "P-521": return true;
942
+ default: return key.algorithm.name === "X25519";
943
+ }
944
+ }
945
+ async function digest(algorithm, data) {
946
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
947
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
948
+ }
949
+ //#endregion
950
+ //#region src/core/jose/pbes2kw.ts
951
+ /**
952
+ * This is a fork of Jose library's utility functions.
953
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/pbes2kw.ts
954
+ * @license MIT https://github.com/panva/jose/blob/69b7960c67e05be55fa2ec31c74b987696c20c60/LICENSE.md
955
+ */
956
+ async function wrap(alg, key, cek, p2c, p2s) {
957
+ if (p2c && p2s) {
958
+ const derived = await deriveKey(p2s, alg, p2c, key);
959
+ return {
960
+ encryptedKey: await _wrap(alg.slice(-6), derived, cek),
961
+ p2c,
962
+ p2s: base64UrlEncode(p2s)
963
+ };
964
+ } else return { encryptedKey: await _wrap(alg, key, cek) };
965
+ }
966
+ async function unwrap(alg, key, encryptedKey, p2c, p2s) {
967
+ if (p2c && p2s) {
968
+ const derived = await deriveKey(p2s, alg, p2c, key);
969
+ return _unwrap(alg.slice(-6), derived, encryptedKey);
970
+ } else return _unwrap(alg, key, encryptedKey);
971
+ }
972
+ function getCryptoKey(key, alg, options = {}) {
973
+ const { importAlg = "PBKDF2", extractable = false, usage = "deriveBits" } = options;
974
+ if (key instanceof Uint8Array) return crypto.subtle.importKey("raw", key, importAlg, extractable, [usage]);
975
+ checkEncCryptoKey(key, alg, usage);
976
+ return key;
977
+ }
978
+ async function deriveKey(p2s, alg, p2c, key) {
979
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) throw new Error("PBES2 Salt Input must be 8 or more octets");
980
+ if (p2c === void 0 || p2c < 1) throw new Error("PBES2 Iteration Count Parameter must be a positive integer");
981
+ const salt = concatUint8Arrays(textEncoder.encode(alg), new Uint8Array([0]), p2s);
982
+ const keylen = Number.parseInt(alg.slice(13, 16), 10);
983
+ const subtleAlg = {
984
+ hash: `SHA-${alg.slice(8, 11)}`,
985
+ iterations: p2c,
986
+ name: "PBKDF2",
987
+ salt
988
+ };
989
+ const cryptoKey = await getCryptoKey(key, alg);
990
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
991
+ }
992
+ /**
993
+ * Fork from: https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/aeskw.ts
994
+ */
995
+ function checkKeySize(key, alg) {
996
+ if (key.algorithm.length !== Number.parseInt(alg.slice(1, 4), 10)) throw new TypeError(`Invalid key size for alg: ${alg}`);
997
+ }
998
+ async function _wrap(alg, key, cek) {
999
+ const cryptoKey = await getCryptoKey(key, alg, {
1000
+ importAlg: "AES-KW",
1001
+ extractable: true,
1002
+ usage: "wrapKey"
1003
+ });
1004
+ checkKeySize(cryptoKey, alg);
1005
+ const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, {
1006
+ hash: "SHA-256",
1007
+ name: "HMAC"
1008
+ }, true, ["sign"]);
1009
+ return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
1010
+ }
1011
+ async function _unwrap(alg, key, encryptedKey) {
1012
+ const cryptoKey = await getCryptoKey(key, alg, {
1013
+ importAlg: "AES-KW",
1014
+ extractable: true,
1015
+ usage: "unwrapKey"
1016
+ });
1017
+ checkKeySize(cryptoKey, alg);
1018
+ const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", {
1019
+ hash: "SHA-256",
1020
+ name: "HMAC"
1021
+ }, true, ["sign"]);
1022
+ return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
1023
+ }
1024
+ //#endregion
1025
+ //#region src/core/jose/encrypt_key.ts
1026
+ const PUBLIC_EPK_FIELDS = new Set([
1027
+ "kty",
1028
+ "crv",
1029
+ "x",
1030
+ "y",
1031
+ "kid",
1032
+ "use",
1033
+ "key_ops",
1034
+ "alg",
1035
+ "x5c",
1036
+ "x5t",
1037
+ "x5t#S256",
1038
+ "x5u"
1039
+ ]);
1040
+ function toPublicEpkJwk(jwk) {
1041
+ const filtered = {};
1042
+ for (const [key, value] of Object.entries(jwk)) if (value !== void 0 && PUBLIC_EPK_FIELDS.has(key)) filtered[key] = value;
1043
+ const { kty, crv, x, y } = filtered;
1044
+ if (typeof kty !== "string") throw new TypeError("ECDH-ES ephemeral key JWK must include the \"kty\" parameter.");
1045
+ if (typeof crv !== "string") throw new TypeError("ECDH-ES ephemeral key JWK must include the \"crv\" parameter.");
1046
+ if (typeof x !== "string") throw new TypeError("ECDH-ES ephemeral key JWK must include the \"x\" coordinate.");
1047
+ if (kty === "EC" && typeof y !== "string") throw new TypeError("ECDH-ES EC ephemeral key JWK must include both \"x\" and \"y\" coordinates.");
1048
+ const publicJwk = {
1049
+ ...filtered,
1050
+ kty,
1051
+ crv,
1052
+ x
1053
+ };
1054
+ if (typeof y === "string") publicJwk.y = y;
1055
+ else delete publicJwk.y;
1056
+ return sanitizeObject(publicJwk);
1057
+ }
1058
+ async function ensurePrivateKey(alg, value) {
1059
+ const normalized = await normalizeKey(value, alg);
1060
+ if (!(normalized instanceof CryptoKey)) throw new TypeError("ECDH-ES ephemeral private key must be a CryptoKey or convertible JWK.");
1061
+ if (normalized.type !== "private") throw new TypeError("ECDH-ES ephemeral private key must have type \"private\".");
1062
+ return normalized;
1063
+ }
1064
+ async function exportPublicJwkFrom(alg, value) {
1065
+ if (isCryptoKey(value)) try {
1066
+ return toPublicEpkJwk(await keyToJWK(value));
1067
+ } catch (error_) {
1068
+ throw new TypeError("ECDH-ES ephemeral CryptoKey must be extractable to export as JWK.", { cause: error_ instanceof Error ? error_ : void 0 });
1069
+ }
1070
+ if (isJWK(value) && isAsymmetricJWK(value) && value.kty === "EC") return toPublicEpkJwk(value);
1071
+ const normalized = await normalizeKey(value, alg);
1072
+ if (!(normalized instanceof CryptoKey)) throw new TypeError("ECDH-ES ephemeral public key must be a CryptoKey or convertible JWK.");
1073
+ return exportPublicJwkFrom(alg, normalized);
1074
+ }
1075
+ async function encryptKey(alg, enc, key, providedCek, providedParameters = {}) {
1076
+ let encryptedKey;
1077
+ let parameters = {};
1078
+ let cek;
1079
+ switch (alg) {
1080
+ case "dir":
1081
+ cek = key;
1082
+ break;
1083
+ case "ECDH-ES":
1084
+ case "ECDH-ES+A128KW":
1085
+ case "ECDH-ES+A192KW":
1086
+ case "ECDH-ES+A256KW": {
1087
+ assertCryptoKey(key);
1088
+ if (!allowed(key)) throw new Error("ECDH with the provided key is not allowed or not supported by your javascript runtime");
1089
+ const { apu, apv, epk: providedEpk, epkPrivateKey } = providedParameters;
1090
+ if (providedEpk && !epkPrivateKey) throw new TypeError("ECDH-ES custom ephemeral key material must include the matching private key.");
1091
+ let ephemeralPrivateKey;
1092
+ let epkHeader;
1093
+ if (epkPrivateKey) {
1094
+ ephemeralPrivateKey = await ensurePrivateKey(alg, epkPrivateKey);
1095
+ epkHeader = await exportPublicJwkFrom(alg, providedEpk ?? epkPrivateKey);
1096
+ } else {
1097
+ if (providedEpk) throw new TypeError("ECDH-ES custom ephemeral public key requires a matching private key.");
1098
+ const generated = await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"]);
1099
+ ephemeralPrivateKey = generated.privateKey;
1100
+ epkHeader = await exportPublicJwkFrom(alg, generated.publicKey);
1101
+ }
1102
+ const sharedSecret = await deriveECDHESKey(key, ephemeralPrivateKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLengthCEK(enc) : Number.parseInt(alg.slice(-5, -2), 10), apu, apv);
1103
+ parameters = { epk: epkHeader };
1104
+ if (apu) parameters.apu = base64UrlEncode(apu);
1105
+ if (apv) parameters.apv = base64UrlEncode(apv);
1106
+ if (alg === "ECDH-ES") {
1107
+ cek = sharedSecret;
1108
+ break;
1109
+ }
1110
+ cek = providedCek || generateCEK(enc);
1111
+ encryptedKey = (await wrap(alg.slice(-6), sharedSecret, cek)).encryptedKey;
1112
+ break;
1113
+ }
1114
+ case "RSA-OAEP":
1115
+ case "RSA-OAEP-256":
1116
+ case "RSA-OAEP-384":
1117
+ case "RSA-OAEP-512":
1118
+ cek = providedCek || generateCEK(enc);
1119
+ assertCryptoKey(key);
1120
+ encryptedKey = await encryptRSAES(alg, key, cek);
1121
+ break;
1122
+ case "PBES2-HS256+A128KW":
1123
+ case "PBES2-HS384+A192KW":
1124
+ case "PBES2-HS512+A256KW": {
1125
+ cek = providedCek || generateCEK(enc);
1126
+ const { p2c, p2s } = providedParameters;
1127
+ ({encryptedKey, ...parameters} = await wrap(alg, key, cek, p2c, p2s));
1128
+ break;
1129
+ }
1130
+ case "A128KW":
1131
+ case "A192KW":
1132
+ case "A256KW":
1133
+ cek = providedCek || generateCEK(enc);
1134
+ encryptedKey = (await wrap(alg, key, cek)).encryptedKey;
1135
+ break;
1136
+ case "A128GCMKW":
1137
+ case "A192GCMKW":
1138
+ case "A256GCMKW": {
1139
+ cek = providedCek || generateCEK(enc);
1140
+ const { iv } = providedParameters;
1141
+ ({encryptedKey, ...parameters} = await encryptIV(alg, key, cek, iv));
1142
+ break;
1143
+ }
1144
+ default: throw new Error("Invalid or unsupported \"alg\" (JWE Algorithm) header value");
1145
+ }
1146
+ return {
1147
+ cek,
1148
+ encryptedKey,
1149
+ parameters
1150
+ };
1151
+ }
1152
+ async function normalizeKey(key, alg) {
1153
+ if (key instanceof Uint8Array) return key;
1154
+ if (isCryptoKey(key)) return key;
1155
+ if (isJWK(key)) {
1156
+ if ("k" in key && key.k) return base64UrlDecode(key.k, false);
1157
+ return jwkTokey(key.alg ? key : {
1158
+ ...key,
1159
+ alg
1160
+ });
1161
+ }
1162
+ throw new Error("unreachable");
1163
+ }
1164
+ //#endregion
1165
+ //#region src/core/jose/asn1.ts
1166
+ /**
1167
+ * This is a fork of Jose library's utility functions.
1168
+ * @source https://github.com/panva/jose/tree/69b7960c67e05be55fa2ec31c74b987696c20c60/src/lib/asn1.ts
1169
+ * @license MIT https://github.com/panva/jose/blob/69b7960c67e05be55fa2ec31c74b987696c20c60/LICENSE.md
1170
+ */
1171
+ const formatPEM = (b64, descriptor) => {
1172
+ return `-----BEGIN ${descriptor}-----\n${(b64.match(/.{1,64}/g) || []).join("\n")}\n-----END ${descriptor}-----`;
1173
+ };
1174
+ const genericExport = async (keyType, keyFormat, key) => {
1175
+ if (!isCryptoKey(key)) throw new TypeError(`Key must be ${key} of type CryptoKey`);
1176
+ if (!key.extractable) throw new TypeError("CryptoKey is not extractable");
1177
+ if (key.type !== keyType) throw new TypeError(`key is not a ${keyType} key`);
1178
+ return formatPEM(base64Encode(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
1179
+ };
1180
+ const toSPKI = (key) => {
1181
+ return genericExport("public", "spki", key);
1182
+ };
1183
+ const toPKCS8 = (key) => {
1184
+ return genericExport("private", "pkcs8", key);
1185
+ };
1186
+ const findOid = (keyData, oid, from = 0) => {
1187
+ if (from === 0) {
1188
+ oid.unshift(oid.length);
1189
+ oid.unshift(6);
1190
+ }
1191
+ const i = keyData.indexOf(oid[0], from);
1192
+ if (i === -1) return false;
1193
+ const sub = keyData.subarray(i, i + oid.length);
1194
+ if (sub.length !== oid.length) return false;
1195
+ return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);
1196
+ };
1197
+ const getNamedCurve = (keyData) => {
1198
+ switch (true) {
1199
+ case findOid(keyData, [
1200
+ 42,
1201
+ 134,
1202
+ 72,
1203
+ 206,
1204
+ 61,
1205
+ 3,
1206
+ 1,
1207
+ 7
1208
+ ]): return "P-256";
1209
+ case findOid(keyData, [
1210
+ 43,
1211
+ 129,
1212
+ 4,
1213
+ 0,
1214
+ 34
1215
+ ]): return "P-384";
1216
+ case findOid(keyData, [
1217
+ 43,
1218
+ 129,
1219
+ 4,
1220
+ 0,
1221
+ 35
1222
+ ]): return "P-521";
1223
+ default: return;
1224
+ }
1225
+ };
1226
+ const genericImport = async (replace, keyFormat, pem, alg, options) => {
1227
+ let algorithm;
1228
+ let keyUsages;
1229
+ const keyData = base64Decode(pem.replace(replace, ""), false);
1230
+ const isPublic = keyFormat === "spki";
1231
+ switch (alg) {
1232
+ case "PS256":
1233
+ case "PS384":
1234
+ case "PS512":
1235
+ algorithm = {
1236
+ name: "RSA-PSS",
1237
+ hash: `SHA-${alg.slice(-3)}`
1238
+ };
1239
+ keyUsages = isPublic ? ["verify"] : ["sign"];
1240
+ break;
1241
+ case "RS256":
1242
+ case "RS384":
1243
+ case "RS512":
1244
+ algorithm = {
1245
+ name: "RSASSA-PKCS1-v1_5",
1246
+ hash: `SHA-${alg.slice(-3)}`
1247
+ };
1248
+ keyUsages = isPublic ? ["verify"] : ["sign"];
1249
+ break;
1250
+ case "RSA-OAEP":
1251
+ case "RSA-OAEP-256":
1252
+ case "RSA-OAEP-384":
1253
+ case "RSA-OAEP-512":
1254
+ algorithm = {
1255
+ name: "RSA-OAEP",
1256
+ hash: `SHA-${Number.parseInt(alg.slice(-3), 10) || 1}`
1257
+ };
1258
+ keyUsages = isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
1259
+ break;
1260
+ case "ES256":
1261
+ algorithm = {
1262
+ name: "ECDSA",
1263
+ namedCurve: "P-256"
1264
+ };
1265
+ keyUsages = isPublic ? ["verify"] : ["sign"];
1266
+ break;
1267
+ case "ES384":
1268
+ algorithm = {
1269
+ name: "ECDSA",
1270
+ namedCurve: "P-384"
1271
+ };
1272
+ keyUsages = isPublic ? ["verify"] : ["sign"];
1273
+ break;
1274
+ case "ES512":
1275
+ algorithm = {
1276
+ name: "ECDSA",
1277
+ namedCurve: "P-521"
1278
+ };
1279
+ keyUsages = isPublic ? ["verify"] : ["sign"];
1280
+ break;
1281
+ case "ECDH-ES":
1282
+ case "ECDH-ES+A128KW":
1283
+ case "ECDH-ES+A192KW":
1284
+ case "ECDH-ES+A256KW": {
1285
+ const namedCurve = getNamedCurve(keyData);
1286
+ algorithm = namedCurve?.startsWith("P-") ? {
1287
+ name: "ECDH",
1288
+ namedCurve
1289
+ } : { name: "X25519" };
1290
+ keyUsages = isPublic ? [] : ["deriveBits"];
1291
+ break;
1292
+ }
1293
+ case "Ed25519":
1294
+ case "EdDSA":
1295
+ algorithm = { name: "Ed25519" };
1296
+ keyUsages = isPublic ? ["verify"] : ["sign"];
1297
+ break;
1298
+ default: throw new Error("Invalid or unsupported \"alg\" (Algorithm) value");
1299
+ }
1300
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
1301
+ };
1302
+ const fromPKCS8 = (pem, alg, options) => {
1303
+ return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", pem, alg, options);
1304
+ };
1305
+ const fromSPKI = (pem, alg, options) => {
1306
+ return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", pem, alg, options);
1307
+ };
1308
+ function getElement(seq) {
1309
+ const result = [];
1310
+ let next = 0;
1311
+ while (next < seq.length) {
1312
+ const nextPart = parseElement(seq.subarray(next));
1313
+ result.push(nextPart);
1314
+ next += nextPart.byteLength;
1315
+ }
1316
+ return result;
1317
+ }
1318
+ function parseElement(bytes) {
1319
+ let position = 0;
1320
+ let tag = bytes[0] & 31;
1321
+ position++;
1322
+ if (tag === 31) {
1323
+ tag = 0;
1324
+ while (bytes[position] >= 128) {
1325
+ tag = tag * 128 + bytes[position] - 128;
1326
+ position++;
1327
+ }
1328
+ tag = tag * 128 + bytes[position] - 128;
1329
+ position++;
1330
+ }
1331
+ let length = 0;
1332
+ if (bytes[position] < 128) {
1333
+ length = bytes[position];
1334
+ position++;
1335
+ } else if (length === 128) {
1336
+ length = 0;
1337
+ while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {
1338
+ if (length > bytes.byteLength) throw new TypeError("invalid indefinite form length");
1339
+ length++;
1340
+ }
1341
+ const byteLength = position + length + 2;
1342
+ return {
1343
+ byteLength,
1344
+ contents: bytes.subarray(position, position + length),
1345
+ raw: bytes.subarray(0, byteLength)
1346
+ };
1347
+ } else {
1348
+ const numberOfDigits = bytes[position] & 127;
1349
+ position++;
1350
+ length = 0;
1351
+ for (let i = 0; i < numberOfDigits; i++) {
1352
+ length = length * 256 + bytes[position];
1353
+ position++;
1354
+ }
1355
+ }
1356
+ const byteLength = position + length;
1357
+ return {
1358
+ byteLength,
1359
+ contents: bytes.subarray(position, byteLength),
1360
+ raw: bytes.subarray(0, byteLength)
1361
+ };
1362
+ }
1363
+ function spkiFromX509(buf) {
1364
+ const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);
1365
+ return base64Encode(tbsCertificate[tbsCertificate[0].raw[0] === 160 ? 6 : 5].raw);
1366
+ }
1367
+ let createPublicKey;
1368
+ function getSPKI(x509) {
1369
+ try {
1370
+ createPublicKey ??= globalThis.process?.getBuiltinModule?.("node:crypto")?.createPublicKey;
1371
+ } catch {
1372
+ createPublicKey = 0;
1373
+ }
1374
+ if (createPublicKey) try {
1375
+ return new createPublicKey(x509).export({
1376
+ format: "pem",
1377
+ type: "spki"
1378
+ });
1379
+ } catch {}
1380
+ return formatPEM(spkiFromX509(base64Decode(x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ""), false)), "PUBLIC KEY");
1381
+ }
1382
+ const fromX509 = (pem, alg, options) => {
1383
+ let spki;
1384
+ try {
1385
+ spki = getSPKI(pem);
1386
+ } catch (error_) {
1387
+ throw new TypeError("Failed to parse the X.509 certificate", { cause: error_ });
1388
+ }
1389
+ return fromSPKI(spki, alg, options);
1390
+ };
1391
+ //#endregion
1392
+ //#region src/core/jwk.ts
1393
+ async function generateKey(alg, options = {}) {
1394
+ const exportToJWK = options.toJWK !== void 0 && options.toJWK !== false;
1395
+ const defaultExtractable = options.extractable !== false;
1396
+ if (alg === "A128CBC-HS256" || alg === "A192CBC-HS384" || alg === "A256CBC-HS512") {
1397
+ const keyBytes = randomBytes(bitLengthCEK(alg) >> 3);
1398
+ if (exportToJWK) return keyToJWK(keyBytes);
1399
+ return keyBytes;
1400
+ }
1401
+ const { algorithm, keyUsages } = getGenerateKeyParams(alg, options);
1402
+ const key = await crypto.subtle.generateKey(algorithm, defaultExtractable, keyUsages);
1403
+ if (exportToJWK) {
1404
+ const { alg: _a, kty: _k, key_ops: _ko, ext: _e, ...additionalKeyParams } = typeof options.toJWK === "object" ? options.toJWK : {};
1405
+ if (key instanceof CryptoKey) return exportKey(key, {
1406
+ ...additionalKeyParams,
1407
+ alg
1408
+ });
1409
+ else {
1410
+ const [publicKey, privateKey] = await Promise.all([exportKey(key.publicKey, {
1411
+ ...additionalKeyParams,
1412
+ alg
1413
+ }), exportKey(key.privateKey, {
1414
+ ...additionalKeyParams,
1415
+ alg
1416
+ })]);
1417
+ return {
1418
+ privateKey,
1419
+ publicKey
1420
+ };
1421
+ }
1422
+ }
1423
+ return key;
1424
+ }
1425
+ /**
1426
+ * Generates a Json Web Key (JWK) for the specified algorithm.
1427
+ *
1428
+ * @param alg The JWA algorithm identifier (e.g., "HS256", "RS256", "A128GCM").
1429
+ * @param jwkParams Optional partial JWK to merge with the generated key, allowing overrides.
1430
+ * @param options Configuration options for key generation.
1431
+ * @returns A Promise resolving to the generated JWK or JWK pair representation.
1432
+ */
1433
+ async function generateJWK(alg, jwkParams, options = {}) {
1434
+ const { toJWK: _, ...opts } = options;
1435
+ return generateKey(alg, {
1436
+ ...opts,
1437
+ toJWK: {
1438
+ kid: typeof jwkParams?.kid === "string" ? jwkParams.kid : crypto.randomUUID(),
1439
+ ...jwkParams
1440
+ }
1441
+ });
1442
+ }
1443
+ async function deriveKeyFromPassword(password, alg, options) {
1444
+ const { salt, iterations, extractable, keyUsage } = options;
1445
+ const exportToJWK = options.toJWK !== void 0 && options.toJWK !== false;
1446
+ if (!(salt instanceof Uint8Array) || salt.length < 8) throw new Error("PBES2 Salt Input (salt) must be 8 or more octets");
1447
+ if (typeof iterations !== "number" || iterations < 1) throw new Error("PBES2 Iteration Count (iterations) must be a positive integer");
1448
+ const derivedBytes = await deriveKey(salt, alg, iterations, typeof password === "string" ? textEncoder.encode(password) : password);
1449
+ const wrappingAlg = alg.slice(-6);
1450
+ const finalUsages = keyUsage ?? ["wrapKey", "unwrapKey"];
1451
+ const finalExtractable = exportToJWK ? true : extractable === true;
1452
+ const derivedKey = await crypto.subtle.importKey("raw", derivedBytes, { name: "AES-KW" }, finalExtractable, finalUsages);
1453
+ if (exportToJWK) {
1454
+ const jwk = await keyToJWK(derivedKey);
1455
+ const { alg: _a, kty: _k, key_ops: _ko, ext: _e, ...additionalKeyParams } = typeof options.toJWK === "object" ? options.toJWK : {};
1456
+ return {
1457
+ ...additionalKeyParams,
1458
+ ...jwk,
1459
+ alg: wrappingAlg,
1460
+ kty: "oct"
1461
+ };
1462
+ }
1463
+ return derivedKey;
1464
+ }
1465
+ /**
1466
+ * Derives a Json Web Key (JWK) from a password using PBKDF2 as specified by PBES2 algorithms.
1467
+ *
1468
+ * @param password The password to derive the key from (string or Uint8Array).
1469
+ * @param alg The PBES2 algorithm identifier (e.g., "PBES2-HS256+A128KW").
1470
+ * @param jwkParams Optional partial JWK to merge with the generated key, allowing overrides.
1471
+ * @param options Configuration options including salt and iterations.
1472
+ * @returns A Promise resolving to the derived JWK (JWK_oct).
1473
+ */
1474
+ async function deriveJWKFromPassword(password, alg, options, jwkParams) {
1475
+ const { toJWK: _, ...opts } = options;
1476
+ return deriveKeyFromPassword(password, alg, {
1477
+ ...opts,
1478
+ toJWK: jwkParams || true
1479
+ });
1480
+ }
1481
+ /**
1482
+ * Cache for imported JWKs to avoid redundant CryptoKey creation.
1483
+ */
1484
+ let _jwkCache;
1485
+ async function importKey(key, alg) {
1486
+ if (typeof key === "string") key = textEncoder.encode(key);
1487
+ if (key instanceof Uint8Array) return key;
1488
+ if (isCryptoKey(key)) return key;
1489
+ if (isJWK(key)) if ("k" in key && typeof key.k === "string") return base64UrlDecode(key.k, false);
1490
+ else {
1491
+ if (!key.alg && !alg) throw new TypeError("Algorithm must be provided when importing non-oct JWK");
1492
+ const effectiveAlg = key.alg || alg;
1493
+ _jwkCache ||= /* @__PURE__ */ new WeakMap();
1494
+ const cached = _jwkCache.get(key);
1495
+ if (cached?.[effectiveAlg]) return cached[effectiveAlg];
1496
+ const cryptoKey = await jwkTokey(key.alg ? key : {
1497
+ ...key,
1498
+ alg
1499
+ });
1500
+ if (!cached) _jwkCache.set(key, { [effectiveAlg]: cryptoKey });
1501
+ else cached[effectiveAlg] = cryptoKey;
1502
+ return cryptoKey;
1503
+ }
1504
+ throw new Error("Invalid key type provided to importKey");
1505
+ }
1506
+ /**
1507
+ * Exports a CryptoKey to a JWK (JSON Web Key) format.
1508
+ *
1509
+ * @param key The CryptoKey to export.
1510
+ * @param jwk Optional partial JWK to merge with the exported key, allowing overrides.
1511
+ * @returns A Promise resolving to the exported JWK.
1512
+ */
1513
+ async function exportKey(key, jwk) {
1514
+ const exportedJwk = await keyToJWK(key);
1515
+ if (jwk) return {
1516
+ ...sanitizeObject(jwk),
1517
+ ...exportedJwk
1518
+ };
1519
+ return exportedJwk;
1520
+ }
1521
+ async function resolveWrappingKey(alg, key) {
1522
+ if (alg.startsWith("PBES2") && (typeof key === "string" || key instanceof Uint8Array)) return typeof key === "string" ? textEncoder.encode(key) : key;
1523
+ if (typeof key === "string") throw new TypeError(`Key must be CryptoKey, JWK, or Uint8Array for ${alg}`);
1524
+ return importKey(key, alg);
1525
+ }
1526
+ /**
1527
+ * Unwraps a Content Encryption Key (CEK) using the specified algorithm and unwrapping key.
1528
+ *
1529
+ * @param alg The JWA key management algorithm (e.g., "A128KW", "RSA-OAEP", "PBES2-HS256+A128KW").
1530
+ * @param wrappedKey The wrapped key (ciphertext) as Uint8Array.
1531
+ * @param unwrappingKey The key used to unwrap the CEK (CryptoKey, JWK, or password string/Uint8Array for PBES2).
1532
+ * @param options Additional options required by certain algorithms (e.g., iv, tag, p2s, p2c, epk).
1533
+ * @returns A Promise resolving to the unwrapped key (CEK) as a CryptoKey or Uint8Array.
1534
+ */
1535
+ async function unwrapKey(alg, wrappedKey, unwrappingKey, options = {}) {
1536
+ const { returnAs = true } = options;
1537
+ const defaultExtractable = options.extractable !== false;
1538
+ const importedUnwrappingKey = isCryptoKey(unwrappingKey) ? unwrappingKey : await resolveWrappingKey(alg, unwrappingKey);
1539
+ let unwrappedCekBytes;
1540
+ switch (alg) {
1541
+ case "A128KW":
1542
+ case "A192KW":
1543
+ case "A256KW":
1544
+ case "PBES2-HS256+A128KW":
1545
+ case "PBES2-HS384+A192KW":
1546
+ case "PBES2-HS512+A256KW": {
1547
+ const { p2s, p2c } = options;
1548
+ let p2sBytes;
1549
+ if (alg.startsWith("PBES2")) {
1550
+ if (!p2s || typeof p2c !== "number") throw new Error("PBES2 requires 'p2s' (salt) and 'p2c' (count) options");
1551
+ p2sBytes = typeof p2s === "string" ? base64UrlDecode(p2s, false) : p2s;
1552
+ }
1553
+ unwrappedCekBytes = await unwrap(alg, importedUnwrappingKey, wrappedKey, p2c, p2sBytes);
1554
+ break;
1555
+ }
1556
+ case "A128GCMKW":
1557
+ case "A192GCMKW":
1558
+ case "A256GCMKW":
1559
+ if (!options.iv || !options.tag) throw new Error("AES-GCMKW requires 'iv' and 'tag' options for unwrapping");
1560
+ unwrappedCekBytes = await decryptIV(alg, importedUnwrappingKey, wrappedKey, typeof options.iv === "string" ? base64UrlDecode(options.iv, false) : options.iv, typeof options.tag === "string" ? base64UrlDecode(options.tag, false) : options.tag);
1561
+ break;
1562
+ case "RSA-OAEP":
1563
+ case "RSA-OAEP-256":
1564
+ case "RSA-OAEP-384":
1565
+ case "RSA-OAEP-512": {
1566
+ if (!(importedUnwrappingKey instanceof CryptoKey)) throw new TypeError("RSA-OAEP requires the unwrapping key to be provided as a CryptoKey");
1567
+ unwrappedCekBytes = await decryptRSAES(alg, importedUnwrappingKey, wrappedKey);
1568
+ if (!returnAs) break;
1569
+ const inferredAlgorithm = options.unwrappedKeyAlgorithm || inferAesImportAlgorithm(options.enc, unwrappedCekBytes.length);
1570
+ if (!inferredAlgorithm) throw new Error("Unable to infer algorithm for RSA-OAEP unwrapped key. Provide \"unwrappedKeyAlgorithm\" in options.");
1571
+ const keyUsages = options.keyUsage || ["encrypt", "decrypt"];
1572
+ return await crypto.subtle.importKey("raw", unwrappedCekBytes, inferredAlgorithm, defaultExtractable, keyUsages);
1573
+ }
1574
+ case "ECDH-ES":
1575
+ case "ECDH-ES+A128KW":
1576
+ case "ECDH-ES+A192KW":
1577
+ case "ECDH-ES+A256KW": {
1578
+ if (!options.epk) throw new Error("ECDH-ES requires 'epk' (Ephemeral Public Key) option");
1579
+ if (!(importedUnwrappingKey instanceof CryptoKey)) throw new TypeError("ECDH-ES requires the unwrapping key to be a CryptoKey");
1580
+ if (!allowed(importedUnwrappingKey)) throw new Error("ECDH with the provided key is not allowed or not supported");
1581
+ const epkCandidate = options.epk instanceof CryptoKey ? options.epk : await normalizeKey(options.epk, alg);
1582
+ if (!(epkCandidate instanceof CryptoKey)) throw new TypeError("Failed to normalize ECDH ephemeral public key");
1583
+ const apuBytes = typeof options.apu === "string" ? base64UrlDecode(options.apu, false) : options.apu ?? new Uint8Array(0);
1584
+ const apvBytes = typeof options.apv === "string" ? base64UrlDecode(options.apv, false) : options.apv ?? new Uint8Array(0);
1585
+ const infoAlg = alg === "ECDH-ES" ? options.enc : alg;
1586
+ if (!infoAlg) throw new Error("ECDH-ES requires content encryption algorithm ('enc') to derive the shared secret");
1587
+ const sharedSecret = await deriveECDHESKey(epkCandidate, importedUnwrappingKey, infoAlg, alg === "ECDH-ES" ? bitLengthCEK(infoAlg) : Number.parseInt(alg.slice(-5, -2), 10), apuBytes, apvBytes);
1588
+ if (alg === "ECDH-ES") unwrappedCekBytes = sharedSecret;
1589
+ else {
1590
+ const kwAlg = alg.slice(-6);
1591
+ if (!(wrappedKey instanceof Uint8Array) || wrappedKey.length === 0) throw new Error("ECDH-ES key agreement with key wrapping requires an encrypted key");
1592
+ unwrappedCekBytes = await unwrap(kwAlg, sharedSecret, wrappedKey);
1593
+ }
1594
+ break;
1595
+ }
1596
+ default: throw new Error(`Unsupported key unwrapping algorithm: ${alg}`);
1597
+ }
1598
+ if (!returnAs) return unwrappedCekBytes;
1599
+ return await crypto.subtle.importKey("raw", unwrappedCekBytes, options.unwrappedKeyAlgorithm || { name: "AES-GCM" }, defaultExtractable, options.keyUsage || ["encrypt", "decrypt"]);
1600
+ }
1601
+ /**
1602
+ * Imports a key from a PEM-encoded string and converts it to a JWK.
1603
+ *
1604
+ * @param pem The PEM-encoded string.
1605
+ * @param pemType The type of PEM encoding ('pkcs8' for private keys, 'spki' for public keys, 'x509' for certificates).
1606
+ * @param alg The JWA algorithm identifier. This is crucial for `crypto.subtle.importKey`
1607
+ * to understand the key's intended algorithm and for setting the 'alg' field in the resulting JWK.
1608
+ * @param importOptions Options for the PEM import process (e.g., extractable for the CryptoKey).
1609
+ * @param jwkExtras Additional properties to merge into the resulting JWK.
1610
+ * @returns A Promise resolving to the imported key as a JWK.
1611
+ */
1612
+ async function importJWKFromPEM(pem, pemType, alg, importOptions, jwkExtras) {
1613
+ let cryptoKey;
1614
+ const defaultExtractable = importOptions?.extractable !== false;
1615
+ switch (pemType) {
1616
+ case "pkcs8":
1617
+ cryptoKey = await fromPKCS8(pem, alg, {
1618
+ ...importOptions,
1619
+ extractable: defaultExtractable
1620
+ });
1621
+ break;
1622
+ case "spki":
1623
+ cryptoKey = await fromSPKI(pem, alg, {
1624
+ ...importOptions,
1625
+ extractable: defaultExtractable
1626
+ });
1627
+ break;
1628
+ case "x509":
1629
+ cryptoKey = await fromX509(pem, alg, {
1630
+ ...importOptions,
1631
+ extractable: defaultExtractable
1632
+ });
1633
+ break;
1634
+ default: throw new TypeError(`Unsupported PEM type: ${pemType}`);
1635
+ }
1636
+ const finalJWKExtras = {
1637
+ alg,
1638
+ ...jwkExtras
1639
+ };
1640
+ return exportKey(cryptoKey, finalJWKExtras);
1641
+ }
1642
+ /**
1643
+ * Exports a JWK to a PEM-encoded string.
1644
+ *
1645
+ * @param jwk The JWK to export.
1646
+ * @param pemFormat The desired PEM format ('pkcs8' for private keys, 'spki' for public keys).
1647
+ * @param algForCryptoKeyImport If the JWK does not have an 'alg' property, this algorithm hint is
1648
+ * required to correctly convert it to a CryptoKey first.
1649
+ * @returns A Promise resolving to the PEM-encoded key string.
1650
+ */
1651
+ async function exportJWKToPEM(jwk, pemFormat, algForCryptoKeyImport) {
1652
+ if (jwk.kty === "oct") throw new TypeError("Octet (symmetric) JWKs (kty: 'oct') cannot be exported to PKCS8 or SPKI PEM formats.");
1653
+ const effectiveAlg = jwk.alg || algForCryptoKeyImport;
1654
+ if (!effectiveAlg && (jwk.kty === "RSA" || jwk.kty === "EC" || jwk.kty === "OKP")) throw new TypeError("Algorithm (alg) must be provided in the JWK or as a parameter for converting this JWK type to a CryptoKey.");
1655
+ const cryptoKeyCandidate = await importKey({
1656
+ ...jwk,
1657
+ ext: true
1658
+ }, effectiveAlg);
1659
+ if (!isCryptoKey(cryptoKeyCandidate)) throw new Error("Failed to convert JWK to a CryptoKey instance suitable for PEM export.");
1660
+ const cryptoKey = cryptoKeyCandidate;
1661
+ switch (pemFormat) {
1662
+ case "pkcs8":
1663
+ if (cryptoKey.type !== "private") throw new TypeError(`Only 'private' type CryptoKeys can be exported to PKCS8 PEM format. Key type is '${cryptoKey.type}'.`);
1664
+ return toPKCS8(cryptoKey);
1665
+ case "spki":
1666
+ if (cryptoKey.type !== "public") throw new TypeError(`Only 'public' type CryptoKeys can be exported to SPKI PEM format. Key type is '${cryptoKey.type}'.`);
1667
+ return toSPKI(cryptoKey);
1668
+ default: throw new TypeError(`Unsupported PEM format: ${pemFormat}`);
1669
+ }
1670
+ }
1671
+ /**
1672
+ * Retrieves a JWK (JSON Web Key) from a JWKSet based on a key ID (kid) or
1673
+ * properties from a JOSE Header.
1674
+ *
1675
+ * @param jwkSet The JWKSet to search within.
1676
+ * @param kidOrProtectedHeader Either a string representing the 'kid' (Key ID)
1677
+ * or an object representing the JOSE Protected Header. If an object is
1678
+ * provided, it must contain a 'kid' property. It can optionally contain
1679
+ * 'alg' (Algorithm) and 'kty' (Key Type) to further refine the search.
1680
+ * @returns The matching JWK from the set.
1681
+ * @throws TypeError if `jwkSet` is invalid or `kidOrProtectedHeader` is not a
1682
+ * string or a valid header object.
1683
+ * @throws Error if no key is found matching the provided criteria, or if the
1684
+ * header object is missing the 'kid' property.
1685
+ */
1686
+ function getJWKFromSet(jwkSet, kidOrProtectedHeader) {
1687
+ if (!jwkSet || !isJWKSet(jwkSet)) throw new TypeError("Invalid JWK Set provided");
1688
+ if (typeof kidOrProtectedHeader === "string") {
1689
+ const kid = kidOrProtectedHeader;
1690
+ const selectedKey = jwkSet.keys.find((k) => k.kid === kid);
1691
+ if (!selectedKey) throw new Error(`No key found in JWK Set with kid "${kid}".`);
1692
+ return selectedKey;
1693
+ } else if (typeof kidOrProtectedHeader === "object") {
1694
+ const { kid, alg, kty } = kidOrProtectedHeader;
1695
+ if (!kid) throw new Error("JWS Protected Header is missing 'kid' (Key ID) and a JWK Set was provided. Cannot select key from JWK Set automatically.");
1696
+ const selectedKey = jwkSet.keys.find((k) => {
1697
+ return k.kid === kid && (!alg || k.alg === alg) && (!kty || k.kty === kty);
1698
+ });
1699
+ if (!selectedKey) {
1700
+ let errorMessage = `No key found in JWK Set with kid "${kid}"`;
1701
+ if (alg) errorMessage += ` and alg "${alg}"`;
1702
+ if (kty) errorMessage += ` and kty "${kty}"`;
1703
+ errorMessage += ".";
1704
+ throw new Error(errorMessage);
1705
+ }
1706
+ return selectedKey;
1707
+ }
1708
+ throw new TypeError("`kidOrProtectedHeader` must be a string (kid) or an object (JOSE Protected Header).");
1709
+ }
1710
+ function getGenerateKeyParams(alg, options) {
1711
+ let algorithm;
1712
+ let keyUsages;
1713
+ const defaultKeyUsage = options?.keyUsage;
1714
+ switch (alg) {
1715
+ case "HS256":
1716
+ case "HS384":
1717
+ case "HS512":
1718
+ algorithm = {
1719
+ name: "HMAC",
1720
+ hash: `SHA-${alg.slice(2)}`
1721
+ };
1722
+ keyUsages = defaultKeyUsage ?? ["sign", "verify"];
1723
+ break;
1724
+ case "RS256":
1725
+ case "RS384":
1726
+ case "RS512":
1727
+ algorithm = {
1728
+ name: "RSASSA-PKCS1-v1_5",
1729
+ modulusLength: options?.modulusLength ?? 2048,
1730
+ publicExponent: options?.publicExponent ?? new Uint8Array([
1731
+ 1,
1732
+ 0,
1733
+ 1
1734
+ ]),
1735
+ hash: `SHA-${alg.slice(2)}`
1736
+ };
1737
+ keyUsages = defaultKeyUsage ?? ["sign", "verify"];
1738
+ break;
1739
+ case "PS256":
1740
+ case "PS384":
1741
+ case "PS512":
1742
+ algorithm = {
1743
+ name: "RSA-PSS",
1744
+ modulusLength: options?.modulusLength ?? 2048,
1745
+ publicExponent: options?.publicExponent ?? new Uint8Array([
1746
+ 1,
1747
+ 0,
1748
+ 1
1749
+ ]),
1750
+ hash: `SHA-${alg.slice(2)}`
1751
+ };
1752
+ keyUsages = defaultKeyUsage ?? ["sign", "verify"];
1753
+ break;
1754
+ case "RSA-OAEP":
1755
+ case "RSA-OAEP-256":
1756
+ case "RSA-OAEP-384":
1757
+ case "RSA-OAEP-512":
1758
+ algorithm = {
1759
+ name: "RSA-OAEP",
1760
+ modulusLength: options?.modulusLength ?? 2048,
1761
+ publicExponent: options?.publicExponent ?? new Uint8Array([
1762
+ 1,
1763
+ 0,
1764
+ 1
1765
+ ]),
1766
+ hash: `SHA-${Number.parseInt(alg.slice(9), 10) || 1}`
1767
+ };
1768
+ keyUsages = defaultKeyUsage ?? [
1769
+ "encrypt",
1770
+ "decrypt",
1771
+ "wrapKey",
1772
+ "unwrapKey"
1773
+ ];
1774
+ break;
1775
+ case "A128KW":
1776
+ case "A192KW":
1777
+ case "A256KW":
1778
+ algorithm = {
1779
+ name: "AES-KW",
1780
+ length: Number.parseInt(alg.slice(1, 4), 10)
1781
+ };
1782
+ keyUsages = defaultKeyUsage ?? ["wrapKey", "unwrapKey"];
1783
+ break;
1784
+ case "A128GCM":
1785
+ case "A192GCM":
1786
+ case "A256GCM":
1787
+ case "A128GCMKW":
1788
+ case "A192GCMKW":
1789
+ case "A256GCMKW": {
1790
+ const baseAlg = alg.replace("KW", "");
1791
+ algorithm = {
1792
+ name: "AES-GCM",
1793
+ length: Number.parseInt(baseAlg.slice(1, 4), 10)
1794
+ };
1795
+ keyUsages = defaultKeyUsage ?? (alg.endsWith("KW") ? ["wrapKey", "unwrapKey"] : ["encrypt", "decrypt"]);
1796
+ break;
1797
+ }
1798
+ case "ES256":
1799
+ case "ES384":
1800
+ case "ES512":
1801
+ algorithm = {
1802
+ name: "ECDSA",
1803
+ namedCurve: `P-${alg.slice(2)}`
1804
+ };
1805
+ keyUsages = defaultKeyUsage ?? ["sign", "verify"];
1806
+ break;
1807
+ case "Ed25519":
1808
+ keyUsages = defaultKeyUsage ?? ["sign", "verify"];
1809
+ algorithm = { name: "Ed25519" };
1810
+ break;
1811
+ case "EdDSA": {
1812
+ keyUsages = defaultKeyUsage ?? ["sign", "verify"];
1813
+ const namedCurve = options?.namedCurve ?? "Ed25519";
1814
+ switch (namedCurve) {
1815
+ case "Ed25519":
1816
+ case "Ed448":
1817
+ algorithm = { name: namedCurve };
1818
+ break;
1819
+ default: throw new Error("Unsupported namedCurve provided. Supported values are: Ed25519 and Ed448");
1820
+ }
1821
+ break;
1822
+ }
1823
+ case "ECDH-ES":
1824
+ case "ECDH-ES+A128KW":
1825
+ case "ECDH-ES+A192KW":
1826
+ case "ECDH-ES+A256KW": {
1827
+ keyUsages = ["deriveBits"];
1828
+ const namedCurve = options?.namedCurve ?? "P-256";
1829
+ switch (namedCurve) {
1830
+ case "P-256":
1831
+ case "P-384":
1832
+ case "P-521":
1833
+ algorithm = {
1834
+ name: "ECDH",
1835
+ namedCurve
1836
+ };
1837
+ break;
1838
+ case "X25519":
1839
+ algorithm = { name: "X25519" };
1840
+ break;
1841
+ default: throw new Error("Unsupported namedCurve provided. Supported values are: P-256, P-384, P-521 and X25519");
1842
+ }
1843
+ break;
1844
+ }
1845
+ default: throw new Error(`Unsupported or invalid algorithm for key generation: ${alg}`);
1846
+ }
1847
+ return {
1848
+ algorithm,
1849
+ keyUsages
1850
+ };
1851
+ }
1852
+ function inferAesImportAlgorithm(enc, cekLengthBytes) {
1853
+ const bitLength = cekLengthBytes << 3;
1854
+ if (enc) {
1855
+ if (enc.includes("GCM")) return {
1856
+ name: "AES-GCM",
1857
+ length: Number.parseInt(enc.slice(1, 4), 10)
1858
+ };
1859
+ if (enc.includes("CBC-HS")) return;
1860
+ }
1861
+ if (bitLength === 128 || bitLength === 192 || bitLength === 256) return {
1862
+ name: "AES-GCM",
1863
+ length: bitLength
1864
+ };
1865
+ }
1866
+ //#endregion
1867
+ //#region src/core/jwe.ts
1868
+ async function encrypt(payload, key, options = {}) {
1869
+ const { protectedHeader: additionalProtectedHeader, cek: providedCek, contentEncryptionIV: providedContentIV, keyManagementIV, p2s, p2c, ecdh } = options;
1870
+ let { alg, enc } = options;
1871
+ if (!alg) {
1872
+ if (typeof key === "string" || key instanceof Uint8Array) alg = "PBES2-HS256+A128KW";
1873
+ else if (isJWK(key)) alg = key.alg === "A128GCM" || key.alg === "A192GCM" || key.alg === "A256GCM" ? `${key.alg}KW` : key.alg;
1874
+ }
1875
+ if (!alg) throw new TypeError("JWE \"alg\" (Key Management Algorithm) must be provided in options or inferable from the key");
1876
+ if (!enc) enc = isJWK(key) && "enc" in key ? key.enc : "A128GCM";
1877
+ const jweKeyManagementParams = {};
1878
+ if (keyManagementIV) jweKeyManagementParams.iv = keyManagementIV;
1879
+ if (p2s) jweKeyManagementParams.p2s = p2s;
1880
+ else if (alg?.startsWith("PBES2")) jweKeyManagementParams.p2s = randomBytes(16);
1881
+ if (p2c) jweKeyManagementParams.p2c = p2c;
1882
+ else if (alg?.startsWith("PBES2")) jweKeyManagementParams.p2c = 2048;
1883
+ if (ecdh?.partyUInfo) jweKeyManagementParams.apu = ecdh.partyUInfo;
1884
+ if (ecdh?.partyVInfo) jweKeyManagementParams.apv = ecdh.partyVInfo;
1885
+ if (ecdh?.ephemeralKey) {
1886
+ const { epk, epkPrivateKey } = parseEphemeralKey(ecdh.ephemeralKey);
1887
+ jweKeyManagementParams.epk = epk;
1888
+ jweKeyManagementParams.epkPrivateKey = epkPrivateKey;
1889
+ }
1890
+ const wrappingKeyMaterial = await importKey(key, alg);
1891
+ const { cek: finalCek, encryptedKey: jweEncryptedKey, parameters: keyManagementHeaderParams } = await encryptKey(alg, enc, wrappingKeyMaterial, providedCek, jweKeyManagementParams);
1892
+ const jweProtectedHeader = {
1893
+ ...additionalProtectedHeader,
1894
+ ...keyManagementHeaderParams,
1895
+ alg,
1896
+ enc
1897
+ };
1898
+ if (isJWK(key) && key.kid) jweProtectedHeader.kid = key.kid;
1899
+ const protectedHeader = applyTypCtyDefaults(jweProtectedHeader, payload);
1900
+ const plaintextBytes = getPlaintextBytes(computeJwtTimeClaims(payload, protectedHeader.typ, options.expiresIn, options.currentDate) || payload);
1901
+ const protectedHeaderEncoded = base64UrlEncode(JSON.stringify(protectedHeader));
1902
+ const aadBytes = textEncoder.encode(protectedHeaderEncoded);
1903
+ const contentIVBytes = providedContentIV ?? generateIV(enc);
1904
+ const { ciphertext: contentCiphertext, tag: contentAuthTag, iv: actualContentIV } = await encrypt$1(enc, plaintextBytes, finalCek, contentIVBytes, aadBytes);
1905
+ if (!actualContentIV) throw new Error("Content encryption IV was not generated or returned.");
1906
+ if (!contentAuthTag) throw new Error("Content encryption auth tag was not generated or returned.");
1907
+ return [
1908
+ protectedHeaderEncoded,
1909
+ jweEncryptedKey ? base64UrlEncode(jweEncryptedKey) : "",
1910
+ base64UrlEncode(actualContentIV),
1911
+ base64UrlEncode(contentCiphertext),
1912
+ base64UrlEncode(contentAuthTag)
1913
+ ].join(".");
1914
+ }
1915
+ async function decrypt(jwe, key, options = {}) {
1916
+ const parts = jwe.split(".");
1917
+ if (parts.length !== 5) throw new Error("Invalid JWE: Must contain five sections (RFC7516, section-3).");
1918
+ const [protectedHeaderEncoded, encryptedKeyEncoded, ivEncoded, ciphertextEncoded, authTagEncoded] = parts;
1919
+ let protectedHeader;
1920
+ try {
1921
+ const protectedHeaderJson = base64UrlDecode(protectedHeaderEncoded);
1922
+ protectedHeader = sanitizeObject(JSON.parse(protectedHeaderJson));
1923
+ } catch {
1924
+ throw new Error("Invalid JWE: Protected header could not be decoded.");
1925
+ }
1926
+ 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.");
1927
+ const alg = protectedHeader.alg;
1928
+ const enc = protectedHeader.enc;
1929
+ if (options?.algorithms && !options.algorithms.includes(alg)) throw new Error(`Key management algorithm not allowed: ${alg}`);
1930
+ if (options?.encryptionAlgorithms && !options.encryptionAlgorithms.includes(enc)) throw new Error(`Content encryption algorithm not allowed: ${enc}`);
1931
+ const unwrappingKey = await importKey(typeof key === "function" ? await key(protectedHeader, jwe) : key, alg);
1932
+ const encryptedKeyBytes = base64UrlDecode(encryptedKeyEncoded, false);
1933
+ const contentIVBytes = base64UrlDecode(ivEncoded, false);
1934
+ const contentAuthTagBytes = base64UrlDecode(authTagEncoded, false);
1935
+ const ciphertextBytes = base64UrlDecode(ciphertextEncoded, false);
1936
+ const unwrapKeyOpts = {
1937
+ enc,
1938
+ returnAs: enc.includes("GCM"),
1939
+ keyUsage: options?.keyUsage || ["decrypt"]
1940
+ };
1941
+ if (protectedHeader.iv) unwrapKeyOpts.iv = protectedHeader.iv;
1942
+ if (protectedHeader.tag) unwrapKeyOpts.tag = protectedHeader.tag;
1943
+ if (protectedHeader.p2s) unwrapKeyOpts.p2s = protectedHeader.p2s;
1944
+ if (protectedHeader.p2c) unwrapKeyOpts.p2c = protectedHeader.p2c;
1945
+ if (protectedHeader.epk) unwrapKeyOpts.epk = protectedHeader.epk;
1946
+ if (protectedHeader.apu) unwrapKeyOpts.apu = protectedHeader.apu;
1947
+ if (protectedHeader.apv) unwrapKeyOpts.apv = protectedHeader.apv;
1948
+ if (options?.unwrappedKeyAlgorithm) unwrapKeyOpts.unwrappedKeyAlgorithm = options.unwrappedKeyAlgorithm;
1949
+ if (options?.extractable) unwrapKeyOpts.extractable = options.extractable;
1950
+ const cek = await unwrapKey(alg, encryptedKeyBytes, unwrappingKey, unwrapKeyOpts);
1951
+ const aadBytes = textEncoder.encode(protectedHeaderEncoded);
1952
+ const payload = decodePayloadFromBytes(await decrypt$1(enc, cek, ciphertextBytes, contentIVBytes, contentAuthTagBytes, aadBytes), protectedHeader, options?.forceUint8Array);
1953
+ if (protectedHeader.crit || options?.critical?.length || options?.requiredHeaders?.length) validateCriticalHeadersJWE(protectedHeader, [...options?.critical || [], ...options?.requiredHeaders || []]);
1954
+ if (payload && typeof payload === "object" && options.validateJWT !== false && (options.validateJWT === true || protectedHeader.typ?.toLowerCase().includes("jwt")) && !options.forceUint8Array && !(payload instanceof Uint8Array)) validateJwtClaims(payload, options);
1955
+ const result = {
1956
+ payload,
1957
+ protectedHeader
1958
+ };
1959
+ if (options.returnCek) {
1960
+ result.cek = isCryptoKey(cek) ? new Uint8Array(await crypto.subtle.exportKey("raw", cek)) : cek;
1961
+ result.aad = aadBytes;
1962
+ }
1963
+ return result;
1964
+ }
1965
+ function parseEphemeralKey(ephemeralKey) {
1966
+ let epk;
1967
+ let epkPrivateKey;
1968
+ if (isCryptoKeyPair(ephemeralKey)) {
1969
+ epk = ephemeralKey.publicKey;
1970
+ epkPrivateKey = ephemeralKey.privateKey;
1971
+ } else if (typeof ephemeralKey === "object" && ephemeralKey !== null && "publicKey" in ephemeralKey && "privateKey" in ephemeralKey) {
1972
+ const candidate = ephemeralKey;
1973
+ if (!candidate.publicKey || !candidate.privateKey) throw new TypeError("ECDH-ES custom ephemeral key must include both publicKey and privateKey.");
1974
+ epk = candidate.publicKey;
1975
+ epkPrivateKey = candidate.privateKey;
1976
+ } else if (isCryptoKey(ephemeralKey)) {
1977
+ if (ephemeralKey.type !== "private") throw new TypeError("ECDH-ES custom ephemeral CryptoKey must include private key material.");
1978
+ epk = ephemeralKey;
1979
+ epkPrivateKey = ephemeralKey;
1980
+ } else if (isJWK(ephemeralKey)) {
1981
+ if (!("d" in ephemeralKey) || typeof ephemeralKey.d !== "string") throw new TypeError("ECDH-ES custom ephemeral JWK must include private parameter \"d\".");
1982
+ epk = ephemeralKey;
1983
+ epkPrivateKey = ephemeralKey;
1984
+ } else throw new TypeError("Unsupported ECDH-ES ephemeral key material provided in options.");
1985
+ return {
1986
+ epk,
1987
+ epkPrivateKey
1988
+ };
1989
+ }
1990
+ //#endregion
1991
+ //#region src/core/jws.ts
1992
+ async function sign(payload, key, options = {}) {
1993
+ const { protectedHeader: additionalProtectedHeader } = options;
1994
+ const safeAdditionalHeader = sanitizeObject(additionalProtectedHeader);
1995
+ let { alg } = options;
1996
+ if (!alg) if (isJWK(key) && key.alg) alg = key.alg;
1997
+ else throw new TypeError("JWS \"alg\" (Algorithm) must be provided in options");
1998
+ validateKeyLength(key, alg);
1999
+ const signingKey = await importKey(key, alg);
2000
+ const protectedHeader = {
2001
+ ...safeAdditionalHeader,
2002
+ ...isJWK(key) && key.kid ? { kid: key.kid } : {},
2003
+ alg,
2004
+ typ: safeAdditionalHeader?.typ
2005
+ };
2006
+ applyTypCtyDefaults(protectedHeader, payload);
2007
+ if (protectedHeader.b64 === true) delete protectedHeader.b64;
2008
+ const computedPayload = computeJwtTimeClaims(payload, protectedHeader.typ, options.expiresIn, options.currentDate);
2009
+ const protectedHeaderEncoded = base64UrlEncode(JSON.stringify(protectedHeader));
2010
+ let payloadBytes;
2011
+ if (payload instanceof Uint8Array) payloadBytes = payload;
2012
+ else if (typeof payload === "string") payloadBytes = textEncoder.encode(payload);
2013
+ else if (typeof payload === "object" && payload !== null) payloadBytes = textEncoder.encode(JSON.stringify(computedPayload || payload));
2014
+ else throw new TypeError("Payload must be a string, Uint8Array, or a JSON-serializable object.");
2015
+ const signingInputString = `${protectedHeaderEncoded}.${protectedHeader.b64 !== false ? base64UrlEncode(payloadBytes) : textDecoder.decode(payloadBytes)}`;
2016
+ const signingInputBytes = textEncoder.encode(signingInputString);
2017
+ return `${signingInputString}.${base64UrlEncode(await sign$1(alg, signingKey, signingInputBytes))}`;
2018
+ }
2019
+ async function verify(jws, key, options = {}) {
2020
+ const parts = jws.split(".");
2021
+ if (parts.length !== 3) throw new Error("Invalid JWS: Must contain three parts separated by dots.");
2022
+ const [protectedHeaderEncoded, payloadEncoded, signatureEncoded] = parts;
2023
+ let protectedHeader;
2024
+ try {
2025
+ const protectedHeaderString = base64UrlDecode(protectedHeaderEncoded);
2026
+ protectedHeader = sanitizeObject(JSON.parse(protectedHeaderString));
2027
+ } catch {
2028
+ throw new Error("Invalid JWS: Protected header could not be decoded.");
2029
+ }
2030
+ if (!protectedHeader || typeof protectedHeader !== "object" || !protectedHeader.alg) throw new Error("Invalid JWS: Protected header must be an object with an \"alg\" property.");
2031
+ const alg = protectedHeader.alg;
2032
+ if (options.algorithms && !options.algorithms.includes(alg)) throw new Error(`Algorithm not allowed: ${alg}`);
2033
+ if (options.typ && protectedHeader.typ !== options.typ) throw new Error(`Invalid JWS: "typ" (Type) Header Parameter mismatch. Expected "${options.typ}", got "${protectedHeader.typ}".`);
2034
+ let signatureBytes;
2035
+ try {
2036
+ signatureBytes = base64UrlDecode(signatureEncoded, false);
2037
+ } catch {
2038
+ throw new Error("Invalid JWS: Signature could not be decoded.");
2039
+ }
2040
+ const keyInput = typeof key === "function" ? await key(protectedHeader, jws) : key;
2041
+ const verificationKey = await importKey(isJWKSet(keyInput) ? getJWKFromSet(keyInput, protectedHeader) : keyInput, alg);
2042
+ const signingInputString = `${protectedHeaderEncoded}.${payloadEncoded}`;
2043
+ const signingInputBytes = textEncoder.encode(signingInputString);
2044
+ if (!await verify$1(alg, verificationKey, signatureBytes, signingInputBytes)) throw new Error("JWS signature verification failed.");
2045
+ const useB64 = protectedHeader.b64 !== false;
2046
+ let payload;
2047
+ try {
2048
+ payload = useB64 ? decodePayloadFromB64UrlSegment(payloadEncoded, protectedHeader, options.forceUint8Array) : options.forceUint8Array ? textEncoder.encode(payloadEncoded) : payloadEncoded;
2049
+ } catch (error_) {
2050
+ throw new Error(`Invalid JWS: Payload decoding failed (${error_ instanceof Error ? error_.message : error_})`);
2051
+ }
2052
+ validateCriticalHeadersJWS(protectedHeader, [...options.critical || [], ...options.requiredHeaders || []]);
2053
+ if (payload && typeof payload === "object" && options.validateJWT !== false && (options.validateJWT === true || protectedHeader.typ?.toLowerCase().includes("jwt")) && !options.forceUint8Array && !(payload instanceof Uint8Array)) validateJwtClaims(payload, options);
2054
+ return {
2055
+ payload,
2056
+ protectedHeader
2057
+ };
2058
+ }
2059
+ function validateKeyLength(key, alg) {
2060
+ if (!alg || isJWK(key)) return;
2061
+ if (alg.startsWith("HS") && key instanceof Uint8Array) {
2062
+ const algLength = Number.parseInt(alg.slice(2)) / 8;
2063
+ if (key.length < algLength) throw new TypeError(`${alg} requires key length to be ${algLength} bytes or larger`);
2064
+ } else if ((alg.startsWith("RS") || alg.startsWith("PS")) && key instanceof CryptoKey) {
2065
+ const { modulusLength } = key.algorithm;
2066
+ if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
2067
+ }
2068
+ }
2069
+ //#endregion
2070
+ export { deriveJWKFromPassword as a, importJWKFromPEM as c, isSymmetricJWK as d, computeExpiresInSeconds as f, encrypt as i, isPrivateJWK as l, verify as n, exportJWKToPEM as o, decrypt as r, generateJWK as s, sign as t, isPublicJWK as u };