@workos-inc/node 10.10.0 → 10.11.0

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.
@@ -13,6 +13,7 @@ var __exportAll = (all, no_symbols) => {
13
13
  //#region node_modules/jose/dist/webapi/lib/buffer_utils.js
14
14
  const encoder = new TextEncoder();
15
15
  const decoder = new TextDecoder();
16
+ const strictDecoder = new TextDecoder("utf-8", { fatal: true });
16
17
  const MAX_INT32 = 2 ** 32;
17
18
  function concat(...buffers) {
18
19
  const size = buffers.reduce((acc, { length }) => acc + length, 0);
@@ -56,154 +57,26 @@ function encode$1(string) {
56
57
  return bytes;
57
58
  }
58
59
  //#endregion
59
- //#region node_modules/jose/dist/webapi/lib/base64.js
60
- function encodeBase64(input) {
61
- if (Uint8Array.prototype.toBase64) return input.toBase64();
62
- const CHUNK_SIZE = 32768;
63
- const arr = [];
64
- for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
65
- return btoa(arr.join(""));
66
- }
67
- function decodeBase64(encoded) {
68
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
69
- const binary = atob(encoded);
70
- const bytes = new Uint8Array(binary.length);
71
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
72
- return bytes;
73
- }
74
- //#endregion
75
- //#region node_modules/jose/dist/webapi/util/base64url.js
76
- var base64url_exports = /* @__PURE__ */ __exportAll({
77
- decode: () => decode,
78
- encode: () => encode
79
- });
80
- function decode(input) {
81
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" });
82
- let encoded = input;
83
- if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
84
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
85
- try {
86
- return decodeBase64(encoded);
87
- } catch {
88
- throw new TypeError("The input to be decoded is not correctly encoded.");
89
- }
90
- }
91
- function encode(input) {
92
- let unencoded = input;
93
- if (typeof unencoded === "string") unencoded = encoder.encode(unencoded);
94
- if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
95
- alphabet: "base64url",
96
- omitPadding: true
97
- });
98
- return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
99
- }
100
- //#endregion
101
60
  //#region node_modules/jose/dist/webapi/lib/crypto_key.js
102
61
  const unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
103
- const isAlgorithm = (algorithm, name) => algorithm.name === name;
104
- function getHashLength(hash) {
105
- return parseInt(hash.name.slice(4), 10);
106
- }
107
- function checkHashLength(algorithm, expected) {
108
- if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
109
- }
110
- function getNamedCurve(alg) {
111
- switch (alg) {
112
- case "ES256": return "P-256";
113
- case "ES384": return "P-384";
114
- case "ES512": return "P-521";
115
- default: throw new Error("unreachable");
116
- }
117
- }
118
62
  function checkUsage(key, usage) {
119
63
  if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
120
64
  }
121
- function checkSigCryptoKey(key, alg, usage) {
122
- switch (alg) {
123
- case "HS256":
124
- case "HS384":
125
- case "HS512":
126
- if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
127
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
128
- break;
129
- case "RS256":
130
- case "RS384":
131
- case "RS512":
132
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
133
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
134
- break;
135
- case "PS256":
136
- case "PS384":
137
- case "PS512":
138
- if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
139
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
140
- break;
141
- case "Ed25519":
142
- case "EdDSA":
143
- if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
144
- break;
145
- case "ML-DSA-44":
146
- case "ML-DSA-65":
147
- case "ML-DSA-87":
148
- if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg);
149
- break;
150
- case "ES256":
151
- case "ES384":
152
- case "ES512": {
153
- if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
154
- const expected = getNamedCurve(alg);
155
- if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
156
- break;
157
- }
158
- default: throw new TypeError("CryptoKey does not support this operation");
159
- }
160
- checkUsage(key, usage);
65
+ function checkModulusLength(alg, key) {
66
+ const { modulusLength } = key.algorithm;
67
+ if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
161
68
  }
162
- function checkEncCryptoKey(key, alg, usage) {
163
- switch (alg) {
164
- case "A128GCM":
165
- case "A192GCM":
166
- case "A256GCM": {
167
- if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM");
168
- const expected = parseInt(alg.slice(1, 4), 10);
169
- if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length");
170
- break;
171
- }
172
- case "A128KW":
173
- case "A192KW":
174
- case "A256KW": {
175
- if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW");
176
- const expected = parseInt(alg.slice(1, 4), 10);
177
- if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length");
178
- break;
179
- }
180
- case "ECDH":
181
- switch (key.algorithm.name) {
182
- case "ECDH":
183
- case "X25519": break;
184
- default: throw unusable("ECDH or X25519");
185
- }
186
- break;
187
- case "PBES2-HS256+A128KW":
188
- case "PBES2-HS384+A192KW":
189
- case "PBES2-HS512+A256KW":
190
- if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2");
191
- break;
192
- case "RSA-OAEP":
193
- case "RSA-OAEP-256":
194
- case "RSA-OAEP-384":
195
- case "RSA-OAEP-512":
196
- if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP");
197
- checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1);
198
- break;
199
- default: throw new TypeError("CryptoKey does not support this operation");
200
- }
69
+ function checkCryptoKey(key, expected, usage) {
70
+ const algorithm = key.algorithm;
71
+ if (algorithm.name !== expected.name) throw unusable(expected.name);
72
+ if (expected.hash && algorithm.hash?.name !== expected.hash) throw unusable(expected.hash, "algorithm.hash");
73
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) throw unusable(expected.namedCurve, "algorithm.namedCurve");
74
+ if (expected.length !== void 0 && algorithm.length !== expected.length) throw unusable(expected.length, "algorithm.length");
201
75
  checkUsage(key, usage);
202
76
  }
203
77
  //#endregion
204
78
  //#region node_modules/jose/dist/webapi/lib/invalid_key_input.js
205
79
  function message(msg, actual, ...types) {
206
- types = types.filter(Boolean);
207
80
  if (types.length > 2) {
208
81
  const last = types.pop();
209
82
  msg += `one of type ${types.join(", ")}, or ${last}.`;
@@ -323,7 +196,7 @@ var JWKSNoMatchingKey = class extends JOSEError {
323
196
  }
324
197
  };
325
198
  var JWKSMultipleMatchingKeys = class extends JOSEError {
326
- [Symbol.asyncIterator];
199
+ [Symbol.asyncIterator] = async function* () {};
327
200
  static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
328
201
  code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
329
202
  constructor(message = "multiple matching keys found in the JSON Web Key Set", options) {
@@ -361,85 +234,54 @@ const isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
361
234
  const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
362
235
  //#endregion
363
236
  //#region node_modules/jose/dist/webapi/lib/content_encryption.js
364
- function cekLength(alg) {
365
- switch (alg) {
366
- case "A128GCM": return 128;
367
- case "A192GCM": return 192;
368
- case "A256GCM":
369
- case "A128CBC-HS256": return 256;
370
- case "A192CBC-HS384": return 384;
371
- case "A256CBC-HS512": return 512;
372
- default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
373
- }
374
- }
375
- const generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3));
237
+ const generateCek = (enc) => crypto.getRandomValues(new Uint8Array(enc.cekBits >> 3));
376
238
  function checkCekLength(cek, expected) {
377
239
  const actual = cek.byteLength << 3;
378
240
  if (actual !== expected) throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
379
241
  }
380
- function ivBitLength(alg) {
381
- switch (alg) {
382
- case "A128GCM":
383
- case "A128GCMKW":
384
- case "A192GCM":
385
- case "A192GCMKW":
386
- case "A256GCM":
387
- case "A256GCMKW": return 96;
388
- case "A128CBC-HS256":
389
- case "A192CBC-HS384":
390
- case "A256CBC-HS512": return 128;
391
- default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
392
- }
393
- }
394
- const generateIv = (alg) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg) >> 3));
242
+ const generateIv = (enc) => crypto.getRandomValues(new Uint8Array(enc.ivBits >> 3));
395
243
  function checkIvLength(enc, iv) {
396
- if (iv.length << 3 !== ivBitLength(enc)) throw new JWEInvalid("Invalid Initialization Vector length");
244
+ if (iv.length << 3 !== enc.ivBits) throw new JWEInvalid("Invalid Initialization Vector length");
397
245
  }
398
246
  async function cbcKeySetup(enc, cek, usage) {
399
247
  if (!(cek instanceof Uint8Array)) throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
400
- const keySize = parseInt(enc.slice(1, 4), 10);
401
- return {
402
- encKey: await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]),
403
- macKey: await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
248
+ const keySize = enc.cekBits >> 1;
249
+ return [
250
+ await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]),
251
+ await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
404
252
  hash: `SHA-${keySize << 1}`,
405
253
  name: "HMAC"
406
254
  }, false, ["sign"]),
407
255
  keySize
408
- };
256
+ ];
409
257
  }
410
258
  async function cbcHmacTag(macKey, macData, keySize) {
411
259
  return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
412
260
  }
413
261
  async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
414
- const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "encrypt");
262
+ const [encKey, macKey, keySize] = await cbcKeySetup(enc, cek, "encrypt");
415
263
  const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
416
264
  iv,
417
265
  name: "AES-CBC"
418
266
  }, encKey, plaintext));
419
267
  return {
420
268
  ciphertext,
421
- tag: await cbcHmacTag(macKey, concat(aad, iv, ciphertext, uint64be(aad.length << 3)), keySize),
269
+ tag: await cbcHmacTag(macKey, concat(aad, iv, ciphertext, uint64be(aad.length * 8)), keySize),
422
270
  iv
423
271
  };
424
272
  }
425
273
  async function timingSafeEqual(a, b) {
426
- if (!(a instanceof Uint8Array)) throw new TypeError("First argument must be a buffer");
427
- if (!(b instanceof Uint8Array)) throw new TypeError("Second argument must be a buffer");
428
274
  const algorithm = {
429
275
  name: "HMAC",
430
276
  hash: "SHA-256"
431
277
  };
432
- const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]);
433
- const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
434
- const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
435
- let out = 0;
436
- let i = -1;
437
- while (++i < 32) out |= aHmac[i] ^ bHmac[i];
438
- return out === 0;
278
+ const key = await crypto.subtle.generateKey(algorithm, false, ["sign", "verify"]);
279
+ const aHmac = await crypto.subtle.sign(algorithm, key, a);
280
+ return crypto.subtle.verify(algorithm, key, aHmac, b);
439
281
  }
440
282
  async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
441
- const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "decrypt");
442
- const expectedTag = await cbcHmacTag(macKey, concat(aad, iv, ciphertext, uint64be(aad.length << 3)), keySize);
283
+ const [encKey, macKey, keySize] = await cbcKeySetup(enc, cek, "decrypt");
284
+ const expectedTag = await cbcHmacTag(macKey, concat(aad, iv, ciphertext, uint64be(aad.length * 8)), keySize);
443
285
  let macCheckPassed;
444
286
  try {
445
287
  macCheckPassed = await timingSafeEqual(tag, expectedTag);
@@ -456,12 +298,7 @@ async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
456
298
  return plaintext;
457
299
  }
458
300
  async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
459
- let encKey;
460
- if (cek instanceof Uint8Array) encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
461
- else {
462
- checkEncCryptoKey(cek, enc, "encrypt");
463
- encKey = cek;
464
- }
301
+ const encKey = cek instanceof Uint8Array ? await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]) : (checkCryptoKey(cek, enc.subtle, "encrypt"), cek);
465
302
  const encrypted = new Uint8Array(await crypto.subtle.encrypt({
466
303
  additionalData: aad,
467
304
  iv,
@@ -476,12 +313,7 @@ async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
476
313
  };
477
314
  }
478
315
  async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
479
- let encKey;
480
- if (cek instanceof Uint8Array) encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
481
- else {
482
- checkEncCryptoKey(cek, enc, "decrypt");
483
- encKey = cek;
484
- }
316
+ const encKey = cek instanceof Uint8Array ? await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]) : (checkCryptoKey(cek, enc.subtle, "decrypt"), cek);
485
317
  try {
486
318
  return new Uint8Array(await crypto.subtle.decrypt({
487
319
  additionalData: aad,
@@ -493,84 +325,86 @@ async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
493
325
  throw new JWEDecryptionFailed();
494
326
  }
495
327
  }
496
- const unsupportedEnc = "Unsupported JWE Content Encryption Algorithm";
497
- async function encrypt$1(enc, plaintext, cek, iv, aad) {
328
+ async function encrypt(enc, plaintext, cek, iv, aad) {
498
329
  if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
499
330
  if (iv) checkIvLength(enc, iv);
500
331
  else iv = generateIv(enc);
501
- switch (enc) {
502
- case "A128CBC-HS256":
503
- case "A192CBC-HS384":
504
- case "A256CBC-HS512":
505
- if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10));
506
- return cbcEncrypt(enc, plaintext, cek, iv, aad);
507
- case "A128GCM":
508
- case "A192GCM":
509
- case "A256GCM":
510
- if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
511
- return gcmEncrypt(enc, plaintext, cek, iv, aad);
512
- default: throw new JOSENotSupported(unsupportedEnc);
513
- }
332
+ if (cek instanceof Uint8Array) checkCekLength(cek, enc.cekBits);
333
+ return enc.cbc ? cbcEncrypt(enc, plaintext, cek, iv, aad) : gcmEncrypt(enc, plaintext, cek, iv, aad);
514
334
  }
515
- async function decrypt$1(enc, cek, ciphertext, iv, tag, aad) {
335
+ async function decrypt(enc, cek, ciphertext, iv, tag, aad) {
516
336
  if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
517
337
  if (!iv) throw new JWEInvalid("JWE Initialization Vector missing");
518
338
  if (!tag) throw new JWEInvalid("JWE Authentication Tag missing");
519
339
  checkIvLength(enc, iv);
520
- switch (enc) {
521
- case "A128CBC-HS256":
522
- case "A192CBC-HS384":
523
- case "A256CBC-HS512":
524
- if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10));
525
- return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);
526
- case "A128GCM":
527
- case "A192GCM":
528
- case "A256GCM":
529
- if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
530
- return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);
531
- default: throw new JOSENotSupported(unsupportedEnc);
532
- }
340
+ if (cek instanceof Uint8Array) checkCekLength(cek, enc.cekBits);
341
+ return enc.cbc ? cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) : gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);
533
342
  }
534
343
  //#endregion
535
- //#region node_modules/jose/dist/webapi/lib/helpers.js
536
- const unprotected = Symbol();
537
- function assertNotSet(value, name) {
538
- if (value) throw new TypeError(`${name} can only be called once`);
344
+ //#region node_modules/jose/dist/webapi/lib/base64.js
345
+ function encodeBase64(input) {
346
+ if (Uint8Array.prototype.toBase64) return input.toBase64();
347
+ const CHUNK_SIZE = 32768;
348
+ const arr = [];
349
+ for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
350
+ return btoa(arr.join(""));
539
351
  }
540
- function decodeBase64url(value, label, ErrorClass) {
352
+ function decodeBase64(encoded) {
353
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
354
+ const binary = atob(encoded);
355
+ const bytes = new Uint8Array(binary.length);
356
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
357
+ return bytes;
358
+ }
359
+ //#endregion
360
+ //#region node_modules/jose/dist/webapi/util/base64url.js
361
+ var base64url_exports = /* @__PURE__ */ __exportAll({
362
+ decode: () => decode,
363
+ encode: () => encode
364
+ });
365
+ const invalid = "The input to be decoded is not correctly encoded.";
366
+ function decode(input) {
367
+ if (Uint8Array.fromBase64) try {
368
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" });
369
+ } catch (cause) {
370
+ throw new TypeError(invalid, { cause });
371
+ }
372
+ let encoded = input;
373
+ if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
374
+ if (encoded.includes("+") || encoded.includes("/")) throw new TypeError(invalid);
375
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
541
376
  try {
542
- return decode(value);
377
+ return decodeBase64(encoded);
543
378
  } catch {
544
- throw new ErrorClass(`Failed to base64url decode the ${label}`);
379
+ throw new TypeError(invalid);
545
380
  }
546
381
  }
547
- async function digest(algorithm, data) {
548
- const subtleDigest = `SHA-${algorithm.slice(-3)}`;
549
- return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
382
+ function encode(input) {
383
+ let unencoded = input;
384
+ if (typeof unencoded === "string") unencoded = encoder.encode(unencoded);
385
+ if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
386
+ alphabet: "base64url",
387
+ omitPadding: true
388
+ });
389
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
550
390
  }
551
391
  //#endregion
552
392
  //#region node_modules/jose/dist/webapi/lib/type_checks.js
553
- const isObjectLike = (value) => typeof value === "object" && value !== null;
554
393
  function isObject(input) {
555
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
556
- if (Object.getPrototypeOf(input) === null) return true;
557
- let proto = input;
394
+ if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") return false;
395
+ const prototype = Object.getPrototypeOf(input);
396
+ if (prototype === null) return true;
397
+ let proto = prototype;
558
398
  while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
559
- return Object.getPrototypeOf(input) === proto;
399
+ return prototype === proto;
560
400
  }
561
401
  function isDisjoint(...headers) {
562
- const sources = headers.filter(Boolean);
563
- if (sources.length === 0 || sources.length === 1) return true;
564
- let acc;
565
- for (const header of sources) {
566
- const parameters = Object.keys(header);
567
- if (!acc || acc.size === 0) {
568
- acc = new Set(parameters);
569
- continue;
570
- }
571
- for (const parameter of parameters) {
572
- if (acc.has(parameter)) return false;
573
- acc.add(parameter);
402
+ const parameters = /* @__PURE__ */ new Set();
403
+ for (const header of headers) {
404
+ if (!header) continue;
405
+ for (const parameter of Object.keys(header)) {
406
+ if (parameters.has(parameter)) return false;
407
+ parameters.add(parameter);
574
408
  }
575
409
  }
576
410
  return true;
@@ -580,809 +414,373 @@ const isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof
580
414
  const isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
581
415
  const isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
582
416
  //#endregion
583
- //#region node_modules/jose/dist/webapi/lib/aeskw.js
584
- function checkKeySize(key, alg) {
585
- if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) throw new TypeError(`Invalid key size for alg: ${alg}`);
586
- }
587
- function getCryptoKey$1(key, alg, usage) {
588
- if (key instanceof Uint8Array) return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]);
589
- checkEncCryptoKey(key, alg, usage);
590
- return key;
591
- }
592
- async function wrap$2(alg, key, cek) {
593
- const cryptoKey = await getCryptoKey$1(key, alg, "wrapKey");
594
- checkKeySize(cryptoKey, alg);
595
- const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, {
596
- hash: "SHA-256",
597
- name: "HMAC"
598
- }, true, ["sign"]);
599
- return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
600
- }
601
- async function unwrap$2(alg, key, encryptedKey) {
602
- const cryptoKey = await getCryptoKey$1(key, alg, "unwrapKey");
603
- checkKeySize(cryptoKey, alg);
604
- const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", {
605
- hash: "SHA-256",
606
- name: "HMAC"
607
- }, true, ["sign"]);
608
- return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
609
- }
610
- //#endregion
611
- //#region node_modules/jose/dist/webapi/lib/ecdhes.js
612
- function lengthAndInput(input) {
613
- return concat(uint32be(input.length), input);
614
- }
615
- async function concatKdf(Z, L, OtherInfo) {
616
- const dkLen = L >> 3;
617
- const hashLen = 32;
618
- const reps = Math.ceil(dkLen / hashLen);
619
- const dk = new Uint8Array(reps * hashLen);
620
- for (let i = 1; i <= reps; i++) {
621
- const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);
622
- hashInput.set(uint32be(i), 0);
623
- hashInput.set(Z, 4);
624
- hashInput.set(OtherInfo, 4 + Z.length);
625
- const hashResult = await digest("sha256", hashInput);
626
- dk.set(hashResult, (i - 1) * hashLen);
627
- }
628
- return dk.slice(0, dkLen);
629
- }
630
- async function deriveKey$1(publicKey, privateKey, algorithm, keyLength, apu = /* @__PURE__ */ new Uint8Array(), apv = /* @__PURE__ */ new Uint8Array()) {
631
- checkEncCryptoKey(publicKey, "ECDH");
632
- checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
633
- const otherInfo = concat(lengthAndInput(encode$1(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength), /* @__PURE__ */ new Uint8Array());
634
- return concatKdf(new Uint8Array(await crypto.subtle.deriveBits({
635
- name: publicKey.algorithm.name,
636
- public: publicKey
637
- }, privateKey, getEcdhBitLength(publicKey))), keyLength, otherInfo);
638
- }
639
- function getEcdhBitLength(publicKey) {
640
- if (publicKey.algorithm.name === "X25519") return 256;
641
- return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
642
- }
643
- function allowed(key) {
644
- switch (key.algorithm.namedCurve) {
645
- case "P-256":
646
- case "P-384":
647
- case "P-521": return true;
648
- default: return key.algorithm.name === "X25519";
649
- }
650
- }
651
- //#endregion
652
- //#region node_modules/jose/dist/webapi/lib/pbes2kw.js
653
- function getCryptoKey(key, alg) {
654
- if (key instanceof Uint8Array) return crypto.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]);
655
- checkEncCryptoKey(key, alg, "deriveBits");
656
- return key;
657
- }
658
- const concatSalt = (alg, p2sInput) => concat(encode$1(alg), Uint8Array.of(0), p2sInput);
659
- async function deriveKey(p2s, alg, p2c, key) {
660
- if (!(p2s instanceof Uint8Array) || p2s.length < 8) throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
661
- if (!Number.isSafeInteger(p2c) || Math.sign(p2c) !== 1) throw new JWEInvalid("PBES2 Count Input must be a positive integer");
662
- const salt = concatSalt(alg, p2s);
663
- const keylen = parseInt(alg.slice(13, 16), 10);
664
- const subtleAlg = {
665
- hash: `SHA-${alg.slice(8, 11)}`,
666
- iterations: p2c,
667
- name: "PBKDF2",
668
- salt
669
- };
670
- const cryptoKey = await getCryptoKey(key, alg);
671
- return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
672
- }
673
- async function wrap$1(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))) {
674
- const derived = await deriveKey(p2s, alg, p2c, key);
675
- return {
676
- encryptedKey: await wrap$2(alg.slice(-6), derived, cek),
677
- p2c,
678
- p2s: encode(p2s)
679
- };
680
- }
681
- async function unwrap$1(alg, key, encryptedKey, p2c, p2s) {
682
- const derived = await deriveKey(p2s, alg, p2c, key);
683
- return unwrap$2(alg.slice(-6), derived, encryptedKey);
417
+ //#region node_modules/jose/dist/webapi/lib/helpers.js
418
+ const unprotected = Symbol();
419
+ function assertNotSet(value, name) {
420
+ if (value) throw new TypeError(`${name} can only be called once`);
684
421
  }
685
- //#endregion
686
- //#region node_modules/jose/dist/webapi/lib/signing.js
687
- function checkKeyLength(alg, key) {
688
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
689
- const { modulusLength } = key.algorithm;
690
- if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
422
+ function decodeBase64url(value, label, ErrorClass) {
423
+ try {
424
+ return decode(value);
425
+ } catch {
426
+ throw new ErrorClass(`Failed to base64url decode the ${label}`);
691
427
  }
692
428
  }
693
- function subtleAlgorithm$1(alg, algorithm) {
694
- const hash = `SHA-${alg.slice(-3)}`;
695
- switch (alg) {
696
- case "HS256":
697
- case "HS384":
698
- case "HS512": return {
699
- hash,
700
- name: "HMAC"
701
- };
702
- case "PS256":
703
- case "PS384":
704
- case "PS512": return {
705
- hash,
706
- name: "RSA-PSS",
707
- saltLength: parseInt(alg.slice(-3), 10) >> 3
708
- };
709
- case "RS256":
710
- case "RS384":
711
- case "RS512": return {
712
- hash,
713
- name: "RSASSA-PKCS1-v1_5"
714
- };
715
- case "ES256":
716
- case "ES384":
717
- case "ES512": return {
718
- hash,
719
- name: "ECDSA",
720
- namedCurve: algorithm.namedCurve
721
- };
722
- case "Ed25519":
723
- case "EdDSA": return { name: "Ed25519" };
724
- case "ML-DSA-44":
725
- case "ML-DSA-65":
726
- case "ML-DSA-87": return { name: alg };
727
- default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
728
- }
729
- }
730
- async function getSigKey(alg, key, usage) {
731
- if (key instanceof Uint8Array) {
732
- if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
733
- return crypto.subtle.importKey("raw", key, {
734
- hash: `SHA-${alg.slice(-3)}`,
735
- name: "HMAC"
736
- }, false, [usage]);
429
+ function encodeBase64url(value, label, ErrorClass) {
430
+ try {
431
+ return encode$1(value);
432
+ } catch {
433
+ throw new ErrorClass(`The ${label} is not a valid base64url string`);
737
434
  }
738
- checkSigCryptoKey(key, alg, usage);
739
- return key;
740
435
  }
741
- async function sign(alg, key, data) {
742
- const cryptoKey = await getSigKey(alg, key, "sign");
743
- checkKeyLength(alg, cryptoKey);
744
- const signature = await crypto.subtle.sign(subtleAlgorithm$1(alg, cryptoKey.algorithm), cryptoKey, data);
745
- return new Uint8Array(signature);
436
+ async function digest(algorithm, data) {
437
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
438
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
746
439
  }
747
- async function verify(alg, key, signature, data) {
748
- const cryptoKey = await getSigKey(alg, key, "verify");
749
- checkKeyLength(alg, cryptoKey);
750
- const algorithm = subtleAlgorithm$1(alg, cryptoKey.algorithm);
440
+ function parseJoseHeader(b64, ErrorClass, message) {
441
+ let parsed;
751
442
  try {
752
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
443
+ parsed = JSON.parse(strictDecoder.decode(decode(b64)));
753
444
  } catch {
754
- return false;
445
+ throw new ErrorClass(message);
755
446
  }
756
- }
757
- //#endregion
758
- //#region node_modules/jose/dist/webapi/lib/rsaes.js
759
- const subtleAlgorithm = (alg) => {
760
- switch (alg) {
761
- case "RSA-OAEP":
762
- case "RSA-OAEP-256":
763
- case "RSA-OAEP-384":
764
- case "RSA-OAEP-512": return "RSA-OAEP";
765
- default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
766
- }
767
- };
768
- async function encrypt(alg, key, cek) {
769
- checkEncCryptoKey(key, alg, "encrypt");
770
- checkKeyLength(alg, key);
771
- return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
772
- }
773
- async function decrypt(alg, key, encryptedKey) {
774
- checkEncCryptoKey(key, alg, "decrypt");
775
- checkKeyLength(alg, key);
776
- return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
447
+ if (!isObject(parsed)) throw new ErrorClass(message);
448
+ return parsed;
777
449
  }
778
450
  //#endregion
779
451
  //#region node_modules/jose/dist/webapi/lib/jwk_to_key.js
780
- const unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value";
781
- function subtleMapping(jwk) {
782
- let algorithm;
783
- let keyUsages;
784
- switch (jwk.kty) {
785
- case "AKP":
786
- switch (jwk.alg) {
787
- case "ML-DSA-44":
788
- case "ML-DSA-65":
789
- case "ML-DSA-87":
790
- algorithm = { name: jwk.alg };
791
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
792
- break;
793
- default: throw new JOSENotSupported(unsupportedAlg);
794
- }
795
- break;
796
- case "RSA":
797
- switch (jwk.alg) {
798
- case "PS256":
799
- case "PS384":
800
- case "PS512":
801
- algorithm = {
802
- name: "RSA-PSS",
803
- hash: `SHA-${jwk.alg.slice(-3)}`
804
- };
805
- keyUsages = jwk.d ? ["sign"] : ["verify"];
806
- break;
807
- case "RS256":
808
- case "RS384":
809
- case "RS512":
810
- algorithm = {
811
- name: "RSASSA-PKCS1-v1_5",
812
- hash: `SHA-${jwk.alg.slice(-3)}`
813
- };
814
- keyUsages = jwk.d ? ["sign"] : ["verify"];
815
- break;
816
- case "RSA-OAEP":
817
- case "RSA-OAEP-256":
818
- case "RSA-OAEP-384":
819
- case "RSA-OAEP-512":
820
- algorithm = {
821
- name: "RSA-OAEP",
822
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
823
- };
824
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
825
- break;
826
- default: throw new JOSENotSupported(unsupportedAlg);
827
- }
828
- break;
829
- case "EC":
830
- switch (jwk.alg) {
831
- case "ES256":
832
- case "ES384":
833
- case "ES512":
834
- algorithm = {
835
- name: "ECDSA",
836
- namedCurve: {
837
- ES256: "P-256",
838
- ES384: "P-384",
839
- ES512: "P-521"
840
- }[jwk.alg]
841
- };
842
- keyUsages = jwk.d ? ["sign"] : ["verify"];
843
- break;
844
- case "ECDH-ES":
845
- case "ECDH-ES+A128KW":
846
- case "ECDH-ES+A192KW":
847
- case "ECDH-ES+A256KW":
848
- algorithm = {
849
- name: "ECDH",
850
- namedCurve: jwk.crv
851
- };
852
- keyUsages = jwk.d ? ["deriveBits"] : [];
853
- break;
854
- default: throw new JOSENotSupported(unsupportedAlg);
855
- }
856
- break;
857
- case "OKP":
858
- switch (jwk.alg) {
859
- case "Ed25519":
860
- case "EdDSA":
861
- algorithm = { name: "Ed25519" };
862
- keyUsages = jwk.d ? ["sign"] : ["verify"];
863
- break;
864
- case "ECDH-ES":
865
- case "ECDH-ES+A128KW":
866
- case "ECDH-ES+A192KW":
867
- case "ECDH-ES+A256KW":
868
- algorithm = { name: jwk.crv };
869
- keyUsages = jwk.d ? ["deriveBits"] : [];
870
- break;
871
- default: throw new JOSENotSupported(unsupportedAlg);
872
- }
873
- break;
874
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
875
- }
876
- return {
877
- algorithm,
878
- keyUsages
879
- };
880
- }
881
- async function jwkToKey(jwk) {
882
- if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
883
- const { algorithm, keyUsages } = subtleMapping(jwk);
452
+ async function jwkToKey(entry, jwk) {
453
+ if (jwk.kty === "RSA" && "oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
454
+ if (!entry.kty.includes(jwk.kty)) throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
455
+ const algorithm = entry.resolve?.({
456
+ kty: jwk.kty,
457
+ crv: jwk.crv
458
+ }) ?? entry.subtle;
459
+ const isPrivate = !!(jwk.d || jwk.priv);
884
460
  const keyData = { ...jwk };
885
461
  if (keyData.kty !== "AKP") delete keyData.alg;
886
462
  delete keyData.use;
887
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
463
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
888
464
  }
889
465
  //#endregion
890
- //#region node_modules/jose/dist/webapi/lib/normalize_key.js
891
- const unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
892
- let cache;
893
- const handleJWK = async (key, jwk, alg, freeze = false) => {
894
- cache ||= /* @__PURE__ */ new WeakMap();
895
- let cached = cache.get(key);
896
- if (cached?.[alg]) return cached[alg];
897
- const cryptoKey = await jwkToKey({
898
- ...jwk,
899
- alg
900
- });
901
- if (freeze) Object.freeze(key);
902
- if (!cached) cache.set(key, { [alg]: cryptoKey });
903
- else cached[alg] = cryptoKey;
904
- return cryptoKey;
905
- };
906
- const handleKeyObject = (keyObject, alg) => {
907
- cache ||= /* @__PURE__ */ new WeakMap();
908
- let cached = cache.get(keyObject);
909
- if (cached?.[alg]) return cached[alg];
910
- const isPublic = keyObject.type === "public";
911
- const extractable = isPublic ? true : false;
912
- let cryptoKey;
913
- if (keyObject.asymmetricKeyType === "x25519") {
914
- switch (alg) {
915
- case "ECDH-ES":
916
- case "ECDH-ES+A128KW":
917
- case "ECDH-ES+A192KW":
918
- case "ECDH-ES+A256KW": break;
919
- default: throw new TypeError(unusableForAlg);
920
- }
921
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
922
- }
923
- if (keyObject.asymmetricKeyType === "ed25519") {
924
- if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg);
925
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
926
- }
927
- switch (keyObject.asymmetricKeyType) {
928
- case "ml-dsa-44":
929
- case "ml-dsa-65":
930
- case "ml-dsa-87":
931
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg);
932
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
933
- }
934
- if (keyObject.asymmetricKeyType === "rsa") {
935
- let hash;
936
- switch (alg) {
937
- case "RSA-OAEP":
938
- hash = "SHA-1";
939
- break;
940
- case "RS256":
941
- case "PS256":
942
- case "RSA-OAEP-256":
943
- hash = "SHA-256";
944
- break;
945
- case "RS384":
946
- case "PS384":
947
- case "RSA-OAEP-384":
948
- hash = "SHA-384";
949
- break;
950
- case "RS512":
951
- case "PS512":
952
- case "RSA-OAEP-512":
953
- hash = "SHA-512";
954
- break;
955
- default: throw new TypeError(unusableForAlg);
956
- }
957
- if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
958
- name: "RSA-OAEP",
959
- hash
960
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
961
- cryptoKey = keyObject.toCryptoKey({
962
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
963
- hash
964
- }, extractable, [isPublic ? "verify" : "sign"]);
965
- }
966
- if (keyObject.asymmetricKeyType === "ec") {
967
- const namedCurve = (/* @__PURE__ */ new Map([
968
- ["prime256v1", "P-256"],
969
- ["secp384r1", "P-384"],
970
- ["secp521r1", "P-521"]
971
- ])).get(keyObject.asymmetricKeyDetails?.namedCurve);
972
- if (!namedCurve) throw new TypeError(unusableForAlg);
973
- const expectedCurve = {
974
- ES256: "P-256",
975
- ES384: "P-384",
976
- ES512: "P-521"
977
- };
978
- if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({
979
- name: "ECDSA",
980
- namedCurve
981
- }, extractable, [isPublic ? "verify" : "sign"]);
982
- if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
983
- name: "ECDH",
984
- namedCurve
985
- }, extractable, isPublic ? [] : ["deriveBits"]);
986
- }
987
- if (!cryptoKey) throw new TypeError(unusableForAlg);
988
- if (!cached) cache.set(keyObject, { [alg]: cryptoKey });
989
- else cached[alg] = cryptoKey;
990
- return cryptoKey;
991
- };
992
- async function normalizeKey(key, alg) {
993
- if (key instanceof Uint8Array) return key;
994
- if (isCryptoKey(key)) return key;
995
- if (isKeyObject(key)) {
996
- if (key.type === "secret") return key.export();
997
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try {
998
- return handleKeyObject(key, alg);
999
- } catch (err) {
1000
- if (err instanceof TypeError) throw err;
1001
- }
1002
- let jwk = key.export({ format: "jwk" });
1003
- return handleJWK(key, jwk, alg);
466
+ //#region node_modules/jose/dist/webapi/lib/key.js
467
+ const tag = (key) => key[Symbol.toStringTag];
468
+ const jwkMatchesOp = (entry, key, usage) => {
469
+ const { alg } = entry;
470
+ if (key.use !== void 0) {
471
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
472
+ if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
473
+ }
474
+ if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
475
+ if (Array.isArray(key.key_ops)) {
476
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
477
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
1004
478
  }
479
+ };
480
+ function checkKeyType(entry, key, usage) {
481
+ const { alg, secret } = entry;
482
+ const privateKey = usage === "decrypt" || usage === "sign";
483
+ if (secret && key instanceof Uint8Array) return [BYTES, key];
1005
484
  if (isJWK(key)) {
1006
- if (key.k) return decode(key.k);
1007
- return handleJWK(key, key, alg, true);
485
+ if (secret ? !isSecretJWK(key) : !(privateKey ? isPrivateJWK(key) : isPublicJWK(key))) throw new TypeError(secret ? `JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present` : `JSON Web Key for this operation must be a ${privateKey ? "private" : "public"} JWK`);
486
+ jwkMatchesOp(entry, key, usage);
487
+ return [JWK, key];
488
+ }
489
+ if (!isKeyLike(key)) throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
490
+ if (secret) {
491
+ if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
492
+ } else {
493
+ if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
494
+ const expectedType = privateKey ? "private" : "public";
495
+ if ((key.type === "public" || key.type === "private") && key.type !== expectedType) {
496
+ const operation = usage === "sign" ? "signing" : usage === "verify" ? "verifying" : `${usage.slice(0, -1)}tion`;
497
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm ${operation} must be of type "${expectedType}"`);
498
+ }
1008
499
  }
1009
- throw new Error("unreachable");
500
+ return isCryptoKey(key) ? [CRYPTO, key] : [KEYOBJECT, key];
1010
501
  }
1011
- //#endregion
1012
- //#region node_modules/jose/dist/webapi/lib/asn1.js
1013
- const formatPEM = (b64, descriptor) => {
1014
- return `-----BEGIN ${descriptor}-----\n${(b64.match(/.{1,64}/g) || []).join("\n")}\n-----END ${descriptor}-----`;
502
+ const BYTES = 0;
503
+ const CRYPTO = 1;
504
+ const KEYOBJECT = 2;
505
+ const JWK = 3;
506
+ let cache;
507
+ const nist = {
508
+ __proto__: null,
509
+ prime256v1: "P-256",
510
+ secp384r1: "P-384",
511
+ secp521r1: "P-521"
1015
512
  };
1016
- const genericExport = async (keyType, keyFormat, key) => {
1017
- if (isKeyObject(key)) {
1018
- if (key.type !== keyType) throw new TypeError(`key is not a ${keyType} key`);
1019
- return key.export({
1020
- format: "pem",
1021
- type: keyFormat
513
+ function cached(key, alg, value) {
514
+ cache ||= /* @__PURE__ */ new WeakMap();
515
+ const entry = cache.get(key);
516
+ if (value) {
517
+ if (entry) entry[alg] = value;
518
+ else cache.set(key, {
519
+ __proto__: null,
520
+ [alg]: value
1022
521
  });
1023
522
  }
1024
- if (!isCryptoKey(key)) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject"));
1025
- if (!key.extractable) throw new TypeError("CryptoKey is not extractable");
1026
- if (key.type !== keyType) throw new TypeError(`key is not a ${keyType} key`);
1027
- return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
1028
- };
1029
- const toSPKI = (key) => genericExport("public", "spki", key);
1030
- const toPKCS8 = (key) => genericExport("private", "pkcs8", key);
1031
- const bytesEqual = (a, b) => {
1032
- if (a.byteLength !== b.length) return false;
1033
- for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false;
1034
- return true;
523
+ return value ?? entry?.[alg];
524
+ }
525
+ const handleJWK = async (key, jwk, entry) => cached(key, entry.alg) ?? cached(key, entry.alg, await jwkToKey(entry, {
526
+ ...jwk,
527
+ alg: entry.alg
528
+ }));
529
+ const handleKeyObject = (keyObject, entry) => {
530
+ const hit = cached(keyObject, entry.alg);
531
+ if (hit) return hit;
532
+ const isPublic = keyObject.type === "public";
533
+ const usages = entry.usages[isPublic ? 0 : 1];
534
+ const { asymmetricKeyType } = keyObject;
535
+ const crv = nist[keyObject.asymmetricKeyDetails?.namedCurve];
536
+ const params = entry.resolve?.({
537
+ crv,
538
+ asymmetricKeyType
539
+ }) ?? entry.subtle;
540
+ return cached(keyObject, entry.alg, keyObject.toCryptoKey(params, isPublic, usages));
1035
541
  };
1036
- const createASN1State = (data) => ({
1037
- data,
1038
- pos: 0
1039
- });
1040
- const parseLength = (state) => {
1041
- const first = state.data[state.pos++];
1042
- if (first & 128) {
1043
- const lengthOfLen = first & 127;
1044
- let length = 0;
1045
- for (let i = 0; i < lengthOfLen; i++) length = length << 8 | state.data[state.pos++];
1046
- return length;
542
+ async function prepareKey(entry, key, usage) {
543
+ const tagged = checkKeyType(entry, key, usage);
544
+ switch (tagged[0]) {
545
+ case BYTES:
546
+ case CRYPTO: return tagged[1];
547
+ case JWK: {
548
+ const key = tagged[1];
549
+ if (key.k) return decode(key.k);
550
+ if (!Object.isFrozen(key)) {
551
+ const { key_ops } = key;
552
+ if (Array.isArray(key_ops)) Object.freeze(key_ops);
553
+ Object.freeze(key);
554
+ }
555
+ return handleJWK(key, key, entry);
556
+ }
557
+ case KEYOBJECT: {
558
+ const keyObject = tagged[1];
559
+ if (keyObject.type === "secret") return keyObject.export();
560
+ if ("toCryptoKey" in keyObject && typeof keyObject.toCryptoKey === "function") return handleKeyObject(keyObject, entry);
561
+ return handleJWK(keyObject, keyObject.export({ format: "jwk" }), entry);
562
+ }
1047
563
  }
1048
- return first;
1049
- };
1050
- const skipElement = (state, count = 1) => {
1051
- if (count <= 0) return;
1052
- state.pos++;
1053
- const length = parseLength(state);
1054
- state.pos += length;
1055
- if (count > 1) skipElement(state, count - 1);
1056
- };
1057
- const expectTag = (state, expectedTag, errorMessage) => {
1058
- if (state.data[state.pos++] !== expectedTag) throw new Error(errorMessage);
1059
- };
1060
- const getSubarray = (state, length) => {
1061
- const result = state.data.subarray(state.pos, state.pos + length);
1062
- state.pos += length;
1063
- return result;
1064
- };
1065
- const parseAlgorithmOID = (state) => {
1066
- expectTag(state, 6, "Expected algorithm OID");
1067
- const oidLen = parseLength(state);
1068
- return getSubarray(state, oidLen);
1069
- };
1070
- function parsePKCS8Header(state) {
1071
- expectTag(state, 48, "Invalid PKCS#8 structure");
1072
- parseLength(state);
1073
- expectTag(state, 2, "Expected version field");
1074
- const verLen = parseLength(state);
1075
- state.pos += verLen;
1076
- expectTag(state, 48, "Expected algorithm identifier");
1077
- const algIdLen = parseLength(state);
1078
- return {
1079
- algIdStart: state.pos,
1080
- algIdLength: algIdLen
564
+ }
565
+ //#endregion
566
+ //#region node_modules/jose/dist/webapi/lib/key_descriptor.js
567
+ function table(entries) {
568
+ const out = { __proto__: null };
569
+ for (const alg in entries) out[alg] = {
570
+ ...entries[alg],
571
+ alg
1081
572
  };
573
+ return out;
1082
574
  }
1083
- function parseSPKIHeader(state) {
1084
- expectTag(state, 48, "Invalid SPKI structure");
1085
- parseLength(state);
1086
- expectTag(state, 48, "Expected algorithm identifier");
1087
- const algIdLen = parseLength(state);
575
+ //#endregion
576
+ //#region node_modules/jose/dist/webapi/lib/jwe_algorithms.js
577
+ const wrap = [["encrypt", "wrapKey"], ["decrypt", "unwrapKey"]];
578
+ const derive = [[], ["deriveBits"]];
579
+ const none = [[], []];
580
+ function rsaes(bits) {
1088
581
  return {
1089
- algIdStart: state.pos,
1090
- algIdLength: algIdLen
582
+ kty: ["RSA"],
583
+ subtle: {
584
+ name: "RSA-OAEP",
585
+ hash: `SHA-${bits}`
586
+ },
587
+ usages: wrap,
588
+ ops: ["wrapKey", "unwrapKey"]
1091
589
  };
1092
590
  }
1093
- const parseECAlgorithmIdentifier = (state) => {
1094
- const algOid = parseAlgorithmOID(state);
1095
- if (bytesEqual(algOid, [
1096
- 43,
1097
- 101,
1098
- 110
1099
- ])) return "X25519";
1100
- if (!bytesEqual(algOid, [
1101
- 42,
1102
- 134,
1103
- 72,
1104
- 206,
1105
- 61,
1106
- 2,
1107
- 1
1108
- ])) throw new Error("Unsupported key algorithm");
1109
- expectTag(state, 6, "Expected curve OID");
1110
- const curveOidLen = parseLength(state);
1111
- const curveOid = getSubarray(state, curveOidLen);
1112
- for (const { name, oid } of [
1113
- {
1114
- name: "P-256",
1115
- oid: [
1116
- 42,
1117
- 134,
1118
- 72,
1119
- 206,
1120
- 61,
1121
- 3,
1122
- 1,
1123
- 7
1124
- ]
591
+ function ecdh() {
592
+ return {
593
+ kty: ["EC", "OKP"],
594
+ subtle: { name: "ECDH" },
595
+ resolve: ({ kty, crv, asymmetricKeyType }) => {
596
+ if (crv === "X25519" || asymmetricKeyType === "x25519") return { name: "X25519" };
597
+ if (kty === "OKP") throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
598
+ return {
599
+ name: "ECDH",
600
+ namedCurve: crv
601
+ };
1125
602
  },
1126
- {
1127
- name: "P-384",
1128
- oid: [
1129
- 43,
1130
- 129,
1131
- 4,
1132
- 0,
1133
- 34
1134
- ]
603
+ usages: derive,
604
+ ops: [void 0, "deriveBits"]
605
+ };
606
+ }
607
+ function aeskw(bits, gcm = false) {
608
+ return {
609
+ kty: ["oct"],
610
+ secret: true,
611
+ subtle: {
612
+ name: gcm ? "AES-GCM" : "AES-KW",
613
+ length: bits
1135
614
  },
1136
- {
1137
- name: "P-521",
1138
- oid: [
1139
- 43,
1140
- 129,
1141
- 4,
1142
- 0,
1143
- 35
1144
- ]
1145
- }
1146
- ]) if (bytesEqual(curveOid, oid)) return name;
1147
- throw new Error("Unsupported named curve");
1148
- };
1149
- const genericImport = async (keyFormat, keyData, alg, options) => {
1150
- let algorithm;
1151
- let keyUsages;
1152
- const isPublic = keyFormat === "spki";
1153
- const getSigUsages = () => isPublic ? ["verify"] : ["sign"];
1154
- const getEncUsages = () => isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
1155
- switch (alg) {
1156
- case "PS256":
1157
- case "PS384":
1158
- case "PS512":
1159
- algorithm = {
1160
- name: "RSA-PSS",
1161
- hash: `SHA-${alg.slice(-3)}`
1162
- };
1163
- keyUsages = getSigUsages();
1164
- break;
1165
- case "RS256":
1166
- case "RS384":
1167
- case "RS512":
1168
- algorithm = {
1169
- name: "RSASSA-PKCS1-v1_5",
1170
- hash: `SHA-${alg.slice(-3)}`
1171
- };
1172
- keyUsages = getSigUsages();
1173
- break;
1174
- case "RSA-OAEP":
1175
- case "RSA-OAEP-256":
1176
- case "RSA-OAEP-384":
1177
- case "RSA-OAEP-512":
1178
- algorithm = {
1179
- name: "RSA-OAEP",
1180
- hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
1181
- };
1182
- keyUsages = getEncUsages();
1183
- break;
1184
- case "ES256":
1185
- case "ES384":
1186
- case "ES512":
1187
- algorithm = {
1188
- name: "ECDSA",
1189
- namedCurve: {
1190
- ES256: "P-256",
1191
- ES384: "P-384",
1192
- ES512: "P-521"
1193
- }[alg]
1194
- };
1195
- keyUsages = getSigUsages();
1196
- break;
1197
- case "ECDH-ES":
1198
- case "ECDH-ES+A128KW":
1199
- case "ECDH-ES+A192KW":
1200
- case "ECDH-ES+A256KW":
1201
- try {
1202
- const namedCurve = options.getNamedCurve(keyData);
1203
- algorithm = namedCurve === "X25519" ? { name: "X25519" } : {
1204
- name: "ECDH",
1205
- namedCurve
1206
- };
1207
- } catch (cause) {
1208
- throw new JOSENotSupported("Invalid or unsupported key format");
1209
- }
1210
- keyUsages = isPublic ? [] : ["deriveBits"];
1211
- break;
1212
- case "Ed25519":
1213
- case "EdDSA":
1214
- algorithm = { name: "Ed25519" };
1215
- keyUsages = getSigUsages();
1216
- break;
1217
- case "ML-DSA-44":
1218
- case "ML-DSA-65":
1219
- case "ML-DSA-87":
1220
- algorithm = { name: alg };
1221
- keyUsages = getSigUsages();
1222
- break;
1223
- default: throw new JOSENotSupported("Invalid or unsupported \"alg\" (Algorithm) value");
1224
- }
1225
- return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
1226
- };
1227
- const processPEMData = (pem, pattern) => {
1228
- return decodeBase64(pem.replace(pattern, ""));
1229
- };
1230
- const fromPKCS8 = (pem, alg, options) => {
1231
- const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
1232
- let opts = options;
1233
- if (alg?.startsWith?.("ECDH-ES")) {
1234
- opts ||= {};
1235
- opts.getNamedCurve = (keyData) => {
1236
- const state = createASN1State(keyData);
1237
- parsePKCS8Header(state);
1238
- return parseECAlgorithmIdentifier(state);
1239
- };
1240
- }
1241
- return genericImport("pkcs8", keyData, alg, opts);
1242
- };
1243
- const fromSPKI = (pem, alg, options) => {
1244
- const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);
1245
- let opts = options;
1246
- if (alg?.startsWith?.("ECDH-ES")) {
1247
- opts ||= {};
1248
- opts.getNamedCurve = (keyData) => {
1249
- const state = createASN1State(keyData);
1250
- parseSPKIHeader(state);
1251
- return parseECAlgorithmIdentifier(state);
1252
- };
1253
- }
1254
- return genericImport("spki", keyData, alg, opts);
1255
- };
1256
- function spkiFromX509(buf) {
1257
- const state = createASN1State(buf);
1258
- expectTag(state, 48, "Invalid certificate structure");
1259
- parseLength(state);
1260
- expectTag(state, 48, "Invalid tbsCertificate structure");
1261
- parseLength(state);
1262
- if (buf[state.pos] === 160) skipElement(state, 6);
1263
- else skipElement(state, 5);
1264
- const spkiStart = state.pos;
1265
- expectTag(state, 48, "Invalid SPKI structure");
1266
- const spkiContentLen = parseLength(state);
1267
- return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));
615
+ usages: none,
616
+ ops: gcm ? ["encrypt", "decrypt"] : ["wrapKey", "unwrapKey"]
617
+ };
1268
618
  }
1269
- function extractX509SPKI(x509) {
1270
- return spkiFromX509(processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g));
619
+ function pbes2() {
620
+ return {
621
+ kty: ["oct"],
622
+ secret: true,
623
+ subtle: { name: "PBKDF2" },
624
+ usages: none,
625
+ ops: ["deriveBits", "deriveBits"]
626
+ };
1271
627
  }
1272
- const fromX509 = (pem, alg, options) => {
1273
- let spki;
1274
- try {
1275
- spki = extractX509SPKI(pem);
1276
- } catch (cause) {
1277
- throw new TypeError("Failed to parse the X.509 certificate", { cause });
1278
- }
1279
- return fromSPKI(formatPEM(encodeBase64(spki), "PUBLIC KEY"), alg, options);
1280
- };
1281
- //#endregion
1282
- //#region node_modules/jose/dist/webapi/key/import.js
1283
- async function importSPKI(spki, alg, options) {
1284
- if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) throw new TypeError("\"spki\" must be SPKI formatted string");
1285
- return fromSPKI(spki, alg, options);
628
+ const JWE = table({
629
+ dir: {
630
+ kty: ["oct"],
631
+ secret: true,
632
+ subtle: { name: "AES-GCM" },
633
+ usages: none,
634
+ ops: ["encrypt", "decrypt"]
635
+ },
636
+ "RSA-OAEP": rsaes(1),
637
+ "RSA-OAEP-256": rsaes(256),
638
+ "RSA-OAEP-384": rsaes(384),
639
+ "RSA-OAEP-512": rsaes(512),
640
+ "ECDH-ES": ecdh(),
641
+ "ECDH-ES+A128KW": ecdh(),
642
+ "ECDH-ES+A192KW": ecdh(),
643
+ "ECDH-ES+A256KW": ecdh(),
644
+ A128KW: aeskw(128),
645
+ A192KW: aeskw(192),
646
+ A256KW: aeskw(256),
647
+ A128GCMKW: aeskw(128, true),
648
+ A192GCMKW: aeskw(192, true),
649
+ A256GCMKW: aeskw(256, true),
650
+ "PBES2-HS256+A128KW": pbes2(),
651
+ "PBES2-HS384+A192KW": pbes2(),
652
+ "PBES2-HS512+A256KW": pbes2()
653
+ });
654
+ const contentOps = ["encrypt", "decrypt"];
655
+ function contentEncryption(bits, cbc = false) {
656
+ return {
657
+ kty: ["oct"],
658
+ secret: true,
659
+ subtle: {
660
+ name: cbc ? "AES-CBC" : "AES-GCM",
661
+ length: bits
662
+ },
663
+ usages: none,
664
+ ops: contentOps,
665
+ cekBits: bits,
666
+ ivBits: cbc ? 128 : 96,
667
+ cbc
668
+ };
1286
669
  }
1287
- async function importX509(x509, alg, options) {
1288
- if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) throw new TypeError("\"x509\" must be X.509 formatted string");
1289
- return fromX509(x509, alg, options);
670
+ const ENC = table({
671
+ A128GCM: contentEncryption(128),
672
+ A192GCM: contentEncryption(192),
673
+ A256GCM: contentEncryption(256),
674
+ "A128CBC-HS256": contentEncryption(256, true),
675
+ "A192CBC-HS384": contentEncryption(384, true),
676
+ "A256CBC-HS512": contentEncryption(512, true)
677
+ });
678
+ function unsupported(parameter, name) {
679
+ throw new JOSENotSupported(`Invalid or unsupported "${parameter}" (JWE ${name}) header value`);
1290
680
  }
1291
- async function importPKCS8(pkcs8, alg, options) {
1292
- if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) throw new TypeError("\"pkcs8\" must be PKCS#8 formatted string");
1293
- return fromPKCS8(pkcs8, alg, options);
681
+ function jweAlgorithm(alg) {
682
+ return (typeof alg === "string" ? JWE[alg] : void 0) ?? unsupported("alg", "Algorithm");
1294
683
  }
1295
- async function importJWK(jwk, alg, options) {
1296
- if (!isObject(jwk)) throw new TypeError("JWK must be an object");
1297
- let ext;
1298
- alg ??= jwk.alg;
1299
- ext ??= options?.extractable ?? jwk.ext;
1300
- switch (jwk.kty) {
1301
- case "oct":
1302
- if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
1303
- return decode(jwk.k);
1304
- case "RSA":
1305
- if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
1306
- return jwkToKey({
1307
- ...jwk,
1308
- alg,
1309
- ext
1310
- });
1311
- case "AKP":
1312
- if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
1313
- if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch");
1314
- return jwkToKey({
1315
- ...jwk,
1316
- ext
1317
- });
1318
- case "EC":
1319
- case "OKP": return jwkToKey({
1320
- ...jwk,
1321
- alg,
1322
- ext
1323
- });
1324
- default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
1325
- }
684
+ function jweEncryption(enc) {
685
+ return (typeof enc === "string" ? ENC[enc] : void 0) ?? unsupported("enc", "Encryption Algorithm");
1326
686
  }
1327
687
  //#endregion
1328
- //#region node_modules/jose/dist/webapi/lib/key_to_jwk.js
1329
- async function keyToJWK(key) {
1330
- if (isKeyObject(key)) if (key.type === "secret") key = key.export();
1331
- else return key.export({ format: "jwk" });
1332
- if (key instanceof Uint8Array) return {
1333
- kty: "oct",
1334
- k: encode(key)
1335
- };
1336
- if (!isCryptoKey(key)) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
1337
- if (!key.extractable) throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
1338
- const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
1339
- if (jwk.kty === "AKP") jwk.alg = alg;
1340
- return jwk;
688
+ //#region node_modules/jose/dist/webapi/lib/key_management.js
689
+ function checkEcdhCryptoKey(key, usage) {
690
+ if (key.algorithm.name !== "ECDH" && key.algorithm.name !== "X25519") throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");
691
+ checkUsage(key, usage);
1341
692
  }
1342
- //#endregion
1343
- //#region node_modules/jose/dist/webapi/key/export.js
1344
- async function exportSPKI(key) {
1345
- return toSPKI(key);
693
+ async function aeskwCryptoKey(key, alg, usage) {
694
+ const expected = jweAlgorithm(alg).subtle;
695
+ const cryptoKey = key instanceof Uint8Array ? await crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]) : key;
696
+ checkCryptoKey(cryptoKey, expected, usage);
697
+ return cryptoKey;
698
+ }
699
+ async function aeskwWrap(alg, key, cek) {
700
+ const cryptoKey = await aeskwCryptoKey(key, alg, "wrapKey");
701
+ const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, {
702
+ hash: "SHA-256",
703
+ name: "HMAC"
704
+ }, true, ["sign"]);
705
+ return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
706
+ }
707
+ async function aeskwUnwrap(alg, key, encryptedKey) {
708
+ const cryptoKey = await aeskwCryptoKey(key, alg, "unwrapKey");
709
+ const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", {
710
+ hash: "SHA-256",
711
+ name: "HMAC"
712
+ }, true, ["sign"]);
713
+ return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
1346
714
  }
1347
- async function exportPKCS8(key) {
1348
- return toPKCS8(key);
715
+ function checkRsaKey(alg, key, usage) {
716
+ checkCryptoKey(key, jweAlgorithm(alg).subtle, usage);
717
+ checkModulusLength(alg, key);
1349
718
  }
1350
- async function exportJWK(key) {
1351
- return keyToJWK(key);
719
+ function pbes2CryptoKey(key, alg) {
720
+ if (key instanceof Uint8Array) return crypto.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]);
721
+ checkCryptoKey(key, jweAlgorithm(alg).subtle, "deriveBits");
722
+ return key;
1352
723
  }
1353
- //#endregion
1354
- //#region node_modules/jose/dist/webapi/lib/aesgcmkw.js
1355
- async function wrap(alg, key, cek, iv) {
1356
- const wrapped = await encrypt$1(alg.slice(0, 7), cek, key, iv, /* @__PURE__ */ new Uint8Array());
1357
- return {
1358
- encryptedKey: wrapped.ciphertext,
1359
- iv: encode(wrapped.iv),
1360
- tag: encode(wrapped.tag)
724
+ async function deriveKey(p2s, alg, p2c, key) {
725
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
726
+ if (!Number.isSafeInteger(p2c) || Math.sign(p2c) !== 1) throw new JWEInvalid("PBES2 Count Input must be a positive integer");
727
+ const salt = concat(encode$1(alg), Uint8Array.of(0), p2s);
728
+ const keylen = parseInt(alg.slice(13, 16), 10);
729
+ const subtleAlg = {
730
+ hash: `SHA-${alg.slice(8, 11)}`,
731
+ iterations: p2c,
732
+ name: "PBKDF2",
733
+ salt
1361
734
  };
735
+ const cryptoKey = await pbes2CryptoKey(key, alg);
736
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
1362
737
  }
1363
- async function unwrap(alg, key, encryptedKey, iv, tag) {
1364
- return decrypt$1(alg.slice(0, 7), key, encryptedKey, iv, tag, /* @__PURE__ */ new Uint8Array());
738
+ function lengthAndInput(input) {
739
+ return concat(uint32be(input.length), input);
740
+ }
741
+ async function concatKdf(Z, L, OtherInfo) {
742
+ const dkLen = L >> 3;
743
+ const hashLen = 32;
744
+ const reps = Math.ceil(dkLen / hashLen);
745
+ const dk = new Uint8Array(reps * hashLen);
746
+ for (let i = 1; i <= reps; i++) {
747
+ const hashResult = await digest("sha256", concat(uint32be(i), Z, OtherInfo));
748
+ dk.set(hashResult, (i - 1) * hashLen);
749
+ }
750
+ return dk.slice(0, dkLen);
751
+ }
752
+ async function ecdhesDeriveKey(publicKey, privateKey, algorithm, keyLength, apu = /* @__PURE__ */ new Uint8Array(), apv = /* @__PURE__ */ new Uint8Array()) {
753
+ checkEcdhCryptoKey(publicKey);
754
+ checkEcdhCryptoKey(privateKey, "deriveBits");
755
+ const otherInfo = concat(lengthAndInput(encode$1(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
756
+ return concatKdf(new Uint8Array(await crypto.subtle.deriveBits({
757
+ name: publicKey.algorithm.name,
758
+ public: publicKey
759
+ }, privateKey, publicKey.algorithm.name === "X25519" ? 256 : Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3)), keyLength, otherInfo);
760
+ }
761
+ function assertEcdhKey(key) {
762
+ assertCryptoKey(key);
763
+ const curve = key.algorithm.namedCurve;
764
+ if (curve !== "P-256" && curve !== "P-384" && curve !== "P-521" && key.algorithm.name !== "X25519") throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
1365
765
  }
1366
- //#endregion
1367
- //#region node_modules/jose/dist/webapi/lib/key_management.js
1368
- const unsupportedAlgHeader = "Invalid or unsupported \"alg\" (JWE Algorithm) header value";
1369
766
  function assertEncryptedKey(encryptedKey) {
1370
767
  if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing");
1371
768
  }
1372
- async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
1373
- switch (alg) {
1374
- case "dir":
1375
- if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
1376
- return key;
1377
- case "ECDH-ES": if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
1378
- case "ECDH-ES+A128KW":
1379
- case "ECDH-ES+A192KW":
1380
- case "ECDH-ES+A256KW": {
769
+ function assertNoEncryptedKey(encryptedKey) {
770
+ if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
771
+ }
772
+ async function decryptKeyManagement(alg, enc, key, encryptedKey, joseHeader, options) {
773
+ const entry = jweAlgorithm(alg);
774
+ if (alg === "dir") {
775
+ assertNoEncryptedKey(encryptedKey);
776
+ return key;
777
+ }
778
+ switch (entry.subtle.name) {
779
+ case "ECDH": {
780
+ if (alg === "ECDH-ES") assertNoEncryptedKey(encryptedKey);
1381
781
  if (!isObject(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
1382
- assertCryptoKey(key);
1383
- if (!allowed(key)) throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
1384
- const epk = await importJWK(joseHeader.epk, alg);
1385
- assertCryptoKey(epk);
782
+ assertEcdhKey(key);
783
+ const epk = await jwkToKey(entry, joseHeader.epk);
1386
784
  let partyUInfo;
1387
785
  let partyVInfo;
1388
786
  if (joseHeader.apu !== void 0) {
@@ -1393,38 +791,29 @@ async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options)
1393
791
  if (typeof joseHeader.apv !== "string") throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
1394
792
  partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid);
1395
793
  }
1396
- const sharedSecret = await deriveKey$1(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
794
+ const sharedSecret = await ecdhesDeriveKey(epk, key, alg === "ECDH-ES" ? enc.alg : alg, alg === "ECDH-ES" ? enc.cekBits : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
1397
795
  if (alg === "ECDH-ES") return sharedSecret;
1398
796
  assertEncryptedKey(encryptedKey);
1399
- return unwrap$2(alg.slice(-6), sharedSecret, encryptedKey);
797
+ return aeskwUnwrap(alg.slice(-6), sharedSecret, encryptedKey);
1400
798
  }
1401
799
  case "RSA-OAEP":
1402
- case "RSA-OAEP-256":
1403
- case "RSA-OAEP-384":
1404
- case "RSA-OAEP-512":
1405
800
  assertEncryptedKey(encryptedKey);
1406
801
  assertCryptoKey(key);
1407
- return decrypt(alg, key, encryptedKey);
1408
- case "PBES2-HS256+A128KW":
1409
- case "PBES2-HS384+A192KW":
1410
- case "PBES2-HS512+A256KW": {
802
+ checkRsaKey(alg, key, "decrypt");
803
+ return new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP", key, encryptedKey));
804
+ case "PBKDF2": {
1411
805
  assertEncryptedKey(encryptedKey);
1412
806
  if (typeof joseHeader.p2c !== "number") throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
1413
807
  const p2cLimit = options?.maxPBES2Count || 1e4;
1414
808
  if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
1415
809
  if (typeof joseHeader.p2s !== "string") throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
1416
- let p2s;
1417
- p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid);
1418
- return unwrap$1(alg, key, encryptedKey, joseHeader.p2c, p2s);
810
+ const derived = await deriveKey(decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid), alg, joseHeader.p2c, key);
811
+ return aeskwUnwrap(alg.slice(-6), derived, encryptedKey);
1419
812
  }
1420
- case "A128KW":
1421
- case "A192KW":
1422
- case "A256KW":
813
+ case "AES-KW":
1423
814
  assertEncryptedKey(encryptedKey);
1424
- return unwrap$2(alg, key, encryptedKey);
1425
- case "A128GCMKW":
1426
- case "A192GCMKW":
1427
- case "A256GCMKW": {
815
+ return aeskwUnwrap(alg, key, encryptedKey);
816
+ case "AES-GCM": {
1428
817
  assertEncryptedKey(encryptedKey);
1429
818
  if (typeof joseHeader.iv !== "string") throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
1430
819
  if (typeof joseHeader.tag !== "string") throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
@@ -1432,31 +821,35 @@ async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options)
1432
821
  iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid);
1433
822
  let tag;
1434
823
  tag = decodeBase64url(joseHeader.tag, "tag", JWEInvalid);
1435
- return unwrap(alg, key, encryptedKey, iv, tag);
824
+ return decrypt(jweEncryption(alg.slice(0, -2)), key, encryptedKey, iv, tag, /* @__PURE__ */ new Uint8Array());
1436
825
  }
1437
- default: throw new JOSENotSupported(unsupportedAlgHeader);
1438
826
  }
1439
827
  }
1440
828
  async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
1441
829
  let encryptedKey;
1442
830
  let parameters;
1443
831
  let cek;
1444
- switch (alg) {
1445
- case "dir":
1446
- cek = key;
1447
- break;
1448
- case "ECDH-ES":
1449
- case "ECDH-ES+A128KW":
1450
- case "ECDH-ES+A192KW":
1451
- case "ECDH-ES+A256KW": {
1452
- assertCryptoKey(key);
1453
- if (!allowed(key)) throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
832
+ const entry = jweAlgorithm(alg);
833
+ if (alg === "dir") return [
834
+ key,
835
+ void 0,
836
+ void 0
837
+ ];
838
+ switch (entry.subtle.name) {
839
+ case "ECDH": {
840
+ assertEcdhKey(key);
1454
841
  const { apu, apv } = providedParameters;
1455
842
  let ephemeralKey;
1456
- if (providedParameters.epk) ephemeralKey = await normalizeKey(providedParameters.epk, alg);
843
+ if (providedParameters.epk) ephemeralKey = await prepareKey(entry, providedParameters.epk, "decrypt");
1457
844
  else ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
1458
- const { x, y, crv, kty } = await exportJWK(ephemeralKey);
1459
- const sharedSecret = await deriveKey$1(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
845
+ const subtle = crypto.subtle;
846
+ let exportableEpk = ephemeralKey;
847
+ if (!exportableEpk.extractable) {
848
+ if (typeof subtle.getPublicKey !== "function") throw new TypeError("CryptoKey for \"epk\" must be extractable");
849
+ exportableEpk = await subtle.getPublicKey(ephemeralKey, []);
850
+ }
851
+ const { x, y, crv, kty } = await subtle.exportKey("jwk", exportableEpk);
852
+ const sharedSecret = await ecdhesDeriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc.alg : alg, alg === "ECDH-ES" ? enc.cekBits : parseInt(alg.slice(-5, -2), 10), apu, apv);
1460
853
  parameters = { epk: {
1461
854
  x,
1462
855
  crv,
@@ -1470,157 +863,79 @@ async function encryptKeyManagement(alg, enc, key, providedCek, providedParamete
1470
863
  break;
1471
864
  }
1472
865
  cek = providedCek || generateCek(enc);
1473
- encryptedKey = await wrap$2(alg.slice(-6), sharedSecret, cek);
866
+ encryptedKey = await aeskwWrap(alg.slice(-6), sharedSecret, cek);
1474
867
  break;
1475
868
  }
1476
869
  case "RSA-OAEP":
1477
- case "RSA-OAEP-256":
1478
- case "RSA-OAEP-384":
1479
- case "RSA-OAEP-512":
1480
870
  cek = providedCek || generateCek(enc);
1481
871
  assertCryptoKey(key);
1482
- encryptedKey = await encrypt(alg, key, cek);
872
+ checkRsaKey(alg, key, "encrypt");
873
+ encryptedKey = new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP", key, cek));
1483
874
  break;
1484
- case "PBES2-HS256+A128KW":
1485
- case "PBES2-HS384+A192KW":
1486
- case "PBES2-HS512+A256KW": {
875
+ case "PBKDF2": {
1487
876
  cek = providedCek || generateCek(enc);
1488
- const { p2c, p2s } = providedParameters;
1489
- ({encryptedKey, ...parameters} = await wrap$1(alg, key, cek, p2c, p2s));
877
+ const { p2c = 2048, p2s = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)) } = providedParameters;
878
+ const derived = await deriveKey(p2s, alg, p2c, key);
879
+ encryptedKey = await aeskwWrap(alg.slice(-6), derived, cek);
880
+ parameters = {
881
+ p2c,
882
+ p2s: encode(p2s)
883
+ };
1490
884
  break;
1491
885
  }
1492
- case "A128KW":
1493
- case "A192KW":
1494
- case "A256KW":
886
+ case "AES-KW":
1495
887
  cek = providedCek || generateCek(enc);
1496
- encryptedKey = await wrap$2(alg, key, cek);
888
+ encryptedKey = await aeskwWrap(alg, key, cek);
1497
889
  break;
1498
- case "A128GCMKW":
1499
- case "A192GCMKW":
1500
- case "A256GCMKW": {
890
+ case "AES-GCM": {
1501
891
  cek = providedCek || generateCek(enc);
1502
892
  const { iv } = providedParameters;
1503
- ({encryptedKey, ...parameters} = await wrap(alg, key, cek, iv));
893
+ const wrapped = await encrypt(jweEncryption(alg.slice(0, -2)), cek, key, iv, /* @__PURE__ */ new Uint8Array());
894
+ encryptedKey = wrapped.ciphertext;
895
+ parameters = {
896
+ iv: encode(wrapped.iv),
897
+ tag: encode(wrapped.tag)
898
+ };
1504
899
  break;
1505
900
  }
1506
- default: throw new JOSENotSupported(unsupportedAlgHeader);
1507
901
  }
1508
- return {
902
+ return [
1509
903
  cek,
1510
904
  encryptedKey,
1511
905
  parameters
1512
- };
1513
- }
1514
- //#endregion
1515
- //#region node_modules/jose/dist/webapi/lib/validate_crit.js
1516
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
1517
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
1518
- if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set();
1519
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
1520
- let recognized;
1521
- if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
1522
- else recognized = recognizedDefault;
1523
- for (const parameter of protectedHeader.crit) {
1524
- if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
1525
- if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
1526
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
1527
- }
1528
- return new Set(protectedHeader.crit);
906
+ ];
1529
907
  }
1530
908
  //#endregion
1531
- //#region node_modules/jose/dist/webapi/lib/validate_algorithms.js
909
+ //#region node_modules/jose/dist/webapi/lib/options.js
910
+ const JWS_RECOGNIZED = {
911
+ __proto__: null,
912
+ b64: true
913
+ };
914
+ const JWE_RECOGNIZED = { __proto__: null };
1532
915
  function validateAlgorithms(option, algorithms) {
1533
916
  if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
1534
917
  if (!algorithms) return;
1535
918
  return new Set(algorithms);
1536
919
  }
1537
- //#endregion
1538
- //#region node_modules/jose/dist/webapi/lib/check_key_type.js
1539
- const tag = (key) => key?.[Symbol.toStringTag];
1540
- const jwkMatchesOp = (alg, key, usage) => {
1541
- if (key.use !== void 0) {
1542
- let expected;
1543
- switch (usage) {
1544
- case "sign":
1545
- case "verify":
1546
- expected = "sig";
1547
- break;
1548
- case "encrypt":
1549
- case "decrypt":
1550
- expected = "enc";
1551
- break;
1552
- }
1553
- if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
1554
- }
1555
- if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
1556
- if (Array.isArray(key.key_ops)) {
1557
- let expectedKeyOp;
1558
- switch (true) {
1559
- case usage === "sign" || usage === "verify":
1560
- case alg === "dir":
1561
- case alg.includes("CBC-HS"):
1562
- expectedKeyOp = usage;
1563
- break;
1564
- case alg.startsWith("PBES2"):
1565
- expectedKeyOp = "deriveBits";
1566
- break;
1567
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
1568
- if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
1569
- else expectedKeyOp = usage;
1570
- break;
1571
- case usage === "encrypt" && alg.startsWith("RSA"):
1572
- expectedKeyOp = "wrapKey";
1573
- break;
1574
- case usage === "decrypt":
1575
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
1576
- break;
1577
- }
1578
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
1579
- }
1580
- return true;
1581
- };
1582
- const symmetricTypeCheck = (alg, key, usage) => {
1583
- if (key instanceof Uint8Array) return;
1584
- if (isJWK(key)) {
1585
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
1586
- throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
1587
- }
1588
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
1589
- if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
1590
- };
1591
- const asymmetricTypeCheck = (alg, key, usage) => {
1592
- if (isJWK(key)) switch (usage) {
1593
- case "decrypt":
1594
- case "sign":
1595
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
1596
- throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
1597
- case "encrypt":
1598
- case "verify":
1599
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
1600
- throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
1601
- }
1602
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
1603
- if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
1604
- if (key.type === "public") switch (usage) {
1605
- case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
1606
- case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
1607
- }
1608
- if (key.type === "private") switch (usage) {
1609
- case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
1610
- case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
1611
- }
1612
- };
1613
- function checkKeyType(alg, key, usage) {
1614
- switch (alg.substring(0, 2)) {
1615
- case "A1":
1616
- case "A2":
1617
- case "di":
1618
- case "HS":
1619
- case "PB":
1620
- symmetricTypeCheck(alg, key, usage);
1621
- break;
1622
- default: asymmetricTypeCheck(alg, key, usage);
920
+ function validateCritDuplicates(Err, protectedHeader) {
921
+ const { crit } = protectedHeader ?? {};
922
+ if (Array.isArray(crit) && new Set(crit).size !== crit.length) throw new Err("\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values");
923
+ }
924
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
925
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
926
+ if (!protectedHeader || protectedHeader.crit === void 0) return [];
927
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
928
+ const recognized = recognizedOption === void 0 ? recognizedDefault : {
929
+ __proto__: null,
930
+ ...recognizedOption,
931
+ ...recognizedDefault
932
+ };
933
+ for (const parameter of protectedHeader.crit) {
934
+ if (!(parameter in recognized)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
935
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
936
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0)) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
1623
937
  }
938
+ return protectedHeader.crit;
1624
939
  }
1625
940
  //#endregion
1626
941
  //#region node_modules/jose/dist/webapi/lib/deflate.js
@@ -1661,119 +976,170 @@ async function decompress(input, maxLength) {
1661
976
  return concat(...chunks);
1662
977
  }
1663
978
  //#endregion
1664
- //#region node_modules/jose/dist/webapi/jwe/flattened/decrypt.js
1665
- async function flattenedDecrypt(jwe, key, options) {
1666
- if (!isObject(jwe)) throw new JWEInvalid("Flattened JWE must be an object");
1667
- if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) throw new JWEInvalid("JOSE Header missing");
979
+ //#region node_modules/jose/dist/webapi/lib/jwe_decrypt.js
980
+ function checkShared(jwe) {
981
+ const { ciphertext, protected: encodedProtected, unprotected } = jwe;
1668
982
  if (jwe.iv !== void 0 && typeof jwe.iv !== "string") throw new JWEInvalid("JWE Initialization Vector incorrect type");
1669
- if (typeof jwe.ciphertext !== "string") throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
983
+ if (typeof ciphertext !== "string") throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
1670
984
  if (jwe.tag !== void 0 && typeof jwe.tag !== "string") throw new JWEInvalid("JWE Authentication Tag incorrect type");
1671
- if (jwe.protected !== void 0 && typeof jwe.protected !== "string") throw new JWEInvalid("JWE Protected Header incorrect type");
1672
- if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") throw new JWEInvalid("JWE Encrypted Key incorrect type");
985
+ if (encodedProtected !== void 0 && typeof encodedProtected !== "string") throw new JWEInvalid("JWE Protected Header incorrect type");
1673
986
  if (jwe.aad !== void 0 && typeof jwe.aad !== "string") throw new JWEInvalid("JWE AAD incorrect type");
1674
- if (jwe.header !== void 0 && !isObject(jwe.header)) throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
1675
- if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
987
+ if (unprotected !== void 0 && !isObject(unprotected)) throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
988
+ }
989
+ function checkRecipient(jwe) {
990
+ const { encrypted_key: encryptedKey, header } = jwe;
991
+ if (encryptedKey !== void 0 && typeof encryptedKey !== "string") throw new JWEInvalid("JWE Encrypted Key incorrect type");
992
+ if (header !== void 0 && !isObject(header)) throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
993
+ if (jwe.protected === void 0 && header === void 0 && jwe.unprotected === void 0) throw new JWEInvalid("JOSE Header missing");
994
+ }
995
+ function shareJWE(jwe) {
996
+ const { protected: encodedProtected, ciphertext, iv, tag, aad } = jwe;
1676
997
  let parsedProt;
1677
- if (jwe.protected) try {
1678
- const protectedHeader = decode(jwe.protected);
1679
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
1680
- } catch {
1681
- throw new JWEInvalid("JWE Protected Header is invalid");
1682
- }
1683
- if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
1684
- const joseHeader = {
1685
- ...parsedProt,
1686
- ...jwe.header,
1687
- ...jwe.unprotected
998
+ if (encodedProtected) parsedProt = parseJoseHeader(encodedProtected, JWEInvalid, "JWE Protected Header is invalid");
999
+ const protectedHeader = encodedProtected !== void 0 ? encode$1(encodedProtected) : /* @__PURE__ */ new Uint8Array();
1000
+ return [
1001
+ parsedProt,
1002
+ decodeBase64url(ciphertext, "ciphertext", JWEInvalid),
1003
+ iv !== void 0 ? decodeBase64url(iv, "iv", JWEInvalid) : void 0,
1004
+ tag !== void 0 ? decodeBase64url(tag, "tag", JWEInvalid) : void 0,
1005
+ aad !== void 0 ? concat(protectedHeader, encode$1("."), encodeBase64url(aad, "aad", JWEInvalid)) : protectedHeader
1006
+ ];
1007
+ }
1008
+ function decryptResult(jwe, decrypted) {
1009
+ const [plaintext, parsedProt, key, resolvedKey] = decrypted;
1010
+ const { protected: encodedProtected, aad, unprotected, header } = jwe;
1011
+ const result = { plaintext };
1012
+ if (encodedProtected !== void 0) result.protectedHeader = parsedProt;
1013
+ if (aad !== void 0) result.additionalAuthenticatedData = decodeBase64url(aad, "aad", JWEInvalid);
1014
+ if (unprotected !== void 0) result.sharedUnprotectedHeader = unprotected;
1015
+ if (header !== void 0) result.unprotectedHeader = header;
1016
+ if (resolvedKey) return {
1017
+ ...result,
1018
+ key
1688
1019
  };
1689
- validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
1020
+ return result;
1021
+ }
1022
+ function prepareDecrypt(options) {
1023
+ return [
1024
+ options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms),
1025
+ options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms),
1026
+ options
1027
+ ];
1028
+ }
1029
+ async function decryptRecipient(jwe, token, shared, key) {
1030
+ const [keyManagementAlgorithms, contentEncryptionAlgorithms, options] = shared;
1031
+ const [parsedProt, ciphertext, iv, tag, additionalData] = token;
1032
+ const { encrypted_key: encodedKey, header, unprotected } = jwe;
1033
+ let joseHeader;
1034
+ if (header !== void 0 || unprotected !== void 0) {
1035
+ if (!isDisjoint(parsedProt, header, unprotected)) throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
1036
+ joseHeader = {
1037
+ ...parsedProt,
1038
+ ...header,
1039
+ ...unprotected
1040
+ };
1041
+ } else joseHeader = parsedProt ?? {};
1042
+ validateCrit(JWEInvalid, JWE_RECOGNIZED, options?.crit, parsedProt, joseHeader);
1690
1043
  if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") throw new JOSENotSupported("Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.");
1691
1044
  if (joseHeader.zip !== void 0 && !parsedProt?.zip) throw new JWEInvalid("JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.");
1692
1045
  const { alg, enc } = joseHeader;
1693
1046
  if (typeof alg !== "string" || !alg) throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
1694
1047
  if (typeof enc !== "string" || !enc) throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
1695
- const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms);
1696
- const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
1697
1048
  if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
1698
1049
  if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) throw new JOSEAlgNotAllowed("\"enc\" (Encryption Algorithm) Header Parameter value not allowed");
1050
+ const encEntry = jweEncryption(enc);
1699
1051
  let encryptedKey;
1700
- if (jwe.encrypted_key !== void 0) encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid);
1052
+ if (encodedKey !== void 0) encryptedKey = decodeBase64url(encodedKey, "encrypted_key", JWEInvalid);
1701
1053
  let resolvedKey = false;
1702
1054
  if (typeof key === "function") {
1703
1055
  key = await key(parsedProt, jwe);
1704
1056
  resolvedKey = true;
1705
1057
  }
1706
- checkKeyType(alg === "dir" ? enc : alg, key, "decrypt");
1707
- const k = await normalizeKey(key, alg);
1058
+ const algEntry = jweAlgorithm(alg);
1059
+ const k = await prepareKey(alg === "dir" ? encEntry : algEntry, key, "decrypt");
1708
1060
  let cek;
1709
1061
  try {
1710
- cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);
1062
+ cek = await decryptKeyManagement(alg, encEntry, k, encryptedKey, joseHeader, options);
1711
1063
  } catch (err) {
1712
1064
  if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) throw err;
1713
- cek = generateCek(enc);
1065
+ cek = generateCek(encEntry);
1714
1066
  }
1715
- let iv;
1716
- let tag;
1717
- if (jwe.iv !== void 0) iv = decodeBase64url(jwe.iv, "iv", JWEInvalid);
1718
- if (jwe.tag !== void 0) tag = decodeBase64url(jwe.tag, "tag", JWEInvalid);
1719
- const protectedHeader = jwe.protected !== void 0 ? encode$1(jwe.protected) : /* @__PURE__ */ new Uint8Array();
1720
- let additionalData;
1721
- if (jwe.aad !== void 0) additionalData = concat(protectedHeader, encode$1("."), encode$1(jwe.aad));
1722
- else additionalData = protectedHeader;
1723
- const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid);
1724
- const plaintext = await decrypt$1(enc, cek, ciphertext, iv, tag, additionalData);
1725
- const result = { plaintext };
1067
+ let plaintext = await decrypt(encEntry, cek, ciphertext, iv, tag, additionalData);
1726
1068
  if (joseHeader.zip === "DEF") {
1727
1069
  const maxDecompressedLength = options?.maxDecompressedLength ?? 25e4;
1728
1070
  if (maxDecompressedLength === 0) throw new JOSENotSupported("JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.");
1729
1071
  if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");
1730
- result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => {
1072
+ plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => {
1731
1073
  if (cause instanceof JWEInvalid) throw cause;
1732
1074
  throw new JWEInvalid("Failed to decompress plaintext", { cause });
1733
1075
  });
1734
1076
  }
1735
- if (jwe.protected !== void 0) result.protectedHeader = parsedProt;
1736
- if (jwe.aad !== void 0) result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid);
1737
- if (jwe.unprotected !== void 0) result.sharedUnprotectedHeader = jwe.unprotected;
1738
- if (jwe.header !== void 0) result.unprotectedHeader = jwe.header;
1739
- if (resolvedKey) return {
1740
- ...result,
1741
- key: k
1742
- };
1743
- return result;
1077
+ return [
1078
+ plaintext,
1079
+ parsedProt,
1080
+ k,
1081
+ resolvedKey
1082
+ ];
1744
1083
  }
1745
- //#endregion
1746
- //#region node_modules/jose/dist/webapi/jwe/compact/decrypt.js
1747
- async function compactDecrypt(jwe, key, options) {
1084
+ async function decryptJWE(jwe, shared, key) {
1085
+ return decryptRecipient(jwe, shareJWE(jwe), shared, key);
1086
+ }
1087
+ async function decryptCompact(jwe, shared, key) {
1748
1088
  if (jwe instanceof Uint8Array) jwe = decoder.decode(jwe);
1749
1089
  if (typeof jwe !== "string") throw new JWEInvalid("Compact JWE must be a string or Uint8Array");
1750
1090
  const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length } = jwe.split(".");
1751
1091
  if (length !== 5) throw new JWEInvalid("Invalid Compact JWE");
1752
- const decrypted = await flattenedDecrypt({
1092
+ return decryptJWE({
1753
1093
  ciphertext,
1754
1094
  iv: iv || void 0,
1755
1095
  protected: protectedHeader,
1756
1096
  tag: tag || void 0,
1757
1097
  encrypted_key: encryptedKey || void 0
1758
- }, key, options);
1098
+ }, shared, key);
1099
+ }
1100
+ //#endregion
1101
+ //#region node_modules/jose/dist/webapi/jwe/compact/decrypt.js
1102
+ async function compactDecrypt(jwe, key, options) {
1103
+ const decrypted = await decryptCompact(jwe, prepareDecrypt(options), key);
1759
1104
  const result = {
1760
- plaintext: decrypted.plaintext,
1761
- protectedHeader: decrypted.protectedHeader
1105
+ plaintext: decrypted[0],
1106
+ protectedHeader: decrypted[1]
1762
1107
  };
1763
1108
  if (typeof key === "function") return {
1764
1109
  ...result,
1765
- key: decrypted.key
1110
+ key: decrypted[2]
1766
1111
  };
1767
1112
  return result;
1768
1113
  }
1769
1114
  //#endregion
1115
+ //#region node_modules/jose/dist/webapi/jwe/flattened/decrypt.js
1116
+ async function flattenedDecrypt(jwe, key, options) {
1117
+ if (!isObject(jwe)) throw new JWEInvalid("Flattened JWE must be an object");
1118
+ checkShared(jwe);
1119
+ checkRecipient(jwe);
1120
+ return decryptResult(jwe, await decryptJWE(jwe, prepareDecrypt(options), key));
1121
+ }
1122
+ //#endregion
1770
1123
  //#region node_modules/jose/dist/webapi/jwe/general/decrypt.js
1771
1124
  async function generalDecrypt(jwe, key, options) {
1772
1125
  if (!isObject(jwe)) throw new JWEInvalid("General JWE must be an object");
1773
1126
  if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) throw new JWEInvalid("JWE Recipients missing or incorrect type");
1774
1127
  if (!jwe.recipients.length) throw new JWEInvalid("JWE Recipients has no members");
1128
+ let shared;
1129
+ let token;
1130
+ try {
1131
+ checkShared(jwe);
1132
+ shared = prepareDecrypt(options);
1133
+ token = shareJWE(jwe);
1134
+ } catch {
1135
+ throw new JWEDecryptionFailed();
1136
+ }
1137
+ if (jwe.recipients.length > 1) for (const { header } of jwe.recipients) {
1138
+ const alg = token[0]?.alg ?? header?.alg ?? jwe.unprotected?.alg;
1139
+ if (alg === "dir" || alg === "ECDH-ES") throw new JWEInvalid(`"${alg}" alg may only have a single recipient`);
1140
+ }
1775
1141
  for (const recipient of jwe.recipients) try {
1776
- return await flattenedDecrypt({
1142
+ const flattened = {
1777
1143
  aad: jwe.aad,
1778
1144
  ciphertext: jwe.ciphertext,
1779
1145
  encrypted_key: recipient.encrypted_key,
@@ -1782,11 +1148,87 @@ async function generalDecrypt(jwe, key, options) {
1782
1148
  protected: jwe.protected,
1783
1149
  tag: jwe.tag,
1784
1150
  unprotected: jwe.unprotected
1785
- }, key, options);
1151
+ };
1152
+ checkRecipient(flattened);
1153
+ return decryptResult(flattened, await decryptRecipient(flattened, token, shared, key));
1786
1154
  } catch {}
1787
1155
  throw new JWEDecryptionFailed();
1788
1156
  }
1789
1157
  //#endregion
1158
+ //#region node_modules/jose/dist/webapi/lib/jwe_encrypt.js
1159
+ function checkEncryptHeaders(input) {
1160
+ const [, protectedHeader, unprotectedHeader, sharedUnprotectedHeader, , , , , crit] = input;
1161
+ if (!isDisjoint(protectedHeader, unprotectedHeader, sharedUnprotectedHeader)) throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
1162
+ const joseHeader = {
1163
+ ...protectedHeader,
1164
+ ...unprotectedHeader,
1165
+ ...sharedUnprotectedHeader
1166
+ };
1167
+ validateCrit(JWEInvalid, JWE_RECOGNIZED, crit, protectedHeader, joseHeader);
1168
+ if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") throw new JOSENotSupported("Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.");
1169
+ if (joseHeader.zip !== void 0 && !protectedHeader?.zip) throw new JWEInvalid("JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.");
1170
+ const { alg, enc } = joseHeader;
1171
+ if (typeof alg !== "string" || !alg) throw new JWEInvalid("JWE \"alg\" (Algorithm) Header Parameter missing or invalid");
1172
+ if (typeof enc !== "string" || !enc) throw new JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid");
1173
+ return [
1174
+ joseHeader,
1175
+ alg,
1176
+ enc,
1177
+ jweEncryption(enc)
1178
+ ];
1179
+ }
1180
+ async function encryptJWE(input, checked, key) {
1181
+ const [joseHeader, alg, , encEntry] = checked;
1182
+ const [inputPlaintext, inputProtectedHeader, inputUnprotectedHeader, sharedUnprotectedHeader, aad, providedCek, inputIv, keyManagementParameters, , unprotectedParameters] = input;
1183
+ let protectedHeader = inputProtectedHeader;
1184
+ let unprotectedHeader = inputUnprotectedHeader;
1185
+ if (providedCek && (alg === "dir" || alg === "ECDH-ES")) throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
1186
+ const algEntry = jweAlgorithm(alg);
1187
+ const [cek, encryptedKey, parameters] = await encryptKeyManagement(alg, encEntry, await prepareKey(alg === "dir" ? encEntry : algEntry, key, "encrypt"), providedCek, keyManagementParameters);
1188
+ if (parameters) {
1189
+ if (unprotectedParameters) unprotectedHeader = unprotectedHeader ? {
1190
+ ...unprotectedHeader,
1191
+ ...parameters
1192
+ } : parameters;
1193
+ else protectedHeader = protectedHeader ? {
1194
+ ...protectedHeader,
1195
+ ...parameters
1196
+ } : parameters;
1197
+ }
1198
+ let protectedHeaderS;
1199
+ let protectedHeaderB;
1200
+ if (protectedHeader) {
1201
+ protectedHeaderS = encode(JSON.stringify(protectedHeader));
1202
+ protectedHeaderB = encode$1(protectedHeaderS);
1203
+ } else {
1204
+ protectedHeaderS = "";
1205
+ protectedHeaderB = /* @__PURE__ */ new Uint8Array();
1206
+ }
1207
+ let additionalData;
1208
+ let aadMember;
1209
+ if (aad?.byteLength) {
1210
+ aadMember = encode(aad);
1211
+ additionalData = concat(protectedHeaderB, encode$1("."), encode$1(aadMember));
1212
+ } else additionalData = protectedHeaderB;
1213
+ let plaintext = inputPlaintext;
1214
+ if (joseHeader.zip === "DEF") plaintext = await compress(plaintext).catch((cause) => {
1215
+ throw new JWEInvalid("Failed to compress plaintext", { cause });
1216
+ });
1217
+ const { ciphertext, tag, iv } = await encrypt(encEntry, plaintext, cek, inputIv, additionalData);
1218
+ const jwe = { ciphertext: encode(ciphertext) };
1219
+ if (iv) jwe.iv = encode(iv);
1220
+ if (tag) jwe.tag = encode(tag);
1221
+ if (encryptedKey) jwe.encrypted_key = encode(encryptedKey);
1222
+ if (aadMember) jwe.aad = aadMember;
1223
+ if (protectedHeader) jwe.protected = protectedHeaderS;
1224
+ if (sharedUnprotectedHeader) jwe.unprotected = sharedUnprotectedHeader;
1225
+ if (unprotectedHeader) jwe.header = unprotectedHeader;
1226
+ return jwe;
1227
+ }
1228
+ async function createJWE(input, key) {
1229
+ return encryptJWE(input, checkEncryptHeaders(input), key);
1230
+ }
1231
+ //#endregion
1790
1232
  //#region node_modules/jose/dist/webapi/jwe/flattened/encrypt.js
1791
1233
  var FlattenedEncrypt = class {
1792
1234
  #plaintext;
@@ -1837,90 +1279,43 @@ var FlattenedEncrypt = class {
1837
1279
  }
1838
1280
  async encrypt(key, options) {
1839
1281
  if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
1840
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
1841
- const joseHeader = {
1842
- ...this.#protectedHeader,
1843
- ...this.#unprotectedHeader,
1844
- ...this.#sharedUnprotectedHeader
1845
- };
1846
- validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader);
1847
- if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") throw new JOSENotSupported("Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.");
1848
- if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) throw new JWEInvalid("JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.");
1849
- const { alg, enc } = joseHeader;
1850
- if (typeof alg !== "string" || !alg) throw new JWEInvalid("JWE \"alg\" (Algorithm) Header Parameter missing or invalid");
1851
- if (typeof enc !== "string" || !enc) throw new JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid");
1852
- let encryptedKey;
1853
- if (this.#cek && (alg === "dir" || alg === "ECDH-ES")) throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
1854
- checkKeyType(alg === "dir" ? enc : alg, key, "encrypt");
1855
- let cek;
1856
- {
1857
- let parameters;
1858
- const k = await normalizeKey(key, alg);
1859
- ({cek, encryptedKey, parameters} = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters));
1860
- if (parameters) if (options && unprotected in options) if (!this.#unprotectedHeader) this.setUnprotectedHeader(parameters);
1861
- else this.#unprotectedHeader = {
1862
- ...this.#unprotectedHeader,
1863
- ...parameters
1864
- };
1865
- else if (!this.#protectedHeader) this.setProtectedHeader(parameters);
1866
- else this.#protectedHeader = {
1867
- ...this.#protectedHeader,
1868
- ...parameters
1869
- };
1870
- }
1871
- let additionalData;
1872
- let protectedHeaderS;
1873
- let protectedHeaderB;
1874
- let aadMember;
1875
- if (this.#protectedHeader) {
1876
- protectedHeaderS = encode(JSON.stringify(this.#protectedHeader));
1877
- protectedHeaderB = encode$1(protectedHeaderS);
1878
- } else {
1879
- protectedHeaderS = "";
1880
- protectedHeaderB = /* @__PURE__ */ new Uint8Array();
1881
- }
1882
- if (this.#aad) {
1883
- aadMember = encode(this.#aad);
1884
- const aadMemberBytes = encode$1(aadMember);
1885
- additionalData = concat(protectedHeaderB, encode$1("."), aadMemberBytes);
1886
- } else additionalData = protectedHeaderB;
1887
- let plaintext = this.#plaintext;
1888
- if (joseHeader.zip === "DEF") plaintext = await compress(plaintext).catch((cause) => {
1889
- throw new JWEInvalid("Failed to compress plaintext", { cause });
1890
- });
1891
- const { ciphertext, tag, iv } = await encrypt$1(enc, plaintext, cek, this.#iv, additionalData);
1892
- const jwe = { ciphertext: encode(ciphertext) };
1893
- if (iv) jwe.iv = encode(iv);
1894
- if (tag) jwe.tag = encode(tag);
1895
- if (encryptedKey) jwe.encrypted_key = encode(encryptedKey);
1896
- if (aadMember) jwe.aad = aadMember;
1897
- if (this.#protectedHeader) jwe.protected = protectedHeaderS;
1898
- if (this.#sharedUnprotectedHeader) jwe.unprotected = this.#sharedUnprotectedHeader;
1899
- if (this.#unprotectedHeader) jwe.header = this.#unprotectedHeader;
1900
- return jwe;
1282
+ validateCritDuplicates(JWEInvalid, this.#protectedHeader);
1283
+ return createJWE([
1284
+ this.#plaintext,
1285
+ this.#protectedHeader,
1286
+ this.#unprotectedHeader,
1287
+ this.#sharedUnprotectedHeader,
1288
+ this.#aad,
1289
+ this.#cek,
1290
+ this.#iv,
1291
+ this.#keyManagementParameters,
1292
+ options?.crit,
1293
+ options ? unprotected in options : false
1294
+ ], key);
1901
1295
  }
1902
1296
  };
1903
1297
  //#endregion
1904
1298
  //#region node_modules/jose/dist/webapi/jwe/general/encrypt.js
1905
1299
  var IndividualRecipient = class {
1906
1300
  #parent;
1907
- unprotectedHeader;
1908
- keyManagementParameters;
1909
- key;
1910
- options;
1911
- constructor(enc, key, options) {
1301
+ state;
1302
+ constructor(enc, key, crit) {
1912
1303
  this.#parent = enc;
1913
- this.key = key;
1914
- this.options = options;
1304
+ this.state = [
1305
+ void 0,
1306
+ void 0,
1307
+ key,
1308
+ crit
1309
+ ];
1915
1310
  }
1916
1311
  setUnprotectedHeader(unprotectedHeader) {
1917
- assertNotSet(this.unprotectedHeader, "setUnprotectedHeader");
1918
- this.unprotectedHeader = unprotectedHeader;
1312
+ assertNotSet(this.state[0], "setUnprotectedHeader");
1313
+ this.state[0] = unprotectedHeader;
1919
1314
  return this;
1920
1315
  }
1921
1316
  setKeyManagementParameters(parameters) {
1922
- assertNotSet(this.keyManagementParameters, "setKeyManagementParameters");
1923
- this.keyManagementParameters = parameters;
1317
+ assertNotSet(this.state[1], "setKeyManagementParameters");
1318
+ this.state[1] = parameters;
1924
1319
  return this;
1925
1320
  }
1926
1321
  addRecipient(...args) {
@@ -1933,6 +1328,13 @@ var IndividualRecipient = class {
1933
1328
  return this.#parent;
1934
1329
  }
1935
1330
  };
1331
+ function copyOptionalMembers(flattened, jwe, recipient) {
1332
+ const { aad, protected: protectedHeader, unprotected, header } = flattened;
1333
+ if (aad) jwe.aad = aad;
1334
+ if (protectedHeader) jwe.protected = protectedHeader;
1335
+ if (unprotected) jwe.unprotected = unprotected;
1336
+ if (header) recipient.header = header;
1337
+ }
1936
1338
  var GeneralEncrypt = class {
1937
1339
  #plaintext;
1938
1340
  #recipients = [];
@@ -1943,7 +1345,7 @@ var GeneralEncrypt = class {
1943
1345
  this.#plaintext = plaintext;
1944
1346
  }
1945
1347
  addRecipient(key, options) {
1946
- const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
1348
+ const recipient = new IndividualRecipient(this, key, options?.crit);
1947
1349
  this.#recipients.push(recipient);
1948
1350
  return recipient;
1949
1351
  }
@@ -1963,72 +1365,70 @@ var GeneralEncrypt = class {
1963
1365
  }
1964
1366
  async encrypt() {
1965
1367
  if (!this.#recipients.length) throw new JWEInvalid("at least one recipient must be added");
1368
+ if (!(this.#plaintext instanceof Uint8Array)) throw new TypeError("plaintext must be an instance of Uint8Array");
1966
1369
  if (this.#recipients.length === 1) {
1967
1370
  const [recipient] = this.#recipients;
1968
- const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options });
1371
+ const [unprotectedHeader, keyManagementParameters, key, crit] = recipient.state;
1372
+ const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(unprotectedHeader).setKeyManagementParameters(keyManagementParameters).encrypt(key, { crit });
1969
1373
  const jwe = {
1970
1374
  ciphertext: flattened.ciphertext,
1971
1375
  iv: flattened.iv,
1972
1376
  recipients: [{}],
1973
1377
  tag: flattened.tag
1974
1378
  };
1975
- if (flattened.aad) jwe.aad = flattened.aad;
1976
- if (flattened.protected) jwe.protected = flattened.protected;
1977
- if (flattened.unprotected) jwe.unprotected = flattened.unprotected;
1978
1379
  if (flattened.encrypted_key) jwe.recipients[0].encrypted_key = flattened.encrypted_key;
1979
- if (flattened.header) jwe.recipients[0].header = flattened.header;
1380
+ copyOptionalMembers(flattened, jwe, jwe.recipients[0]);
1980
1381
  return jwe;
1981
1382
  }
1383
+ validateCritDuplicates(JWEInvalid, this.#protectedHeader);
1982
1384
  let enc;
1385
+ const inputs = [];
1386
+ const checked = [];
1983
1387
  for (let i = 0; i < this.#recipients.length; i++) {
1984
- const recipient = this.#recipients[i];
1985
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, recipient.unprotectedHeader)) throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
1986
- const joseHeader = {
1987
- ...this.#protectedHeader,
1988
- ...this.#unprotectedHeader,
1989
- ...recipient.unprotectedHeader
1990
- };
1991
- const { alg } = joseHeader;
1992
- if (typeof alg !== "string" || !alg) throw new JWEInvalid("JWE \"alg\" (Algorithm) Header Parameter missing or invalid");
1993
- if (alg === "dir" || alg === "ECDH-ES") throw new JWEInvalid("\"dir\" and \"ECDH-ES\" alg may only be used with a single recipient");
1994
- if (typeof joseHeader.enc !== "string" || !joseHeader.enc) throw new JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid");
1995
- if (!enc) enc = joseHeader.enc;
1996
- else if (enc !== joseHeader.enc) throw new JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter must be the same for all recipients");
1997
- validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this.#protectedHeader, joseHeader);
1998
- if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") throw new JOSENotSupported("Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value.");
1999
- if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) throw new JWEInvalid("JWE \"zip\" (Compression Algorithm) Header Parameter MUST be in a protected header.");
1388
+ const [unprotectedHeader, keyManagementParameters, , crit] = this.#recipients[i].state;
1389
+ const input = [
1390
+ this.#plaintext,
1391
+ this.#protectedHeader,
1392
+ unprotectedHeader,
1393
+ this.#unprotectedHeader,
1394
+ this.#aad,
1395
+ void 0,
1396
+ void 0,
1397
+ keyManagementParameters,
1398
+ crit,
1399
+ true
1400
+ ];
1401
+ const headers = checkEncryptHeaders(input);
1402
+ inputs.push(input);
1403
+ checked.push(headers);
1404
+ if (headers[1] === "dir" || headers[1] === "ECDH-ES") throw new JWEInvalid(`"${headers[1]}" alg may only have a single recipient`);
1405
+ if (!enc) enc = headers[2];
1406
+ else if (enc !== headers[2]) throw new JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter must be the same for all recipients");
2000
1407
  }
2001
- const cek = generateCek(enc);
1408
+ const cek = generateCek(checked[0][3]);
2002
1409
  const jwe = {
2003
1410
  ciphertext: "",
2004
1411
  recipients: []
2005
1412
  };
2006
1413
  for (let i = 0; i < this.#recipients.length; i++) {
2007
- const recipient = this.#recipients[i];
1414
+ const [unprotectedHeader, keyManagementParameters, key] = this.#recipients[i].state;
2008
1415
  const target = {};
2009
1416
  jwe.recipients.push(target);
2010
1417
  if (i === 0) {
2011
- const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setContentEncryptionKey(cek).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters(recipient.keyManagementParameters).encrypt(recipient.key, {
2012
- ...recipient.options,
2013
- [unprotected]: true
2014
- });
1418
+ inputs[0][5] = cek;
1419
+ const flattened = await encryptJWE(inputs[0], checked[0], key);
2015
1420
  jwe.ciphertext = flattened.ciphertext;
2016
1421
  jwe.iv = flattened.iv;
2017
1422
  jwe.tag = flattened.tag;
2018
- if (flattened.aad) jwe.aad = flattened.aad;
2019
- if (flattened.protected) jwe.protected = flattened.protected;
2020
- if (flattened.unprotected) jwe.unprotected = flattened.unprotected;
2021
1423
  target.encrypted_key = flattened.encrypted_key;
2022
- if (flattened.header) target.header = flattened.header;
1424
+ copyOptionalMembers(flattened, jwe, target);
2023
1425
  continue;
2024
1426
  }
2025
- const alg = recipient.unprotectedHeader?.alg || this.#protectedHeader?.alg || this.#unprotectedHeader?.alg;
2026
- checkKeyType(alg === "dir" ? enc : alg, recipient.key, "encrypt");
2027
- const k = await normalizeKey(recipient.key, alg);
2028
- const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters);
1427
+ const [, alg, , encEntry] = checked[i];
1428
+ const [, encryptedKey, parameters] = await encryptKeyManagement(alg, encEntry, await prepareKey(jweAlgorithm(alg), key, "encrypt"), cek, keyManagementParameters);
2029
1429
  target.encrypted_key = encode(encryptedKey);
2030
- if (recipient.unprotectedHeader || parameters) target.header = {
2031
- ...recipient.unprotectedHeader,
1430
+ if (unprotectedHeader || parameters) target.header = {
1431
+ ...unprotectedHeader,
2032
1432
  ...parameters
2033
1433
  };
2034
1434
  }
@@ -2036,150 +1436,260 @@ var GeneralEncrypt = class {
2036
1436
  }
2037
1437
  };
2038
1438
  //#endregion
2039
- //#region node_modules/jose/dist/webapi/jws/flattened/verify.js
2040
- async function flattenedVerify(jws, key, options) {
2041
- if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object");
2042
- if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
2043
- if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
2044
- if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
2045
- if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
2046
- if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
2047
- let parsedProt = {};
2048
- if (jws.protected) try {
2049
- const protectedHeader = decode(jws.protected);
2050
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
1439
+ //#region node_modules/jose/dist/webapi/lib/signing.js
1440
+ async function getSigKey(entry, key, usage) {
1441
+ if (key instanceof Uint8Array) return crypto.subtle.importKey("raw", key, entry.subtle, false, [usage]);
1442
+ checkCryptoKey(key, entry.subtle, usage);
1443
+ if (entry.minRsaBits) checkModulusLength(entry.alg, key);
1444
+ return key;
1445
+ }
1446
+ async function sign(entry, key, data) {
1447
+ const cryptoKey = await getSigKey(entry, key, "sign");
1448
+ const signature = await crypto.subtle.sign(entry.signing, cryptoKey, data);
1449
+ return new Uint8Array(signature);
1450
+ }
1451
+ async function verify(entry, key, signature, data) {
1452
+ const cryptoKey = await getSigKey(entry, key, "verify");
1453
+ try {
1454
+ return await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);
2051
1455
  } catch {
2052
- throw new JWSInvalid("JWS Protected Header is invalid");
1456
+ return false;
2053
1457
  }
2054
- if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
2055
- const joseHeader = {
2056
- ...parsedProt,
2057
- ...jws.header
1458
+ }
1459
+ //#endregion
1460
+ //#region node_modules/jose/dist/webapi/lib/jws_algorithms.js
1461
+ const sig = [["verify"], ["sign"]];
1462
+ function hmac(bits) {
1463
+ const subtle = {
1464
+ name: "HMAC",
1465
+ hash: `SHA-${bits}`
1466
+ };
1467
+ return {
1468
+ kty: ["oct"],
1469
+ secret: true,
1470
+ subtle,
1471
+ signing: subtle,
1472
+ usages: sig
1473
+ };
1474
+ }
1475
+ function rsa(bits, saltLength) {
1476
+ const subtle = {
1477
+ name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
1478
+ hash: `SHA-${bits}`
1479
+ };
1480
+ return {
1481
+ kty: ["RSA"],
1482
+ subtle,
1483
+ signing: saltLength ? {
1484
+ ...subtle,
1485
+ saltLength
1486
+ } : subtle,
1487
+ usages: sig,
1488
+ minRsaBits: 2048
1489
+ };
1490
+ }
1491
+ function ecdsa(crv, bits) {
1492
+ return {
1493
+ kty: ["EC"],
1494
+ crv,
1495
+ subtle: {
1496
+ name: "ECDSA",
1497
+ namedCurve: crv
1498
+ },
1499
+ signing: {
1500
+ name: "ECDSA",
1501
+ hash: `SHA-${bits}`
1502
+ },
1503
+ usages: sig
2058
1504
  };
2059
- const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
1505
+ }
1506
+ function eddsa() {
1507
+ const subtle = { name: "Ed25519" };
1508
+ return {
1509
+ kty: ["OKP"],
1510
+ crv: "Ed25519",
1511
+ subtle,
1512
+ signing: subtle,
1513
+ usages: sig
1514
+ };
1515
+ }
1516
+ function mldsa(bits) {
1517
+ const subtle = { name: `ML-DSA-${bits}` };
1518
+ return {
1519
+ kty: ["AKP"],
1520
+ subtle,
1521
+ signing: subtle,
1522
+ usages: sig
1523
+ };
1524
+ }
1525
+ const JWS = table({
1526
+ HS256: hmac(256),
1527
+ HS384: hmac(384),
1528
+ HS512: hmac(512),
1529
+ RS256: rsa(256),
1530
+ RS384: rsa(384),
1531
+ RS512: rsa(512),
1532
+ PS256: rsa(256, 32),
1533
+ PS384: rsa(384, 48),
1534
+ PS512: rsa(512, 64),
1535
+ ES256: ecdsa("P-256", 256),
1536
+ ES384: ecdsa("P-384", 384),
1537
+ ES512: ecdsa("P-521", 512),
1538
+ EdDSA: eddsa(),
1539
+ Ed25519: eddsa(),
1540
+ "ML-DSA-44": mldsa(44),
1541
+ "ML-DSA-65": mldsa(65),
1542
+ "ML-DSA-87": mldsa(87)
1543
+ });
1544
+ function jwsAlgorithm(alg) {
1545
+ const entry = typeof alg === "string" ? JWS[alg] : void 0;
1546
+ if (!entry) throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
1547
+ return entry;
1548
+ }
1549
+ //#endregion
1550
+ //#region node_modules/jose/dist/webapi/lib/jws_verify.js
1551
+ function verifyResult(jws, verified) {
1552
+ const [payload, parsedProt, , key, resolvedKey] = verified;
1553
+ const result = { payload };
1554
+ if (jws.protected !== void 0) result.protectedHeader = parsedProt;
1555
+ if (jws.header !== void 0) result.unprotectedHeader = jws.header;
1556
+ if (resolvedKey) return {
1557
+ ...result,
1558
+ key
1559
+ };
1560
+ return result;
1561
+ }
1562
+ function prepareVerify(options) {
1563
+ return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
1564
+ }
1565
+ async function verifySignature(jws, shared, key) {
1566
+ const { protected: encodedProtected, header, payload: inputPayload } = jws;
1567
+ let parsedProt = {};
1568
+ if (encodedProtected) parsedProt = parseJoseHeader(encodedProtected, JWSInvalid, "JWS Protected Header is invalid");
1569
+ let joseHeader;
1570
+ if (header !== void 0) {
1571
+ if (!isDisjoint(parsedProt, header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1572
+ joseHeader = {
1573
+ ...parsedProt,
1574
+ ...header
1575
+ };
1576
+ } else joseHeader = parsedProt;
1577
+ const extensions = validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader);
2060
1578
  let b64 = true;
2061
- if (extensions.has("b64")) {
1579
+ if (extensions.includes("b64")) {
2062
1580
  b64 = parsedProt.b64;
2063
1581
  if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
2064
1582
  }
2065
1583
  const { alg } = joseHeader;
2066
1584
  if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
2067
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
2068
- if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
1585
+ if (shared[0] && !shared[0].has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
2069
1586
  if (b64) {
2070
- if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string");
2071
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
1587
+ if (typeof inputPayload !== "string") throw new JWSInvalid("JWS Payload must be a string");
1588
+ } else if (typeof inputPayload !== "string" && !(inputPayload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
2072
1589
  let resolvedKey = false;
2073
1590
  if (typeof key === "function") {
2074
1591
  key = await key(parsedProt, jws);
2075
1592
  resolvedKey = true;
2076
1593
  }
2077
- checkKeyType(alg, key, "verify");
2078
- const data = concat(jws.protected !== void 0 ? encode$1(jws.protected) : /* @__PURE__ */ new Uint8Array(), encode$1("."), typeof jws.payload === "string" ? b64 ? encode$1(jws.payload) : encoder.encode(jws.payload) : jws.payload);
1594
+ const entry = jwsAlgorithm(alg);
1595
+ const data = concat(encodedProtected !== void 0 ? encode$1(encodedProtected) : /* @__PURE__ */ new Uint8Array(), encode$1("."), typeof inputPayload === "string" ? b64 ? shared[2] ??= encodeBase64url(inputPayload, "payload", JWSInvalid) : encoder.encode(inputPayload) : inputPayload);
2079
1596
  const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
2080
- const k = await normalizeKey(key, alg);
2081
- if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed();
1597
+ const k = await prepareKey(entry, key, "verify");
1598
+ if (!await verify(entry, k, signature, data)) throw new JWSSignatureVerificationFailed();
2082
1599
  let payload;
2083
- if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
2084
- else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload);
2085
- else payload = jws.payload;
2086
- const result = { payload };
2087
- if (jws.protected !== void 0) result.protectedHeader = parsedProt;
2088
- if (jws.header !== void 0) result.unprotectedHeader = jws.header;
2089
- if (resolvedKey) return {
2090
- ...result,
2091
- key: k
2092
- };
2093
- return result;
1600
+ if (b64) payload = decodeBase64url(inputPayload, "payload", JWSInvalid);
1601
+ else if (typeof inputPayload === "string") payload = encoder.encode(inputPayload);
1602
+ else payload = inputPayload;
1603
+ return [
1604
+ payload,
1605
+ parsedProt,
1606
+ b64,
1607
+ k,
1608
+ resolvedKey
1609
+ ];
2094
1610
  }
2095
- //#endregion
2096
- //#region node_modules/jose/dist/webapi/jws/compact/verify.js
2097
- async function compactVerify(jws, key, options) {
1611
+ async function verifyCompact(jws, shared, key) {
2098
1612
  if (jws instanceof Uint8Array) jws = decoder.decode(jws);
2099
1613
  if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
2100
1614
  const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
2101
1615
  if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
2102
- const verified = await flattenedVerify({
1616
+ return verifySignature({
2103
1617
  payload,
2104
1618
  protected: protectedHeader,
2105
1619
  signature
2106
- }, key, options);
1620
+ }, shared, key);
1621
+ }
1622
+ //#endregion
1623
+ //#region node_modules/jose/dist/webapi/jws/compact/verify.js
1624
+ async function compactVerify(jws, key, options) {
1625
+ const verified = await verifyCompact(jws, prepareVerify(options), key);
2107
1626
  const result = {
2108
- payload: verified.payload,
2109
- protectedHeader: verified.protectedHeader
1627
+ payload: verified[0],
1628
+ protectedHeader: verified[1]
2110
1629
  };
2111
1630
  if (typeof key === "function") return {
2112
1631
  ...result,
2113
- key: verified.key
1632
+ key: verified[3]
2114
1633
  };
2115
1634
  return result;
2116
1635
  }
2117
1636
  //#endregion
1637
+ //#region node_modules/jose/dist/webapi/jws/flattened/verify.js
1638
+ async function flattenedVerify(jws, key, options) {
1639
+ if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object");
1640
+ if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
1641
+ if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
1642
+ if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
1643
+ if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
1644
+ if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
1645
+ return verifyResult(jws, await verifySignature(jws, prepareVerify(options), key));
1646
+ }
1647
+ //#endregion
2118
1648
  //#region node_modules/jose/dist/webapi/jws/general/verify.js
2119
1649
  async function generalVerify(jws, key, options) {
2120
1650
  if (!isObject(jws)) throw new JWSInvalid("General JWS must be an object");
2121
- if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) throw new JWSInvalid("JWS Signatures missing or incorrect type");
2122
- for (const signature of jws.signatures) try {
2123
- return await flattenedVerify({
2124
- header: signature.header,
2125
- payload: jws.payload,
2126
- protected: signature.protected,
2127
- signature: signature.signature
2128
- }, key, options);
1651
+ const { signatures, payload } = jws;
1652
+ if (!Array.isArray(signatures) || !signatures.every(isObject)) throw new JWSInvalid("JWS Signatures missing or incorrect type");
1653
+ let shared;
1654
+ try {
1655
+ if (payload === void 0) throw new Error();
1656
+ shared = prepareVerify(options);
1657
+ } catch {
1658
+ throw new JWSSignatureVerificationFailed();
1659
+ }
1660
+ for (const signature of signatures) try {
1661
+ const { protected: encodedProtected, header, signature: encodedSignature } = signature;
1662
+ if (encodedProtected === void 0 && header === void 0) throw new Error();
1663
+ if (encodedProtected !== void 0 && typeof encodedProtected !== "string") throw new Error();
1664
+ if (typeof encodedSignature !== "string") throw new Error();
1665
+ if (header !== void 0 && !isObject(header)) throw new Error();
1666
+ return verifyResult(signature, await verifySignature({
1667
+ header,
1668
+ payload,
1669
+ protected: encodedProtected,
1670
+ signature: encodedSignature
1671
+ }, shared, key));
2129
1672
  } catch {}
2130
1673
  throw new JWSSignatureVerificationFailed();
2131
1674
  }
2132
1675
  //#endregion
2133
1676
  //#region node_modules/jose/dist/webapi/lib/jwt_claims_set.js
2134
1677
  const epoch = (date) => Math.floor(date.getTime() / 1e3);
2135
- const minute = 60;
2136
- const hour = minute * 60;
2137
- const day = hour * 24;
2138
- const week = day * 7;
2139
- const year = day * 365.25;
1678
+ const multipliers = {
1679
+ s: 1,
1680
+ m: 60,
1681
+ h: 3600,
1682
+ d: 86400,
1683
+ w: 604800,
1684
+ y: 31557600
1685
+ };
2140
1686
  const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
1687
+ const checkFailed = "check_failed";
2141
1688
  function secs(str) {
2142
1689
  const matched = REGEX.exec(str);
2143
1690
  if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
2144
1691
  const value = parseFloat(matched[2]);
2145
- const unit = matched[3].toLowerCase();
2146
- let numericDate;
2147
- switch (unit) {
2148
- case "sec":
2149
- case "secs":
2150
- case "second":
2151
- case "seconds":
2152
- case "s":
2153
- numericDate = Math.round(value);
2154
- break;
2155
- case "minute":
2156
- case "minutes":
2157
- case "min":
2158
- case "mins":
2159
- case "m":
2160
- numericDate = Math.round(value * minute);
2161
- break;
2162
- case "hour":
2163
- case "hours":
2164
- case "hr":
2165
- case "hrs":
2166
- case "h":
2167
- numericDate = Math.round(value * hour);
2168
- break;
2169
- case "day":
2170
- case "days":
2171
- case "d":
2172
- numericDate = Math.round(value * day);
2173
- break;
2174
- case "week":
2175
- case "weeks":
2176
- case "w":
2177
- numericDate = Math.round(value * week);
2178
- break;
2179
- default:
2180
- numericDate = Math.round(value * year);
2181
- break;
2182
- }
1692
+ const numericDate = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
2183
1693
  if (matched[1] === "-" || matched[4] === "ago") return -numericDate;
2184
1694
  return numericDate;
2185
1695
  }
@@ -2187,62 +1697,71 @@ function validateInput(label, input) {
2187
1697
  if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
2188
1698
  return input;
2189
1699
  }
1700
+ function numericDate(value, label) {
1701
+ if (typeof value === "number") return validateInput(label, value);
1702
+ if (value instanceof Date) return validateInput(label, epoch(value));
1703
+ return epoch(/* @__PURE__ */ new Date()) + secs(value);
1704
+ }
2190
1705
  const normalizeTyp = (value) => {
2191
1706
  if (value.includes("/")) return value.toLowerCase();
2192
1707
  return `application/${value.toLowerCase()}`;
2193
1708
  };
2194
1709
  const checkAudiencePresence = (audPayload, audOption) => {
2195
1710
  if (typeof audPayload === "string") return audOption.includes(audPayload);
2196
- if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
1711
+ if (Array.isArray(audPayload)) return audOption.some((aud) => audPayload.includes(aud));
2197
1712
  return false;
2198
1713
  };
1714
+ function validateNumericDate(payload, claim, required = false) {
1715
+ const value = payload[claim];
1716
+ if (value === void 0 && !required) return void 0;
1717
+ if (typeof value !== "number") throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid");
1718
+ return value;
1719
+ }
1720
+ function unexpectedClaim(payload, claim) {
1721
+ throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed);
1722
+ }
2199
1723
  function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
2200
1724
  let payload;
2201
1725
  try {
2202
- payload = JSON.parse(decoder.decode(encodedPayload));
1726
+ payload = JSON.parse(strictDecoder.decode(encodedPayload));
2203
1727
  } catch {}
2204
1728
  if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
2205
1729
  const { typ } = options;
2206
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed");
1730
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", checkFailed);
2207
1731
  const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
2208
1732
  const presenceCheck = [...requiredClaims];
2209
1733
  if (maxTokenAge !== void 0) presenceCheck.push("iat");
2210
1734
  if (audience !== void 0) presenceCheck.push("aud");
2211
1735
  if (subject !== void 0) presenceCheck.push("sub");
2212
- if (issuer !== void 0) presenceCheck.push("iss");
2213
- for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
2214
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed");
2215
- if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed");
2216
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed");
2217
- let tolerance;
2218
- switch (typeof options.clockTolerance) {
2219
- case "string":
2220
- tolerance = secs(options.clockTolerance);
2221
- break;
2222
- case "number":
2223
- tolerance = options.clockTolerance;
2224
- break;
2225
- case "undefined":
2226
- tolerance = 0;
2227
- break;
2228
- default: throw new TypeError("Invalid clockTolerance option type");
2229
- }
1736
+ if (issuer !== void 0) presenceCheck.push("iss");
1737
+ for (const claim of new Set(presenceCheck.reverse())) if (!Object.hasOwn(payload, claim)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
1738
+ if (issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) unexpectedClaim(payload, "iss");
1739
+ if (subject !== void 0 && payload.sub !== subject) unexpectedClaim(payload, "sub");
1740
+ if (audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) unexpectedClaim(payload, "aud");
1741
+ const { clockTolerance } = options;
1742
+ let tolerance = 0;
1743
+ if (typeof clockTolerance === "string") tolerance = secs(clockTolerance);
1744
+ else if (clockTolerance !== void 0) {
1745
+ if (typeof clockTolerance !== "number") throw new TypeError("Invalid clockTolerance option type");
1746
+ tolerance = clockTolerance;
1747
+ }
1748
+ validateInput("clockTolerance option", tolerance);
2230
1749
  const { currentDate } = options;
2231
- const now = epoch(currentDate || /* @__PURE__ */ new Date());
2232
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid");
2233
- if (payload.nbf !== void 0) {
2234
- if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid");
2235
- if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed");
2236
- }
2237
- if (payload.exp !== void 0) {
2238
- if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid");
2239
- if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed");
2240
- }
2241
- if (maxTokenAge) {
2242
- const age = now - payload.iat;
1750
+ const now = validateInput("currentDate option", epoch(currentDate || /* @__PURE__ */ new Date()));
1751
+ const iat = validateNumericDate(payload, "iat", maxTokenAge !== void 0);
1752
+ const nbf = validateNumericDate(payload, "nbf");
1753
+ if (nbf !== void 0) {
1754
+ if (nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", checkFailed);
1755
+ }
1756
+ const exp = validateNumericDate(payload, "exp");
1757
+ if (exp !== void 0) {
1758
+ if (exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", checkFailed);
1759
+ }
1760
+ if (maxTokenAge !== void 0) {
1761
+ const age = now - iat;
2243
1762
  const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
2244
- if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed");
2245
- if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed");
1763
+ if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", checkFailed);
1764
+ if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", checkFailed);
2246
1765
  }
2247
1766
  return payload;
2248
1767
  }
@@ -2277,43 +1796,38 @@ var JWTClaimsBuilder = class {
2277
1796
  this.#payload.jti = value;
2278
1797
  }
2279
1798
  set nbf(value) {
2280
- if (typeof value === "number") this.#payload.nbf = validateInput("setNotBefore", value);
2281
- else if (value instanceof Date) this.#payload.nbf = validateInput("setNotBefore", epoch(value));
2282
- else this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
1799
+ this.#payload.nbf = numericDate(value, "setNotBefore");
2283
1800
  }
2284
1801
  set exp(value) {
2285
- if (typeof value === "number") this.#payload.exp = validateInput("setExpirationTime", value);
2286
- else if (value instanceof Date) this.#payload.exp = validateInput("setExpirationTime", epoch(value));
2287
- else this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
1802
+ this.#payload.exp = numericDate(value, "setExpirationTime");
2288
1803
  }
2289
1804
  set iat(value) {
2290
1805
  if (value === void 0) this.#payload.iat = epoch(/* @__PURE__ */ new Date());
2291
- else if (value instanceof Date) this.#payload.iat = validateInput("setIssuedAt", epoch(value));
2292
1806
  else if (typeof value === "string") this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
2293
- else this.#payload.iat = validateInput("setIssuedAt", value);
1807
+ else this.#payload.iat = numericDate(value, "setIssuedAt");
2294
1808
  }
2295
1809
  };
2296
1810
  //#endregion
2297
1811
  //#region node_modules/jose/dist/webapi/jwt/verify.js
2298
1812
  async function jwtVerify(jwt, key, options) {
2299
- const verified = await compactVerify(jwt, key, options);
2300
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1813
+ const verified = await verifyCompact(jwt, prepareVerify(options), key);
1814
+ if (!verified[2]) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
2301
1815
  const result = {
2302
- payload: validateClaimsSet(verified.protectedHeader, verified.payload, options),
2303
- protectedHeader: verified.protectedHeader
1816
+ payload: validateClaimsSet(verified[1], verified[0], options),
1817
+ protectedHeader: verified[1]
2304
1818
  };
2305
1819
  if (typeof key === "function") return {
2306
1820
  ...result,
2307
- key: verified.key
1821
+ key: verified[3]
2308
1822
  };
2309
1823
  return result;
2310
1824
  }
2311
1825
  //#endregion
2312
1826
  //#region node_modules/jose/dist/webapi/jwt/decrypt.js
2313
1827
  async function jwtDecrypt(jwt, key, options) {
2314
- const decrypted = await compactDecrypt(jwt, key, options);
2315
- const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options);
2316
- const { protectedHeader } = decrypted;
1828
+ const decrypted = await decryptCompact(jwt, prepareDecrypt(options), key);
1829
+ const protectedHeader = decrypted[1];
1830
+ const payload = validateClaimsSet(protectedHeader, decrypted[0], options);
2317
1831
  if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) throw new JWTClaimValidationFailed("replicated \"iss\" claim header parameter mismatch", payload, "iss", "mismatch");
2318
1832
  if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) throw new JWTClaimValidationFailed("replicated \"sub\" claim header parameter mismatch", payload, "sub", "mismatch");
2319
1833
  if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) throw new JWTClaimValidationFailed("replicated \"aud\" claim header parameter mismatch", payload, "aud", "mismatch");
@@ -2323,7 +1837,7 @@ async function jwtDecrypt(jwt, key, options) {
2323
1837
  };
2324
1838
  if (typeof key === "function") return {
2325
1839
  ...result,
2326
- key: decrypted.key
1840
+ key: decrypted[2]
2327
1841
  };
2328
1842
  return result;
2329
1843
  }
@@ -2362,6 +1876,59 @@ var CompactEncrypt = class {
2362
1876
  }
2363
1877
  };
2364
1878
  //#endregion
1879
+ //#region node_modules/jose/dist/webapi/lib/jws_sign.js
1880
+ function unencodedPayload(protectedHeader) {
1881
+ return protectedHeader?.b64 === false && Array.isArray(protectedHeader.crit) && protectedHeader.crit.includes("b64");
1882
+ }
1883
+ async function createSignature(input, key) {
1884
+ const { protectedHeader, unprotectedHeader } = input;
1885
+ if (!protectedHeader && !unprotectedHeader) throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
1886
+ if (!isDisjoint(protectedHeader, unprotectedHeader)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1887
+ const joseHeader = {
1888
+ ...protectedHeader,
1889
+ ...unprotectedHeader
1890
+ };
1891
+ validateCritDuplicates(JWSInvalid, protectedHeader);
1892
+ const extensions = validateCrit(JWSInvalid, JWS_RECOGNIZED, input.crit, protectedHeader, joseHeader);
1893
+ let b64 = true;
1894
+ if (extensions.includes("b64")) {
1895
+ b64 = protectedHeader.b64;
1896
+ if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
1897
+ }
1898
+ const { alg } = joseHeader;
1899
+ if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
1900
+ const entry = jwsAlgorithm(alg);
1901
+ let payloadS;
1902
+ let payloadB;
1903
+ if (b64) {
1904
+ const encoded = input.encoded ??= [];
1905
+ encoded[0] ??= encode(input.payload);
1906
+ encoded[1] ??= encode$1(encoded[0]);
1907
+ payloadS = encoded[0];
1908
+ payloadB = encoded[1];
1909
+ } else {
1910
+ payloadB = input.payload;
1911
+ payloadS = "";
1912
+ }
1913
+ let protectedHeaderString;
1914
+ let protectedHeaderBytes;
1915
+ if (protectedHeader) {
1916
+ protectedHeaderString = encode(JSON.stringify(protectedHeader));
1917
+ protectedHeaderBytes = encode$1(protectedHeaderString);
1918
+ } else {
1919
+ protectedHeaderString = "";
1920
+ protectedHeaderBytes = /* @__PURE__ */ new Uint8Array();
1921
+ }
1922
+ const data = concat(protectedHeaderBytes, encode$1("."), payloadB);
1923
+ const jws = {
1924
+ signature: encode(await sign(entry, await prepareKey(entry, key, "sign"), data)),
1925
+ payload: payloadS
1926
+ };
1927
+ if (protectedHeader) jws.protected = protectedHeaderString;
1928
+ if (unprotectedHeader) jws.header = unprotectedHeader;
1929
+ return jws;
1930
+ }
1931
+ //#endregion
2365
1932
  //#region node_modules/jose/dist/webapi/jws/flattened/sign.js
2366
1933
  var FlattenedSign = class {
2367
1934
  #payload;
@@ -2382,63 +1949,30 @@ var FlattenedSign = class {
2382
1949
  return this;
2383
1950
  }
2384
1951
  async sign(key, options) {
2385
- if (!this.#protectedHeader && !this.#unprotectedHeader) throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
2386
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
2387
- const joseHeader = {
2388
- ...this.#protectedHeader,
2389
- ...this.#unprotectedHeader
2390
- };
2391
- const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
2392
- let b64 = true;
2393
- if (extensions.has("b64")) {
2394
- b64 = this.#protectedHeader.b64;
2395
- if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
2396
- }
2397
- const { alg } = joseHeader;
2398
- if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
2399
- checkKeyType(alg, key, "sign");
2400
- let payloadS;
2401
- let payloadB;
2402
- if (b64) {
2403
- payloadS = encode(this.#payload);
2404
- payloadB = encode$1(payloadS);
2405
- } else {
2406
- payloadB = this.#payload;
2407
- payloadS = "";
2408
- }
2409
- let protectedHeaderString;
2410
- let protectedHeaderBytes;
2411
- if (this.#protectedHeader) {
2412
- protectedHeaderString = encode(JSON.stringify(this.#protectedHeader));
2413
- protectedHeaderBytes = encode$1(protectedHeaderString);
2414
- } else {
2415
- protectedHeaderString = "";
2416
- protectedHeaderBytes = /* @__PURE__ */ new Uint8Array();
2417
- }
2418
- const data = concat(protectedHeaderBytes, encode$1("."), payloadB);
2419
- const jws = {
2420
- signature: encode(await sign(alg, await normalizeKey(key, alg), data)),
2421
- payload: payloadS
2422
- };
2423
- if (this.#unprotectedHeader) jws.header = this.#unprotectedHeader;
2424
- if (this.#protectedHeader) jws.protected = protectedHeaderString;
2425
- return jws;
1952
+ return createSignature({
1953
+ payload: this.#payload,
1954
+ protectedHeader: this.#protectedHeader,
1955
+ unprotectedHeader: this.#unprotectedHeader,
1956
+ crit: options?.crit
1957
+ }, key);
2426
1958
  }
2427
1959
  };
2428
1960
  //#endregion
2429
1961
  //#region node_modules/jose/dist/webapi/jws/compact/sign.js
2430
1962
  var CompactSign = class {
2431
1963
  #flattened;
1964
+ #protectedHeader;
2432
1965
  constructor(payload) {
2433
1966
  this.#flattened = new FlattenedSign(payload);
2434
1967
  }
2435
1968
  setProtectedHeader(protectedHeader) {
2436
1969
  this.#flattened.setProtectedHeader(protectedHeader);
1970
+ this.#protectedHeader = protectedHeader;
2437
1971
  return this;
2438
1972
  }
2439
1973
  async sign(key, options) {
1974
+ if (unencodedPayload(this.#protectedHeader)) throw new TypeError("use the flattened module for creating JWS with b64: false");
2440
1975
  const jws = await this.#flattened.sign(key, options);
2441
- if (jws.payload === void 0) throw new TypeError("use the flattened module for creating JWS with b64: false");
2442
1976
  return `${jws.protected}.${jws.payload}.${jws.signature}`;
2443
1977
  }
2444
1978
  };
@@ -2446,23 +1980,24 @@ var CompactSign = class {
2446
1980
  //#region node_modules/jose/dist/webapi/jws/general/sign.js
2447
1981
  var IndividualSignature = class {
2448
1982
  #parent;
2449
- protectedHeader;
2450
- unprotectedHeader;
2451
- options;
2452
- key;
1983
+ state;
2453
1984
  constructor(sig, key, options) {
2454
1985
  this.#parent = sig;
2455
- this.key = key;
2456
- this.options = options;
1986
+ this.state = [
1987
+ void 0,
1988
+ void 0,
1989
+ key,
1990
+ options?.crit
1991
+ ];
2457
1992
  }
2458
1993
  setProtectedHeader(protectedHeader) {
2459
- assertNotSet(this.protectedHeader, "setProtectedHeader");
2460
- this.protectedHeader = protectedHeader;
1994
+ assertNotSet(this.state[0], "setProtectedHeader");
1995
+ this.state[0] = protectedHeader;
2461
1996
  return this;
2462
1997
  }
2463
1998
  setUnprotectedHeader(unprotectedHeader) {
2464
- assertNotSet(this.unprotectedHeader, "setUnprotectedHeader");
2465
- this.unprotectedHeader = unprotectedHeader;
1999
+ assertNotSet(this.state[1], "setUnprotectedHeader");
2000
+ this.state[1] = unprotectedHeader;
2466
2001
  return this;
2467
2002
  }
2468
2003
  addSignature(...args) {
@@ -2488,16 +2023,21 @@ var GeneralSign = class {
2488
2023
  }
2489
2024
  async sign() {
2490
2025
  if (!this.#signatures.length) throw new JWSInvalid("at least one signature must be added");
2026
+ if (!(this.#payload instanceof Uint8Array)) throw new TypeError("payload must be an instance of Uint8Array");
2491
2027
  const jws = {
2492
2028
  signatures: [],
2493
2029
  payload: ""
2494
2030
  };
2031
+ const encoded = [];
2495
2032
  for (let i = 0; i < this.#signatures.length; i++) {
2496
- const signature = this.#signatures[i];
2497
- const flattened = new FlattenedSign(this.#payload);
2498
- flattened.setProtectedHeader(signature.protectedHeader);
2499
- flattened.setUnprotectedHeader(signature.unprotectedHeader);
2500
- const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
2033
+ const [protectedHeader, unprotectedHeader, key, crit] = this.#signatures[i].state;
2034
+ const { payload, ...rest } = await createSignature({
2035
+ payload: this.#payload,
2036
+ protectedHeader,
2037
+ unprotectedHeader,
2038
+ crit,
2039
+ encoded
2040
+ }, key);
2501
2041
  if (i === 0) jws.payload = payload;
2502
2042
  else if (jws.payload !== payload) throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");
2503
2043
  jws.signatures.push(rest);
@@ -2548,7 +2088,7 @@ var SignJWT = class {
2548
2088
  async sign(key, options) {
2549
2089
  const sig = new CompactSign(this.#jwt.data());
2550
2090
  sig.setProtectedHeader(this.#protectedHeader);
2551
- if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
2091
+ if (unencodedPayload(this.#protectedHeader)) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
2552
2092
  return sig.sign(key, options);
2553
2093
  }
2554
2094
  };
@@ -2642,6 +2182,213 @@ var EncryptJWT = class {
2642
2182
  }
2643
2183
  };
2644
2184
  //#endregion
2185
+ //#region node_modules/jose/dist/webapi/lib/key_algorithm.js
2186
+ const algArgument = "\"alg\" (Algorithm)";
2187
+ function unsupportedAlg(source = "JWK \"alg\" (Algorithm) Parameter") {
2188
+ throw new JOSENotSupported(`Invalid or unsupported ${source} value`);
2189
+ }
2190
+ function keyAlgorithm(alg, source) {
2191
+ return (typeof alg === "string" ? JWS[alg] ?? JWE[alg] : void 0) ?? unsupportedAlg(source);
2192
+ }
2193
+ //#endregion
2194
+ //#region node_modules/jose/dist/webapi/lib/asn1.js
2195
+ const formatPEM = (b64, descriptor) => {
2196
+ return `-----BEGIN ${descriptor}-----\n${(b64.match(/.{1,64}/g) || []).join("\n")}\n-----END ${descriptor}-----`;
2197
+ };
2198
+ const genericExport = async (keyType, keyFormat, key) => {
2199
+ if (isKeyObject(key)) {
2200
+ if (key.type !== keyType) throw new TypeError(`key is not a ${keyType} key`);
2201
+ return key.export({
2202
+ format: "pem",
2203
+ type: keyFormat
2204
+ });
2205
+ }
2206
+ if (!isCryptoKey(key)) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject"));
2207
+ if (!key.extractable) throw new TypeError("CryptoKey is not extractable");
2208
+ if (key.type !== keyType) throw new TypeError(`key is not a ${keyType} key`);
2209
+ return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
2210
+ };
2211
+ const toSPKI = (key) => genericExport("public", "spki", key);
2212
+ const toPKCS8 = (key) => genericExport("private", "pkcs8", key);
2213
+ const bytesEqual = (a, b) => {
2214
+ if (a.byteLength !== b.length) return false;
2215
+ for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false;
2216
+ return true;
2217
+ };
2218
+ const createASN1State = (data) => ({
2219
+ data,
2220
+ pos: 0
2221
+ });
2222
+ const readByte = (state) => {
2223
+ const byte = state.data[state.pos++];
2224
+ if (byte === void 0) throw new Error("Unexpected end of ASN.1 input");
2225
+ return byte;
2226
+ };
2227
+ const parseLength = (state) => {
2228
+ const first = readByte(state);
2229
+ if (first & 128) {
2230
+ const lengthOfLen = first & 127;
2231
+ let length = 0;
2232
+ for (let i = 0; i < lengthOfLen; i++) length = length << 8 | readByte(state);
2233
+ return length;
2234
+ }
2235
+ return first;
2236
+ };
2237
+ const skipElement = (state, count = 1) => {
2238
+ while (count-- > 0) {
2239
+ state.pos++;
2240
+ const length = parseLength(state);
2241
+ state.pos += length;
2242
+ }
2243
+ };
2244
+ const expectTag = (state, expectedTag, errorMessage) => {
2245
+ if (readByte(state) !== expectedTag) throw new Error(errorMessage);
2246
+ };
2247
+ const getSubarray = (state, length) => {
2248
+ if (length < 0 || state.pos + length > state.data.length) throw new Error("Unexpected end of ASN.1 input");
2249
+ const result = state.data.subarray(state.pos, state.pos + length);
2250
+ state.pos += length;
2251
+ return result;
2252
+ };
2253
+ const parseAlgorithmOID = (state) => {
2254
+ expectTag(state, 6, "Expected algorithm OID");
2255
+ const oidLen = parseLength(state);
2256
+ return getSubarray(state, oidLen);
2257
+ };
2258
+ function parseKeyHeader(state, keyFormat) {
2259
+ expectTag(state, 48, `Invalid ${keyFormat === "spki" ? "SPKI" : "PKCS#8"} structure`);
2260
+ parseLength(state);
2261
+ if (keyFormat === "pkcs8") {
2262
+ expectTag(state, 2, "Expected version field");
2263
+ const length = parseLength(state);
2264
+ state.pos += length;
2265
+ }
2266
+ expectTag(state, 48, "Expected algorithm identifier");
2267
+ parseLength(state);
2268
+ }
2269
+ const parseECAlgorithmIdentifier = (state) => {
2270
+ const algOid = parseAlgorithmOID(state);
2271
+ if (bytesEqual(algOid, [
2272
+ 43,
2273
+ 101,
2274
+ 110
2275
+ ])) return "X25519";
2276
+ if (!bytesEqual(algOid, [
2277
+ 42,
2278
+ 134,
2279
+ 72,
2280
+ 206,
2281
+ 61,
2282
+ 2,
2283
+ 1
2284
+ ])) throw new Error("Unsupported key algorithm");
2285
+ expectTag(state, 6, "Expected curve OID");
2286
+ const curveOidLen = parseLength(state);
2287
+ const curveOid = getSubarray(state, curveOidLen);
2288
+ if (bytesEqual(curveOid, [
2289
+ 42,
2290
+ 134,
2291
+ 72,
2292
+ 206,
2293
+ 61,
2294
+ 3,
2295
+ 1,
2296
+ 7
2297
+ ])) return "P-256";
2298
+ if (bytesEqual(curveOid, [
2299
+ 43,
2300
+ 129,
2301
+ 4,
2302
+ 0,
2303
+ 34
2304
+ ])) return "P-384";
2305
+ if (bytesEqual(curveOid, [
2306
+ 43,
2307
+ 129,
2308
+ 4,
2309
+ 0,
2310
+ 35
2311
+ ])) return "P-521";
2312
+ throw new Error("Unsupported named curve");
2313
+ };
2314
+ const genericImport = async (keyFormat, keyData, alg, options) => {
2315
+ const entry = keyAlgorithm(alg, algArgument);
2316
+ if (entry.secret) unsupportedAlg(algArgument);
2317
+ const isPublic = keyFormat === "spki";
2318
+ let algorithm;
2319
+ if (entry.resolve) try {
2320
+ const state = createASN1State(keyData);
2321
+ parseKeyHeader(state, keyFormat);
2322
+ algorithm = entry.resolve({ crv: parseECAlgorithmIdentifier(state) });
2323
+ } catch {
2324
+ throw new JOSENotSupported("Invalid or unsupported key format");
2325
+ }
2326
+ else algorithm = entry.subtle;
2327
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? isPublic, entry.usages[isPublic ? 0 : 1]);
2328
+ };
2329
+ const processPEMData = (pem, pattern) => {
2330
+ return decodeBase64(pem.replace(pattern, ""));
2331
+ };
2332
+ const fromPKCS8 = (pem, alg, options) => {
2333
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
2334
+ return genericImport("pkcs8", keyData, alg, options);
2335
+ };
2336
+ const fromSPKI = (pem, alg, options) => {
2337
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);
2338
+ return genericImport("spki", keyData, alg, options);
2339
+ };
2340
+ function spkiFromX509(buf) {
2341
+ const state = createASN1State(buf);
2342
+ expectTag(state, 48, "Invalid certificate structure");
2343
+ parseLength(state);
2344
+ expectTag(state, 48, "Invalid tbsCertificate structure");
2345
+ parseLength(state);
2346
+ if (buf[state.pos] === 160) skipElement(state, 6);
2347
+ else skipElement(state, 5);
2348
+ const spkiStart = state.pos;
2349
+ expectTag(state, 48, "Invalid SPKI structure");
2350
+ const spkiContentLen = parseLength(state);
2351
+ return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));
2352
+ }
2353
+ const fromX509 = (pem, alg, options) => {
2354
+ let spki;
2355
+ try {
2356
+ spki = spkiFromX509(processPEMData(pem, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g));
2357
+ } catch (cause) {
2358
+ throw new TypeError("Failed to parse the X.509 certificate", { cause });
2359
+ }
2360
+ return genericImport("spki", spki, alg, options);
2361
+ };
2362
+ //#endregion
2363
+ //#region node_modules/jose/dist/webapi/key/export.js
2364
+ function omitUndefinedProperties(jwk) {
2365
+ return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== void 0));
2366
+ }
2367
+ async function keyToJWK(key) {
2368
+ if (isKeyObject(key)) {
2369
+ if (key.type === "secret") key = key.export();
2370
+ else return key.export({ format: "jwk" });
2371
+ }
2372
+ if (key instanceof Uint8Array) return {
2373
+ kty: "oct",
2374
+ k: encode(key)
2375
+ };
2376
+ if (!isCryptoKey(key)) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
2377
+ if (!key.extractable) throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
2378
+ const { ext, key_ops, alg, use, ...jwk } = omitUndefinedProperties(await crypto.subtle.exportKey("jwk", key));
2379
+ if (jwk.kty === "AKP") jwk.alg = alg;
2380
+ return jwk;
2381
+ }
2382
+ function exportSPKI(key) {
2383
+ return toSPKI(key);
2384
+ }
2385
+ function exportPKCS8(key) {
2386
+ return toPKCS8(key);
2387
+ }
2388
+ function exportJWK(key) {
2389
+ return keyToJWK(key);
2390
+ }
2391
+ //#endregion
2645
2392
  //#region node_modules/jose/dist/webapi/jwk/thumbprint.js
2646
2393
  const check = (value, description) => {
2647
2394
  if (typeof value !== "string" || !value) throw new JWKInvalid(`${description} missing or invalid`);
@@ -2718,32 +2465,26 @@ async function EmbeddedJWK(protectedHeader, token) {
2718
2465
  ...token?.header
2719
2466
  };
2720
2467
  if (!isObject(joseHeader.jwk)) throw new JWSInvalid("\"jwk\" (JSON Web Key) Header Parameter must be a JSON object");
2721
- const key = await importJWK({
2468
+ const key = await jwkToKey(jwsAlgorithm(joseHeader.alg), {
2722
2469
  ...joseHeader.jwk,
2723
2470
  ext: true
2724
- }, joseHeader.alg);
2725
- if (key instanceof Uint8Array || key.type !== "public") throw new JWSInvalid("\"jwk\" (JSON Web Key) Header Parameter must be a public key");
2471
+ });
2472
+ if (key.type !== "public") throw new JWSInvalid("\"jwk\" (JSON Web Key) Header Parameter must be a public key");
2726
2473
  return key;
2727
2474
  }
2728
2475
  //#endregion
2729
2476
  //#region node_modules/jose/dist/webapi/jwks/local.js
2730
- function getKtyFromAlg(alg) {
2731
- switch (typeof alg === "string" && alg.slice(0, 2)) {
2732
- case "RS":
2733
- case "PS": return "RSA";
2734
- case "ES": return "EC";
2735
- case "Ed": return "OKP";
2736
- case "ML": return "AKP";
2737
- default: throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
2738
- }
2477
+ function signatureAlgorithm(alg) {
2478
+ const entry = typeof alg === "string" ? JWS[alg] : void 0;
2479
+ if (!entry || entry.secret) throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
2480
+ return entry;
2739
2481
  }
2740
2482
  function isJWKSLike(jwks) {
2741
- return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
2483
+ if (!jwks || typeof jwks !== "object") return false;
2484
+ const { keys } = jwks;
2485
+ return Array.isArray(keys) && keys.every(isObject);
2742
2486
  }
2743
- function isJWKLike(key) {
2744
- return isObject(key);
2745
- }
2746
- var LocalJWKSet = class {
2487
+ var LocalJWKSetImpl = class {
2747
2488
  #jwks;
2748
2489
  #cached = /* @__PURE__ */ new WeakMap();
2749
2490
  constructor(jwks) {
@@ -2758,30 +2499,8 @@ var LocalJWKSet = class {
2758
2499
  ...protectedHeader,
2759
2500
  ...token?.header
2760
2501
  };
2761
- const kty = getKtyFromAlg(alg);
2762
- const candidates = this.#jwks.keys.filter((jwk) => {
2763
- let candidate = kty === jwk.kty;
2764
- if (candidate && typeof kid === "string") candidate = kid === jwk.kid;
2765
- if (candidate && (typeof jwk.alg === "string" || kty === "AKP")) candidate = alg === jwk.alg;
2766
- if (candidate && typeof jwk.use === "string") candidate = jwk.use === "sig";
2767
- if (candidate && Array.isArray(jwk.key_ops)) candidate = jwk.key_ops.includes("verify");
2768
- if (candidate) switch (alg) {
2769
- case "ES256":
2770
- candidate = jwk.crv === "P-256";
2771
- break;
2772
- case "ES384":
2773
- candidate = jwk.crv === "P-384";
2774
- break;
2775
- case "ES512":
2776
- candidate = jwk.crv === "P-521";
2777
- break;
2778
- case "Ed25519":
2779
- case "EdDSA":
2780
- candidate = jwk.crv === "Ed25519";
2781
- break;
2782
- }
2783
- return candidate;
2784
- });
2502
+ const entry = signatureAlgorithm(alg);
2503
+ const candidates = this.#jwks.keys.filter((jwk) => entry.kty.includes(jwk.kty) && (typeof kid !== "string" || kid === jwk.kid) && (!(typeof jwk.alg === "string" || jwk.kty === "AKP") || alg === jwk.alg) && (typeof jwk.use !== "string" || jwk.use === "sig") && (!Array.isArray(jwk.key_ops) || jwk.key_ops.includes("verify")) && (!entry.crv || jwk.crv === entry.crv));
2785
2504
  const { 0: jwk, length } = candidates;
2786
2505
  if (length === 0) throw new JWKSNoMatchingKey();
2787
2506
  if (length !== 1) {
@@ -2789,35 +2508,31 @@ var LocalJWKSet = class {
2789
2508
  const _cached = this.#cached;
2790
2509
  error[Symbol.asyncIterator] = async function* () {
2791
2510
  for (const jwk of candidates) try {
2792
- yield await importWithAlgCache(_cached, jwk, alg);
2511
+ yield await importWithAlgCache(_cached, jwk, entry);
2793
2512
  } catch {}
2794
2513
  };
2795
2514
  throw error;
2796
2515
  }
2797
- return importWithAlgCache(this.#cached, jwk, alg);
2516
+ return importWithAlgCache(this.#cached, jwk, entry);
2798
2517
  }
2799
2518
  };
2800
- async function importWithAlgCache(cache, jwk, alg) {
2801
- const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
2802
- if (cached[alg] === void 0) {
2803
- const key = await importJWK({
2519
+ async function importWithAlgCache(cache, jwk, entry) {
2520
+ const cached = cache.get(jwk) || cache.set(jwk, { __proto__: null }).get(jwk);
2521
+ if (cached[entry.alg] === void 0) {
2522
+ const key = await jwkToKey(entry, {
2804
2523
  ...jwk,
2524
+ alg: entry.alg,
2805
2525
  ext: true
2806
- }, alg);
2807
- if (key instanceof Uint8Array || key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys");
2808
- cached[alg] = key;
2526
+ });
2527
+ if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys");
2528
+ cached[entry.alg] = key;
2809
2529
  }
2810
- return cached[alg];
2530
+ return cached[entry.alg];
2811
2531
  }
2812
2532
  function createLocalJWKSet(jwks) {
2813
- const set = new LocalJWKSet(jwks);
2533
+ const set = new LocalJWKSetImpl(jwks);
2814
2534
  const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
2815
- Object.defineProperties(localJWKSet, { jwks: {
2816
- value: () => structuredClone(set.jwks()),
2817
- enumerable: false,
2818
- configurable: false,
2819
- writable: false
2820
- } });
2535
+ Object.defineProperty(localJWKSet, "jwks", { value: () => structuredClone(set.jwks()) });
2821
2536
  return localJWKSet;
2822
2537
  }
2823
2538
  //#endregion
@@ -2826,7 +2541,7 @@ function isCloudflareWorkers() {
2826
2541
  return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
2827
2542
  }
2828
2543
  let USER_AGENT;
2829
- if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.2.3`;
2544
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.2.8`;
2830
2545
  const customFetch = Symbol();
2831
2546
  async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
2832
2547
  const response = await fetchImpl(url, {
@@ -2852,7 +2567,7 @@ function isFreshJwksCache(input, cacheMaxAge) {
2852
2567
  if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) return false;
2853
2568
  return true;
2854
2569
  }
2855
- var RemoteJWKSet = class {
2570
+ var RemoteJWKSetImpl = class {
2856
2571
  #url;
2857
2572
  #timeoutDuration;
2858
2573
  #cooldownDuration;
@@ -2866,19 +2581,21 @@ var RemoteJWKSet = class {
2866
2581
  constructor(url, options) {
2867
2582
  if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL");
2868
2583
  this.#url = new URL(url.href);
2869
- this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
2870
- this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
2871
- this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
2872
- this.#headers = new Headers(options?.headers);
2584
+ const opts = options ?? {};
2585
+ this.#timeoutDuration = typeof opts.timeoutDuration === "number" ? opts.timeoutDuration : 5e3;
2586
+ this.#cooldownDuration = typeof opts.cooldownDuration === "number" ? opts.cooldownDuration : 3e4;
2587
+ this.#cacheMaxAge = typeof opts.cacheMaxAge === "number" ? opts.cacheMaxAge : 6e5;
2588
+ this.#headers = new Headers(opts.headers);
2873
2589
  if (USER_AGENT && !this.#headers.has("User-Agent")) this.#headers.set("User-Agent", USER_AGENT);
2874
2590
  if (!this.#headers.has("accept")) {
2875
2591
  this.#headers.set("accept", "application/json");
2876
2592
  this.#headers.append("accept", "application/jwk-set+json");
2877
2593
  }
2878
- this.#customFetch = options?.[customFetch];
2879
- if (options?.[jwksCache] !== void 0) {
2880
- this.#cache = options?.[jwksCache];
2881
- if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
2594
+ this.#customFetch = opts[customFetch];
2595
+ const cache = opts[jwksCache];
2596
+ if (cache !== void 0) {
2597
+ this.#cache = cache;
2598
+ if (isFreshJwksCache(cache, this.#cacheMaxAge)) {
2882
2599
  this.#jwksTimestamp = this.#cache.uat;
2883
2600
  this.#local = createLocalJWKSet(this.#cache.jwks);
2884
2601
  }
@@ -2887,11 +2604,14 @@ var RemoteJWKSet = class {
2887
2604
  pendingFetch() {
2888
2605
  return !!this.#pendingFetch;
2889
2606
  }
2607
+ #validFor(duration) {
2608
+ return typeof this.#jwksTimestamp === "number" && Date.now() < this.#jwksTimestamp + duration;
2609
+ }
2890
2610
  coolingDown() {
2891
- return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false;
2611
+ return this.#validFor(this.#cooldownDuration);
2892
2612
  }
2893
2613
  fresh() {
2894
- return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false;
2614
+ return this.#validFor(this.#cacheMaxAge);
2895
2615
  }
2896
2616
  jwks() {
2897
2617
  return this.#local?.jwks();
@@ -2919,44 +2639,35 @@ var RemoteJWKSet = class {
2919
2639
  this.#cache.jwks = json;
2920
2640
  }
2921
2641
  this.#jwksTimestamp = Date.now();
2642
+ }).finally(() => {
2922
2643
  this.#pendingFetch = void 0;
2923
- }).catch((err) => {
2924
- this.#pendingFetch = void 0;
2925
- throw err;
2926
2644
  });
2927
2645
  await this.#pendingFetch;
2928
2646
  }
2929
2647
  };
2930
2648
  function createRemoteJWKSet(url, options) {
2931
- const set = new RemoteJWKSet(url, options);
2649
+ const set = new RemoteJWKSetImpl(url, options);
2932
2650
  const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
2933
2651
  Object.defineProperties(remoteJWKSet, {
2934
2652
  coolingDown: {
2935
2653
  get: () => set.coolingDown(),
2936
- enumerable: true,
2937
- configurable: false
2654
+ enumerable: true
2938
2655
  },
2939
2656
  fresh: {
2940
2657
  get: () => set.fresh(),
2941
- enumerable: true,
2942
- configurable: false
2658
+ enumerable: true
2943
2659
  },
2944
2660
  reload: {
2945
2661
  value: () => set.reload(),
2946
- enumerable: true,
2947
- configurable: false,
2948
- writable: false
2662
+ enumerable: true
2949
2663
  },
2950
2664
  reloading: {
2951
2665
  get: () => set.pendingFetch(),
2952
- enumerable: true,
2953
- configurable: false
2666
+ enumerable: true
2954
2667
  },
2955
2668
  jwks: {
2956
2669
  value: () => set.jwks(),
2957
- enumerable: true,
2958
- configurable: false,
2959
- writable: false
2670
+ enumerable: true
2960
2671
  }
2961
2672
  });
2962
2673
  return remoteJWKSet;
@@ -3005,34 +2716,75 @@ var UnsecuredJWT = class {
3005
2716
  if (length !== 3 || signature !== "") throw new JWTInvalid("Invalid Unsecured JWT");
3006
2717
  let header;
3007
2718
  try {
3008
- header = JSON.parse(decoder.decode(decode(encodedHeader)));
2719
+ header = JSON.parse(strictDecoder.decode(decode(encodedHeader)));
3009
2720
  if (header.alg !== "none") throw new Error();
3010
2721
  } catch {
3011
2722
  throw new JWTInvalid("Invalid Unsecured JWT");
3012
2723
  }
3013
2724
  return {
3014
- payload: validateClaimsSet(header, decode(encodedPayload), options),
2725
+ payload: validateClaimsSet(header, decodeBase64url(encodedPayload, "payload", JWTInvalid), options),
3015
2726
  header
3016
2727
  };
3017
2728
  }
3018
2729
  };
3019
2730
  //#endregion
2731
+ //#region node_modules/jose/dist/webapi/key/import.js
2732
+ async function importSPKI(spki, alg, options) {
2733
+ if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) throw new TypeError("\"spki\" must be SPKI formatted string");
2734
+ return fromSPKI(spki, alg, options);
2735
+ }
2736
+ async function importX509(x509, alg, options) {
2737
+ if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) throw new TypeError("\"x509\" must be X.509 formatted string");
2738
+ return fromX509(x509, alg, options);
2739
+ }
2740
+ async function importPKCS8(pkcs8, alg, options) {
2741
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) throw new TypeError("\"pkcs8\" must be PKCS#8 formatted string");
2742
+ return fromPKCS8(pkcs8, alg, options);
2743
+ }
2744
+ async function importJWK(jwk, alg, options) {
2745
+ if (!isObject(jwk)) throw new TypeError("JWK must be an object");
2746
+ alg ??= jwk.alg;
2747
+ const ext = options?.extractable ?? jwk.ext;
2748
+ if (jwk.kty !== "oct" && !alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
2749
+ switch (jwk.kty) {
2750
+ case "oct":
2751
+ if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
2752
+ return decode(jwk.k);
2753
+ case "RSA": return jwkToKey(keyAlgorithm(alg), {
2754
+ ...jwk,
2755
+ alg,
2756
+ ext
2757
+ });
2758
+ case "AKP":
2759
+ if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
2760
+ if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch");
2761
+ return jwkToKey(keyAlgorithm(jwk.alg), {
2762
+ ...jwk,
2763
+ ext
2764
+ });
2765
+ case "EC":
2766
+ case "OKP": return jwkToKey(keyAlgorithm(alg), {
2767
+ ...jwk,
2768
+ alg,
2769
+ ext
2770
+ });
2771
+ default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
2772
+ }
2773
+ }
2774
+ //#endregion
3020
2775
  //#region node_modules/jose/dist/webapi/util/decode_protected_header.js
3021
2776
  function decodeProtectedHeader(token) {
3022
2777
  let protectedB64u;
3023
2778
  if (typeof token === "string") {
3024
2779
  const parts = token.split(".");
3025
2780
  if (parts.length === 3 || parts.length === 5) [protectedB64u] = parts;
3026
- } else if (typeof token === "object" && token) if ("protected" in token) protectedB64u = token.protected;
3027
- else throw new TypeError("Token does not contain a Protected Header");
3028
- try {
3029
- if (typeof protectedB64u !== "string" || !protectedB64u) throw new Error();
3030
- const result = JSON.parse(decoder.decode(decode(protectedB64u)));
3031
- if (!isObject(result)) throw new Error();
3032
- return result;
3033
- } catch {
3034
- throw new TypeError("Invalid Token or Protected Header formatting");
2781
+ } else if (typeof token === "object" && token) {
2782
+ if ("protected" in token) protectedB64u = token.protected;
2783
+ else throw new TypeError("Token does not contain a Protected Header");
3035
2784
  }
2785
+ const invalid = "Invalid Token or Protected Header formatting";
2786
+ if (typeof protectedB64u !== "string" || !protectedB64u) throw new TypeError(invalid);
2787
+ return parseJoseHeader(protectedB64u, TypeError, invalid);
3036
2788
  }
3037
2789
  //#endregion
3038
2790
  //#region node_modules/jose/dist/webapi/util/decode_jwt.js
@@ -3050,7 +2802,7 @@ function decodeJwt(jwt) {
3050
2802
  }
3051
2803
  let result;
3052
2804
  try {
3053
- result = JSON.parse(decoder.decode(decoded));
2805
+ result = JSON.parse(strictDecoder.decode(decoded));
3054
2806
  } catch {
3055
2807
  throw new JWTInvalid("Failed to parse the decoded payload as JSON");
3056
2808
  }
@@ -3065,105 +2817,34 @@ function getModulusLengthOption(options) {
3065
2817
  return modulusLength;
3066
2818
  }
3067
2819
  async function generateKeyPair(alg, options) {
2820
+ const entry = keyAlgorithm(alg, algArgument);
2821
+ if (entry.secret) unsupportedAlg(algArgument);
3068
2822
  let algorithm;
3069
- let keyUsages;
3070
- switch (alg) {
3071
- case "PS256":
3072
- case "PS384":
3073
- case "PS512":
3074
- algorithm = {
3075
- name: "RSA-PSS",
3076
- hash: `SHA-${alg.slice(-3)}`,
3077
- publicExponent: Uint8Array.of(1, 0, 1),
3078
- modulusLength: getModulusLengthOption(options)
3079
- };
3080
- keyUsages = ["sign", "verify"];
3081
- break;
3082
- case "RS256":
3083
- case "RS384":
3084
- case "RS512":
3085
- algorithm = {
3086
- name: "RSASSA-PKCS1-v1_5",
3087
- hash: `SHA-${alg.slice(-3)}`,
3088
- publicExponent: Uint8Array.of(1, 0, 1),
3089
- modulusLength: getModulusLengthOption(options)
3090
- };
3091
- keyUsages = ["sign", "verify"];
3092
- break;
3093
- case "RSA-OAEP":
3094
- case "RSA-OAEP-256":
3095
- case "RSA-OAEP-384":
3096
- case "RSA-OAEP-512":
3097
- algorithm = {
3098
- name: "RSA-OAEP",
3099
- hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
3100
- publicExponent: Uint8Array.of(1, 0, 1),
3101
- modulusLength: getModulusLengthOption(options)
3102
- };
3103
- keyUsages = [
3104
- "decrypt",
3105
- "unwrapKey",
3106
- "encrypt",
3107
- "wrapKey"
3108
- ];
3109
- break;
3110
- case "ES256":
3111
- algorithm = {
3112
- name: "ECDSA",
3113
- namedCurve: "P-256"
3114
- };
3115
- keyUsages = ["sign", "verify"];
3116
- break;
3117
- case "ES384":
3118
- algorithm = {
3119
- name: "ECDSA",
3120
- namedCurve: "P-384"
3121
- };
3122
- keyUsages = ["sign", "verify"];
3123
- break;
3124
- case "ES512":
3125
- algorithm = {
3126
- name: "ECDSA",
3127
- namedCurve: "P-521"
3128
- };
3129
- keyUsages = ["sign", "verify"];
3130
- break;
3131
- case "Ed25519":
3132
- case "EdDSA":
3133
- keyUsages = ["sign", "verify"];
3134
- algorithm = { name: "Ed25519" };
3135
- break;
3136
- case "ML-DSA-44":
3137
- case "ML-DSA-65":
3138
- case "ML-DSA-87":
3139
- keyUsages = ["sign", "verify"];
3140
- algorithm = { name: alg };
3141
- break;
3142
- case "ECDH-ES":
3143
- case "ECDH-ES+A128KW":
3144
- case "ECDH-ES+A192KW":
3145
- case "ECDH-ES+A256KW": {
3146
- keyUsages = ["deriveBits"];
3147
- const crv = options?.crv ?? "P-256";
3148
- switch (crv) {
3149
- case "P-256":
3150
- case "P-384":
3151
- case "P-521":
3152
- algorithm = {
3153
- name: "ECDH",
3154
- namedCurve: crv
3155
- };
3156
- break;
3157
- case "X25519":
3158
- algorithm = { name: "X25519" };
3159
- break;
3160
- default: throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
3161
- }
3162
- break;
2823
+ if (entry.resolve) {
2824
+ const crv = options?.crv ?? "P-256";
2825
+ switch (crv) {
2826
+ case "P-256":
2827
+ case "P-384":
2828
+ case "P-521":
2829
+ algorithm = {
2830
+ name: "ECDH",
2831
+ namedCurve: crv
2832
+ };
2833
+ break;
2834
+ case "X25519":
2835
+ algorithm = { name: "X25519" };
2836
+ break;
2837
+ default: throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
3163
2838
  }
3164
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
2839
+ } else {
2840
+ if (entry.crv !== void 0 && options?.crv !== void 0 && options.crv !== entry.crv) throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${alg} is ${entry.crv}`);
2841
+ algorithm = entry.kty[0] === "RSA" ? {
2842
+ ...entry.subtle,
2843
+ publicExponent: Uint8Array.of(1, 0, 1),
2844
+ modulusLength: getModulusLengthOption(options)
2845
+ } : entry.subtle;
3165
2846
  }
3166
- return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
2847
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [...entry.usages[1], ...entry.usages[0]]);
3167
2848
  }
3168
2849
  //#endregion
3169
2850
  //#region node_modules/jose/dist/webapi/key/generate_secret.js
@@ -3211,7 +2892,7 @@ async function generateSecret(alg, options) {
3211
2892
  };
3212
2893
  keyUsages = ["encrypt", "decrypt"];
3213
2894
  break;
3214
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
2895
+ default: unsupportedAlg(algArgument);
3215
2896
  }
3216
2897
  return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
3217
2898
  }
@@ -3221,4 +2902,4 @@ const cryptoRuntime = "WebCryptoAPI";
3221
2902
  //#endregion
3222
2903
  export { CompactEncrypt, CompactSign, EmbeddedJWK, EncryptJWT, FlattenedEncrypt, FlattenedSign, GeneralEncrypt, GeneralSign, SignJWT, UnsecuredJWT, base64url_exports as base64url, calculateJwkThumbprint, calculateJwkThumbprintUri, compactDecrypt, compactVerify, createLocalJWKSet, createRemoteJWKSet, cryptoRuntime, customFetch, decodeJwt, decodeProtectedHeader, errors_exports as errors, exportJWK, exportPKCS8, exportSPKI, flattenedDecrypt, flattenedVerify, generalDecrypt, generalVerify, generateKeyPair, generateSecret, importJWK, importPKCS8, importSPKI, importX509, jwksCache, jwtDecrypt, jwtVerify };
3223
2904
 
3224
- //# sourceMappingURL=webapi-BgpV54gi.mjs.map
2905
+ //# sourceMappingURL=webapi-BlhUk1KL.mjs.map