princejs 2.1.6 → 2.2.1

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.
@@ -1,8 +1,21 @@
1
1
  // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
6
+ }
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true,
12
+ configurable: true,
13
+ set: __exportSetter.bind(all, name)
14
+ });
15
+ };
16
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
+
2
18
  // node_modules/jose/dist/webapi/lib/buffer_utils.js
3
- var encoder = new TextEncoder;
4
- var decoder = new TextDecoder;
5
- var MAX_INT32 = 2 ** 32;
6
19
  function concat(...buffers) {
7
20
  const size = buffers.reduce((acc, { length }) => acc + length, 0);
8
21
  const buf = new Uint8Array(size);
@@ -13,6 +26,25 @@ function concat(...buffers) {
13
26
  }
14
27
  return buf;
15
28
  }
29
+ function writeUInt32BE(buf, value, offset) {
30
+ if (value < 0 || value >= MAX_INT32) {
31
+ throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
32
+ }
33
+ buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);
34
+ }
35
+ function uint64be(value) {
36
+ const high = Math.floor(value / MAX_INT32);
37
+ const low = value % MAX_INT32;
38
+ const buf = new Uint8Array(8);
39
+ writeUInt32BE(buf, high, 0);
40
+ writeUInt32BE(buf, low, 4);
41
+ return buf;
42
+ }
43
+ function uint32be(value) {
44
+ const buf = new Uint8Array(4);
45
+ writeUInt32BE(buf, value);
46
+ return buf;
47
+ }
16
48
  function encode(string) {
17
49
  const bytes = new Uint8Array(string.length);
18
50
  for (let i = 0;i < string.length; i++) {
@@ -24,6 +56,12 @@ function encode(string) {
24
56
  }
25
57
  return bytes;
26
58
  }
59
+ var encoder, decoder, MAX_INT32;
60
+ var init_buffer_utils = __esm(() => {
61
+ encoder = new TextEncoder;
62
+ decoder = new TextDecoder;
63
+ MAX_INT32 = 2 ** 32;
64
+ });
27
65
 
28
66
  // node_modules/jose/dist/webapi/lib/base64.js
29
67
  function encodeBase64(input) {
@@ -50,6 +88,11 @@ function decodeBase64(encoded) {
50
88
  }
51
89
 
52
90
  // node_modules/jose/dist/webapi/util/base64url.js
91
+ var exports_base64url = {};
92
+ __export(exports_base64url, {
93
+ encode: () => encode2,
94
+ decode: () => decode
95
+ });
53
96
  function decode(input) {
54
97
  if (Uint8Array.fromBase64) {
55
98
  return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
@@ -77,10 +120,11 @@ function encode2(input) {
77
120
  }
78
121
  return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
79
122
  }
123
+ var init_base64url = __esm(() => {
124
+ init_buffer_utils();
125
+ });
80
126
 
81
127
  // node_modules/jose/dist/webapi/lib/crypto_key.js
82
- var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
83
- var isAlgorithm = (algorithm, name) => algorithm.name === name;
84
128
  function getHashLength(hash) {
85
129
  return parseInt(hash.name.slice(4), 10);
86
130
  }
@@ -161,6 +205,61 @@ function checkSigCryptoKey(key, alg, usage) {
161
205
  }
162
206
  checkUsage(key, usage);
163
207
  }
208
+ function checkEncCryptoKey(key, alg, usage) {
209
+ switch (alg) {
210
+ case "A128GCM":
211
+ case "A192GCM":
212
+ case "A256GCM": {
213
+ if (!isAlgorithm(key.algorithm, "AES-GCM"))
214
+ throw unusable("AES-GCM");
215
+ const expected = parseInt(alg.slice(1, 4), 10);
216
+ const actual = key.algorithm.length;
217
+ if (actual !== expected)
218
+ throw unusable(expected, "algorithm.length");
219
+ break;
220
+ }
221
+ case "A128KW":
222
+ case "A192KW":
223
+ case "A256KW": {
224
+ if (!isAlgorithm(key.algorithm, "AES-KW"))
225
+ throw unusable("AES-KW");
226
+ const expected = parseInt(alg.slice(1, 4), 10);
227
+ const actual = key.algorithm.length;
228
+ if (actual !== expected)
229
+ throw unusable(expected, "algorithm.length");
230
+ break;
231
+ }
232
+ case "ECDH": {
233
+ switch (key.algorithm.name) {
234
+ case "ECDH":
235
+ case "X25519":
236
+ break;
237
+ default:
238
+ throw unusable("ECDH or X25519");
239
+ }
240
+ break;
241
+ }
242
+ case "PBES2-HS256+A128KW":
243
+ case "PBES2-HS384+A192KW":
244
+ case "PBES2-HS512+A256KW":
245
+ if (!isAlgorithm(key.algorithm, "PBKDF2"))
246
+ throw unusable("PBKDF2");
247
+ break;
248
+ case "RSA-OAEP":
249
+ case "RSA-OAEP-256":
250
+ case "RSA-OAEP-384":
251
+ case "RSA-OAEP-512": {
252
+ if (!isAlgorithm(key.algorithm, "RSA-OAEP"))
253
+ throw unusable("RSA-OAEP");
254
+ checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1);
255
+ break;
256
+ }
257
+ default:
258
+ throw new TypeError("CryptoKey does not support this operation");
259
+ }
260
+ checkUsage(key, usage);
261
+ }
262
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`), isAlgorithm = (algorithm, name) => algorithm.name === name;
164
263
 
165
264
  // node_modules/jose/dist/webapi/lib/invalid_key_input.js
166
265
  function message(msg, actual, ...types) {
@@ -184,89 +283,355 @@ function message(msg, actual, ...types) {
184
283
  }
185
284
  return msg;
186
285
  }
187
- var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
188
- var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
286
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types), withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
189
287
 
190
288
  // node_modules/jose/dist/webapi/util/errors.js
191
- class JOSEError extends Error {
192
- static code = "ERR_JOSE_GENERIC";
193
- code = "ERR_JOSE_GENERIC";
194
- constructor(message2, options) {
195
- super(message2, options);
196
- this.name = this.constructor.name;
197
- Error.captureStackTrace?.(this, this.constructor);
289
+ var exports_errors = {};
290
+ __export(exports_errors, {
291
+ JWTInvalid: () => JWTInvalid,
292
+ JWTExpired: () => JWTExpired,
293
+ JWTClaimValidationFailed: () => JWTClaimValidationFailed,
294
+ JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
295
+ JWSInvalid: () => JWSInvalid,
296
+ JWKSTimeout: () => JWKSTimeout,
297
+ JWKSNoMatchingKey: () => JWKSNoMatchingKey,
298
+ JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
299
+ JWKSInvalid: () => JWKSInvalid,
300
+ JWKInvalid: () => JWKInvalid,
301
+ JWEInvalid: () => JWEInvalid,
302
+ JWEDecryptionFailed: () => JWEDecryptionFailed,
303
+ JOSENotSupported: () => JOSENotSupported,
304
+ JOSEError: () => JOSEError,
305
+ JOSEAlgNotAllowed: () => JOSEAlgNotAllowed
306
+ });
307
+ var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed;
308
+ var init_errors = __esm(() => {
309
+ JOSEError = class JOSEError extends Error {
310
+ static code = "ERR_JOSE_GENERIC";
311
+ code = "ERR_JOSE_GENERIC";
312
+ constructor(message2, options) {
313
+ super(message2, options);
314
+ this.name = this.constructor.name;
315
+ Error.captureStackTrace?.(this, this.constructor);
316
+ }
317
+ };
318
+ JWTClaimValidationFailed = class JWTClaimValidationFailed extends JOSEError {
319
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
320
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
321
+ claim;
322
+ reason;
323
+ payload;
324
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
325
+ super(message2, { cause: { claim, reason, payload } });
326
+ this.claim = claim;
327
+ this.reason = reason;
328
+ this.payload = payload;
329
+ }
330
+ };
331
+ JWTExpired = class JWTExpired extends JOSEError {
332
+ static code = "ERR_JWT_EXPIRED";
333
+ code = "ERR_JWT_EXPIRED";
334
+ claim;
335
+ reason;
336
+ payload;
337
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
338
+ super(message2, { cause: { claim, reason, payload } });
339
+ this.claim = claim;
340
+ this.reason = reason;
341
+ this.payload = payload;
342
+ }
343
+ };
344
+ JOSEAlgNotAllowed = class JOSEAlgNotAllowed extends JOSEError {
345
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
346
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
347
+ };
348
+ JOSENotSupported = class JOSENotSupported extends JOSEError {
349
+ static code = "ERR_JOSE_NOT_SUPPORTED";
350
+ code = "ERR_JOSE_NOT_SUPPORTED";
351
+ };
352
+ JWEDecryptionFailed = class JWEDecryptionFailed extends JOSEError {
353
+ static code = "ERR_JWE_DECRYPTION_FAILED";
354
+ code = "ERR_JWE_DECRYPTION_FAILED";
355
+ constructor(message2 = "decryption operation failed", options) {
356
+ super(message2, options);
357
+ }
358
+ };
359
+ JWEInvalid = class JWEInvalid extends JOSEError {
360
+ static code = "ERR_JWE_INVALID";
361
+ code = "ERR_JWE_INVALID";
362
+ };
363
+ JWSInvalid = class JWSInvalid extends JOSEError {
364
+ static code = "ERR_JWS_INVALID";
365
+ code = "ERR_JWS_INVALID";
366
+ };
367
+ JWTInvalid = class JWTInvalid extends JOSEError {
368
+ static code = "ERR_JWT_INVALID";
369
+ code = "ERR_JWT_INVALID";
370
+ };
371
+ JWKInvalid = class JWKInvalid extends JOSEError {
372
+ static code = "ERR_JWK_INVALID";
373
+ code = "ERR_JWK_INVALID";
374
+ };
375
+ JWKSInvalid = class JWKSInvalid extends JOSEError {
376
+ static code = "ERR_JWKS_INVALID";
377
+ code = "ERR_JWKS_INVALID";
378
+ };
379
+ JWKSNoMatchingKey = class JWKSNoMatchingKey extends JOSEError {
380
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
381
+ code = "ERR_JWKS_NO_MATCHING_KEY";
382
+ constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
383
+ super(message2, options);
384
+ }
385
+ };
386
+ JWKSMultipleMatchingKeys = class JWKSMultipleMatchingKeys extends JOSEError {
387
+ [Symbol.asyncIterator];
388
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
389
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
390
+ constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
391
+ super(message2, options);
392
+ }
393
+ };
394
+ JWKSTimeout = class JWKSTimeout extends JOSEError {
395
+ static code = "ERR_JWKS_TIMEOUT";
396
+ code = "ERR_JWKS_TIMEOUT";
397
+ constructor(message2 = "request timed out", options) {
398
+ super(message2, options);
399
+ }
400
+ };
401
+ JWSSignatureVerificationFailed = class JWSSignatureVerificationFailed extends JOSEError {
402
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
403
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
404
+ constructor(message2 = "signature verification failed", options) {
405
+ super(message2, options);
406
+ }
407
+ };
408
+ });
409
+
410
+ // node_modules/jose/dist/webapi/lib/is_key_like.js
411
+ function assertCryptoKey(key) {
412
+ if (!isCryptoKey(key)) {
413
+ throw new Error("CryptoKey instance expected");
198
414
  }
199
415
  }
416
+ var isCryptoKey = (key) => {
417
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
418
+ return true;
419
+ try {
420
+ return key instanceof CryptoKey;
421
+ } catch {
422
+ return false;
423
+ }
424
+ }, isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
200
425
 
201
- class JWTClaimValidationFailed extends JOSEError {
202
- static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
203
- code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
204
- claim;
205
- reason;
206
- payload;
207
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
208
- super(message2, { cause: { claim, reason, payload } });
209
- this.claim = claim;
210
- this.reason = reason;
211
- this.payload = payload;
426
+ // node_modules/jose/dist/webapi/lib/content_encryption.js
427
+ function cekLength(alg) {
428
+ switch (alg) {
429
+ case "A128GCM":
430
+ return 128;
431
+ case "A192GCM":
432
+ return 192;
433
+ case "A256GCM":
434
+ case "A128CBC-HS256":
435
+ return 256;
436
+ case "A192CBC-HS384":
437
+ return 384;
438
+ case "A256CBC-HS512":
439
+ return 512;
440
+ default:
441
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
212
442
  }
213
443
  }
214
-
215
- class JWTExpired extends JOSEError {
216
- static code = "ERR_JWT_EXPIRED";
217
- code = "ERR_JWT_EXPIRED";
218
- claim;
219
- reason;
220
- payload;
221
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
222
- super(message2, { cause: { claim, reason, payload } });
223
- this.claim = claim;
224
- this.reason = reason;
225
- this.payload = payload;
444
+ function checkCekLength(cek, expected) {
445
+ const actual = cek.byteLength << 3;
446
+ if (actual !== expected) {
447
+ throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
226
448
  }
227
449
  }
228
-
229
- class JOSEAlgNotAllowed extends JOSEError {
230
- static code = "ERR_JOSE_ALG_NOT_ALLOWED";
231
- code = "ERR_JOSE_ALG_NOT_ALLOWED";
450
+ function ivBitLength(alg) {
451
+ switch (alg) {
452
+ case "A128GCM":
453
+ case "A128GCMKW":
454
+ case "A192GCM":
455
+ case "A192GCMKW":
456
+ case "A256GCM":
457
+ case "A256GCMKW":
458
+ return 96;
459
+ case "A128CBC-HS256":
460
+ case "A192CBC-HS384":
461
+ case "A256CBC-HS512":
462
+ return 128;
463
+ default:
464
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
465
+ }
232
466
  }
233
-
234
- class JOSENotSupported extends JOSEError {
235
- static code = "ERR_JOSE_NOT_SUPPORTED";
236
- code = "ERR_JOSE_NOT_SUPPORTED";
467
+ function checkIvLength(enc, iv) {
468
+ if (iv.length << 3 !== ivBitLength(enc)) {
469
+ throw new JWEInvalid("Invalid Initialization Vector length");
470
+ }
237
471
  }
238
- class JWSInvalid extends JOSEError {
239
- static code = "ERR_JWS_INVALID";
240
- code = "ERR_JWS_INVALID";
472
+ async function cbcKeySetup(enc, cek, usage) {
473
+ if (!(cek instanceof Uint8Array)) {
474
+ throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
475
+ }
476
+ const keySize = parseInt(enc.slice(1, 4), 10);
477
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]);
478
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
479
+ hash: `SHA-${keySize << 1}`,
480
+ name: "HMAC"
481
+ }, false, ["sign"]);
482
+ return { encKey, macKey, keySize };
241
483
  }
242
-
243
- class JWTInvalid extends JOSEError {
244
- static code = "ERR_JWT_INVALID";
245
- code = "ERR_JWT_INVALID";
484
+ async function cbcHmacTag(macKey, macData, keySize) {
485
+ return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
486
+ }
487
+ async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
488
+ const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "encrypt");
489
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
490
+ iv,
491
+ name: "AES-CBC"
492
+ }, encKey, plaintext));
493
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
494
+ const tag = await cbcHmacTag(macKey, macData, keySize);
495
+ return { ciphertext, tag, iv };
246
496
  }
247
- class JWSSignatureVerificationFailed extends JOSEError {
248
- static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
249
- code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
250
- constructor(message2 = "signature verification failed", options) {
251
- super(message2, options);
497
+ async function timingSafeEqual(a, b) {
498
+ if (!(a instanceof Uint8Array)) {
499
+ throw new TypeError("First argument must be a buffer");
500
+ }
501
+ if (!(b instanceof Uint8Array)) {
502
+ throw new TypeError("Second argument must be a buffer");
503
+ }
504
+ const algorithm = { name: "HMAC", hash: "SHA-256" };
505
+ const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]);
506
+ const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
507
+ const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
508
+ let out = 0;
509
+ let i = -1;
510
+ while (++i < 32) {
511
+ out |= aHmac[i] ^ bHmac[i];
512
+ }
513
+ return out === 0;
514
+ }
515
+ async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
516
+ const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "decrypt");
517
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
518
+ const expectedTag = await cbcHmacTag(macKey, macData, keySize);
519
+ let macCheckPassed;
520
+ try {
521
+ macCheckPassed = await timingSafeEqual(tag, expectedTag);
522
+ } catch {}
523
+ if (!macCheckPassed) {
524
+ throw new JWEDecryptionFailed;
525
+ }
526
+ let plaintext;
527
+ try {
528
+ plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext));
529
+ } catch {}
530
+ if (!plaintext) {
531
+ throw new JWEDecryptionFailed;
252
532
  }
533
+ return plaintext;
253
534
  }
254
-
255
- // node_modules/jose/dist/webapi/lib/is_key_like.js
256
- var isCryptoKey = (key) => {
257
- if (key?.[Symbol.toStringTag] === "CryptoKey")
258
- return true;
535
+ async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
536
+ let encKey;
537
+ if (cek instanceof Uint8Array) {
538
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
539
+ } else {
540
+ checkEncCryptoKey(cek, enc, "encrypt");
541
+ encKey = cek;
542
+ }
543
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
544
+ additionalData: aad,
545
+ iv,
546
+ name: "AES-GCM",
547
+ tagLength: 128
548
+ }, encKey, plaintext));
549
+ const tag = encrypted.slice(-16);
550
+ const ciphertext = encrypted.slice(0, -16);
551
+ return { ciphertext, tag, iv };
552
+ }
553
+ async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
554
+ let encKey;
555
+ if (cek instanceof Uint8Array) {
556
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
557
+ } else {
558
+ checkEncCryptoKey(cek, enc, "decrypt");
559
+ encKey = cek;
560
+ }
259
561
  try {
260
- return key instanceof CryptoKey;
562
+ return new Uint8Array(await crypto.subtle.decrypt({
563
+ additionalData: aad,
564
+ iv,
565
+ name: "AES-GCM",
566
+ tagLength: 128
567
+ }, encKey, concat(ciphertext, tag)));
261
568
  } catch {
262
- return false;
569
+ throw new JWEDecryptionFailed;
263
570
  }
264
- };
265
- var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
266
- var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
571
+ }
572
+ async function encrypt(enc, plaintext, cek, iv, aad) {
573
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
574
+ throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
575
+ }
576
+ if (iv) {
577
+ checkIvLength(enc, iv);
578
+ } else {
579
+ iv = generateIv(enc);
580
+ }
581
+ switch (enc) {
582
+ case "A128CBC-HS256":
583
+ case "A192CBC-HS384":
584
+ case "A256CBC-HS512":
585
+ if (cek instanceof Uint8Array) {
586
+ checkCekLength(cek, parseInt(enc.slice(-3), 10));
587
+ }
588
+ return cbcEncrypt(enc, plaintext, cek, iv, aad);
589
+ case "A128GCM":
590
+ case "A192GCM":
591
+ case "A256GCM":
592
+ if (cek instanceof Uint8Array) {
593
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
594
+ }
595
+ return gcmEncrypt(enc, plaintext, cek, iv, aad);
596
+ default:
597
+ throw new JOSENotSupported(unsupportedEnc);
598
+ }
599
+ }
600
+ async function decrypt(enc, cek, ciphertext, iv, tag, aad) {
601
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
602
+ throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
603
+ }
604
+ if (!iv) {
605
+ throw new JWEInvalid("JWE Initialization Vector missing");
606
+ }
607
+ if (!tag) {
608
+ throw new JWEInvalid("JWE Authentication Tag missing");
609
+ }
610
+ checkIvLength(enc, iv);
611
+ switch (enc) {
612
+ case "A128CBC-HS256":
613
+ case "A192CBC-HS384":
614
+ case "A256CBC-HS512":
615
+ if (cek instanceof Uint8Array)
616
+ checkCekLength(cek, parseInt(enc.slice(-3), 10));
617
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);
618
+ case "A128GCM":
619
+ case "A192GCM":
620
+ case "A256GCM":
621
+ if (cek instanceof Uint8Array)
622
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
623
+ return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);
624
+ default:
625
+ throw new JOSENotSupported(unsupportedEnc);
626
+ }
627
+ }
628
+ var generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3)), generateIv = (alg) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg) >> 3)), unsupportedEnc = "Unsupported JWE Content Encryption Algorithm";
629
+ var init_content_encryption = __esm(() => {
630
+ init_buffer_utils();
631
+ init_errors();
632
+ });
267
633
 
268
634
  // node_modules/jose/dist/webapi/lib/helpers.js
269
- var unprotected = Symbol();
270
635
  function assertNotSet(value, name) {
271
636
  if (value) {
272
637
  throw new TypeError(`${name} can only be called once`);
@@ -279,9 +644,17 @@ function decodeBase64url(value, label, ErrorClass) {
279
644
  throw new ErrorClass(`Failed to base64url decode the ${label}`);
280
645
  }
281
646
  }
647
+ async function digest(algorithm, data) {
648
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
649
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
650
+ }
651
+ var unprotected;
652
+ var init_helpers = __esm(() => {
653
+ init_base64url();
654
+ unprotected = Symbol();
655
+ });
282
656
 
283
657
  // node_modules/jose/dist/webapi/lib/type_checks.js
284
- var isObjectLike = (value) => typeof value === "object" && value !== null;
285
658
  function isObject(input) {
286
659
  if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
287
660
  return false;
@@ -316,10 +689,131 @@ function isDisjoint(...headers) {
316
689
  }
317
690
  return true;
318
691
  }
319
- var isJWK = (key) => isObject(key) && typeof key.kty === "string";
320
- var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
321
- var isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined;
322
- var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
692
+ var isObjectLike = (value) => typeof value === "object" && value !== null, isJWK = (key) => isObject(key) && typeof key.kty === "string", isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"), isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined, isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
693
+
694
+ // node_modules/jose/dist/webapi/lib/aeskw.js
695
+ function checkKeySize(key, alg) {
696
+ if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
697
+ throw new TypeError(`Invalid key size for alg: ${alg}`);
698
+ }
699
+ }
700
+ function getCryptoKey(key, alg, usage) {
701
+ if (key instanceof Uint8Array) {
702
+ return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]);
703
+ }
704
+ checkEncCryptoKey(key, alg, usage);
705
+ return key;
706
+ }
707
+ async function wrap(alg, key, cek) {
708
+ const cryptoKey = await getCryptoKey(key, alg, "wrapKey");
709
+ checkKeySize(cryptoKey, alg);
710
+ const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
711
+ return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
712
+ }
713
+ async function unwrap(alg, key, encryptedKey) {
714
+ const cryptoKey = await getCryptoKey(key, alg, "unwrapKey");
715
+ checkKeySize(cryptoKey, alg);
716
+ const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
717
+ return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
718
+ }
719
+ var init_aeskw = () => {};
720
+
721
+ // node_modules/jose/dist/webapi/lib/ecdhes.js
722
+ function lengthAndInput(input) {
723
+ return concat(uint32be(input.length), input);
724
+ }
725
+ async function concatKdf(Z, L, OtherInfo) {
726
+ const dkLen = L >> 3;
727
+ const hashLen = 32;
728
+ const reps = Math.ceil(dkLen / hashLen);
729
+ const dk = new Uint8Array(reps * hashLen);
730
+ for (let i = 1;i <= reps; i++) {
731
+ const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);
732
+ hashInput.set(uint32be(i), 0);
733
+ hashInput.set(Z, 4);
734
+ hashInput.set(OtherInfo, 4 + Z.length);
735
+ const hashResult = await digest("sha256", hashInput);
736
+ dk.set(hashResult, (i - 1) * hashLen);
737
+ }
738
+ return dk.slice(0, dkLen);
739
+ }
740
+ async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array, apv = new Uint8Array) {
741
+ checkEncCryptoKey(publicKey, "ECDH");
742
+ checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
743
+ const algorithmID = lengthAndInput(encode(algorithm));
744
+ const partyUInfo = lengthAndInput(apu);
745
+ const partyVInfo = lengthAndInput(apv);
746
+ const suppPubInfo = uint32be(keyLength);
747
+ const suppPrivInfo = new Uint8Array;
748
+ const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
749
+ const Z = new Uint8Array(await crypto.subtle.deriveBits({
750
+ name: publicKey.algorithm.name,
751
+ public: publicKey
752
+ }, privateKey, getEcdhBitLength(publicKey)));
753
+ return concatKdf(Z, keyLength, otherInfo);
754
+ }
755
+ function getEcdhBitLength(publicKey) {
756
+ if (publicKey.algorithm.name === "X25519") {
757
+ return 256;
758
+ }
759
+ return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
760
+ }
761
+ function allowed(key) {
762
+ switch (key.algorithm.namedCurve) {
763
+ case "P-256":
764
+ case "P-384":
765
+ case "P-521":
766
+ return true;
767
+ default:
768
+ return key.algorithm.name === "X25519";
769
+ }
770
+ }
771
+ var init_ecdhes = __esm(() => {
772
+ init_buffer_utils();
773
+ init_helpers();
774
+ });
775
+
776
+ // node_modules/jose/dist/webapi/lib/pbes2kw.js
777
+ function getCryptoKey2(key, alg) {
778
+ if (key instanceof Uint8Array) {
779
+ return crypto.subtle.importKey("raw", key, "PBKDF2", false, [
780
+ "deriveBits"
781
+ ]);
782
+ }
783
+ checkEncCryptoKey(key, alg, "deriveBits");
784
+ return key;
785
+ }
786
+ async function deriveKey2(p2s, alg, p2c, key) {
787
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
788
+ throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
789
+ }
790
+ const salt = concatSalt(alg, p2s);
791
+ const keylen = parseInt(alg.slice(13, 16), 10);
792
+ const subtleAlg = {
793
+ hash: `SHA-${alg.slice(8, 11)}`,
794
+ iterations: p2c,
795
+ name: "PBKDF2",
796
+ salt
797
+ };
798
+ const cryptoKey = await getCryptoKey2(key, alg);
799
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
800
+ }
801
+ async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
802
+ const derived = await deriveKey2(p2s, alg, p2c, key);
803
+ const encryptedKey = await wrap(alg.slice(-6), derived, cek);
804
+ return { encryptedKey, p2c, p2s: encode2(p2s) };
805
+ }
806
+ async function unwrap2(alg, key, encryptedKey, p2c, p2s) {
807
+ const derived = await deriveKey2(p2s, alg, p2c, key);
808
+ return unwrap(alg.slice(-6), derived, encryptedKey);
809
+ }
810
+ var concatSalt = (alg, p2sInput) => concat(encode(alg), Uint8Array.of(0), p2sInput);
811
+ var init_pbes2kw = __esm(() => {
812
+ init_base64url();
813
+ init_aeskw();
814
+ init_buffer_utils();
815
+ init_errors();
816
+ });
323
817
 
324
818
  // node_modules/jose/dist/webapi/lib/signing.js
325
819
  function checkKeyLength(alg, key) {
@@ -386,9 +880,38 @@ async function verify(alg, key, signature, data) {
386
880
  return false;
387
881
  }
388
882
  }
883
+ var init_signing = __esm(() => {
884
+ init_errors();
885
+ });
886
+
887
+ // node_modules/jose/dist/webapi/lib/rsaes.js
888
+ async function encrypt2(alg, key, cek) {
889
+ checkEncCryptoKey(key, alg, "encrypt");
890
+ checkKeyLength(alg, key);
891
+ return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm2(alg), key, cek));
892
+ }
893
+ async function decrypt2(alg, key, encryptedKey) {
894
+ checkEncCryptoKey(key, alg, "decrypt");
895
+ checkKeyLength(alg, key);
896
+ return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm2(alg), key, encryptedKey));
897
+ }
898
+ var subtleAlgorithm2 = (alg) => {
899
+ switch (alg) {
900
+ case "RSA-OAEP":
901
+ case "RSA-OAEP-256":
902
+ case "RSA-OAEP-384":
903
+ case "RSA-OAEP-512":
904
+ return "RSA-OAEP";
905
+ default:
906
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
907
+ }
908
+ };
909
+ var init_rsaes = __esm(() => {
910
+ init_signing();
911
+ init_errors();
912
+ });
389
913
 
390
914
  // node_modules/jose/dist/webapi/lib/jwk_to_key.js
391
- var unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value';
392
915
  function subtleMapping(jwk) {
393
916
  let algorithm;
394
917
  let keyUsages;
@@ -494,11 +1017,44 @@ async function jwkToKey(jwk) {
494
1017
  delete keyData.use;
495
1018
  return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
496
1019
  }
1020
+ var unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value';
1021
+ var init_jwk_to_key = __esm(() => {
1022
+ init_errors();
1023
+ });
497
1024
 
498
1025
  // node_modules/jose/dist/webapi/lib/normalize_key.js
499
- var unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
500
- var cache;
501
- var handleJWK = async (key, jwk, alg, freeze = false) => {
1026
+ async function normalizeKey(key, alg) {
1027
+ if (key instanceof Uint8Array) {
1028
+ return key;
1029
+ }
1030
+ if (isCryptoKey(key)) {
1031
+ return key;
1032
+ }
1033
+ if (isKeyObject(key)) {
1034
+ if (key.type === "secret") {
1035
+ return key.export();
1036
+ }
1037
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
1038
+ try {
1039
+ return handleKeyObject(key, alg);
1040
+ } catch (err) {
1041
+ if (err instanceof TypeError) {
1042
+ throw err;
1043
+ }
1044
+ }
1045
+ }
1046
+ let jwk = key.export({ format: "jwk" });
1047
+ return handleJWK(key, jwk, alg);
1048
+ }
1049
+ if (isJWK(key)) {
1050
+ if (key.k) {
1051
+ return decode(key.k);
1052
+ }
1053
+ return handleJWK(key, key, alg, true);
1054
+ }
1055
+ throw new Error("unreachable");
1056
+ }
1057
+ var unusableForAlg = "given KeyObject instance cannot be used for this algorithm", cache, handleJWK = async (key, jwk, alg, freeze = false) => {
502
1058
  cache ||= new WeakMap;
503
1059
  let cached = cache.get(key);
504
1060
  if (cached?.[alg]) {
@@ -513,8 +1069,7 @@ var handleJWK = async (key, jwk, alg, freeze = false) => {
513
1069
  cached[alg] = cryptoKey;
514
1070
  }
515
1071
  return cryptoKey;
516
- };
517
- var handleKeyObject = (keyObject, alg) => {
1072
+ }, handleKeyObject = (keyObject, alg) => {
518
1073
  cache ||= new WeakMap;
519
1074
  let cached = cache.get(keyObject);
520
1075
  if (cached?.[alg]) {
@@ -624,92 +1179,620 @@ var handleKeyObject = (keyObject, alg) => {
624
1179
  }
625
1180
  return cryptoKey;
626
1181
  };
627
- async function normalizeKey(key, alg) {
628
- if (key instanceof Uint8Array) {
629
- return key;
630
- }
631
- if (isCryptoKey(key)) {
632
- return key;
1182
+ var init_normalize_key = __esm(() => {
1183
+ init_base64url();
1184
+ init_jwk_to_key();
1185
+ });
1186
+
1187
+ // node_modules/jose/dist/webapi/lib/asn1.js
1188
+ function parsePKCS8Header(state) {
1189
+ expectTag(state, 48, "Invalid PKCS#8 structure");
1190
+ parseLength(state);
1191
+ expectTag(state, 2, "Expected version field");
1192
+ const verLen = parseLength(state);
1193
+ state.pos += verLen;
1194
+ expectTag(state, 48, "Expected algorithm identifier");
1195
+ const algIdLen = parseLength(state);
1196
+ const algIdStart = state.pos;
1197
+ return { algIdStart, algIdLength: algIdLen };
1198
+ }
1199
+ function parseSPKIHeader(state) {
1200
+ expectTag(state, 48, "Invalid SPKI structure");
1201
+ parseLength(state);
1202
+ expectTag(state, 48, "Expected algorithm identifier");
1203
+ const algIdLen = parseLength(state);
1204
+ const algIdStart = state.pos;
1205
+ return { algIdStart, algIdLength: algIdLen };
1206
+ }
1207
+ function spkiFromX509(buf) {
1208
+ const state = createASN1State(buf);
1209
+ expectTag(state, 48, "Invalid certificate structure");
1210
+ parseLength(state);
1211
+ expectTag(state, 48, "Invalid tbsCertificate structure");
1212
+ parseLength(state);
1213
+ if (buf[state.pos] === 160) {
1214
+ skipElement(state, 6);
1215
+ } else {
1216
+ skipElement(state, 5);
633
1217
  }
1218
+ const spkiStart = state.pos;
1219
+ expectTag(state, 48, "Invalid SPKI structure");
1220
+ const spkiContentLen = parseLength(state);
1221
+ return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));
1222
+ }
1223
+ function extractX509SPKI(x509) {
1224
+ const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g);
1225
+ return spkiFromX509(derBytes);
1226
+ }
1227
+ var formatPEM = (b64, descriptor) => {
1228
+ const newlined = (b64.match(/.{1,64}/g) || []).join(`
1229
+ `);
1230
+ return `-----BEGIN ${descriptor}-----
1231
+ ${newlined}
1232
+ -----END ${descriptor}-----`;
1233
+ }, genericExport = async (keyType, keyFormat, key) => {
634
1234
  if (isKeyObject(key)) {
635
- if (key.type === "secret") {
636
- return key.export();
637
- }
638
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
639
- try {
640
- return handleKeyObject(key, alg);
641
- } catch (err) {
642
- if (err instanceof TypeError) {
643
- throw err;
644
- }
645
- }
646
- }
647
- let jwk = key.export({ format: "jwk" });
648
- return handleJWK(key, jwk, alg);
649
- }
650
- if (isJWK(key)) {
651
- if (key.k) {
652
- return decode(key.k);
1235
+ if (key.type !== keyType) {
1236
+ throw new TypeError(`key is not a ${keyType} key`);
653
1237
  }
654
- return handleJWK(key, key, alg, true);
1238
+ return key.export({ format: "pem", type: keyFormat });
655
1239
  }
656
- throw new Error("unreachable");
657
- }
658
-
659
- // node_modules/jose/dist/webapi/lib/validate_crit.js
660
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
661
- if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
662
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
1240
+ if (!isCryptoKey(key)) {
1241
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject"));
663
1242
  }
664
- if (!protectedHeader || protectedHeader.crit === undefined) {
665
- return new Set;
1243
+ if (!key.extractable) {
1244
+ throw new TypeError("CryptoKey is not extractable");
666
1245
  }
667
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
668
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
1246
+ if (key.type !== keyType) {
1247
+ throw new TypeError(`key is not a ${keyType} key`);
669
1248
  }
670
- let recognized;
671
- if (recognizedOption !== undefined) {
672
- recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
673
- } else {
674
- recognized = recognizedDefault;
1249
+ return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
1250
+ }, toSPKI = (key) => genericExport("public", "spki", key), toPKCS8 = (key) => genericExport("private", "pkcs8", key), bytesEqual = (a, b) => {
1251
+ if (a.byteLength !== b.length)
1252
+ return false;
1253
+ for (let i = 0;i < a.byteLength; i++) {
1254
+ if (a[i] !== b[i])
1255
+ return false;
675
1256
  }
676
- for (const parameter of protectedHeader.crit) {
677
- if (!recognized.has(parameter)) {
678
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
679
- }
680
- if (joseHeader[parameter] === undefined) {
681
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
682
- }
683
- if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
684
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
1257
+ return true;
1258
+ }, createASN1State = (data) => ({ data, pos: 0 }), parseLength = (state) => {
1259
+ const first = state.data[state.pos++];
1260
+ if (first & 128) {
1261
+ const lengthOfLen = first & 127;
1262
+ let length = 0;
1263
+ for (let i = 0;i < lengthOfLen; i++) {
1264
+ length = length << 8 | state.data[state.pos++];
685
1265
  }
1266
+ return length;
686
1267
  }
687
- return new Set(protectedHeader.crit);
688
- }
689
-
690
- // node_modules/jose/dist/webapi/lib/validate_algorithms.js
691
- function validateAlgorithms(option, algorithms) {
692
- if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
693
- throw new TypeError(`"${option}" option must be an array of strings`);
694
- }
695
- if (!algorithms) {
1268
+ return first;
1269
+ }, skipElement = (state, count = 1) => {
1270
+ if (count <= 0)
696
1271
  return;
1272
+ state.pos++;
1273
+ const length = parseLength(state);
1274
+ state.pos += length;
1275
+ if (count > 1) {
1276
+ skipElement(state, count - 1);
1277
+ }
1278
+ }, expectTag = (state, expectedTag, errorMessage) => {
1279
+ if (state.data[state.pos++] !== expectedTag) {
1280
+ throw new Error(errorMessage);
1281
+ }
1282
+ }, getSubarray = (state, length) => {
1283
+ const result = state.data.subarray(state.pos, state.pos + length);
1284
+ state.pos += length;
1285
+ return result;
1286
+ }, parseAlgorithmOID = (state) => {
1287
+ expectTag(state, 6, "Expected algorithm OID");
1288
+ const oidLen = parseLength(state);
1289
+ return getSubarray(state, oidLen);
1290
+ }, parseECAlgorithmIdentifier = (state) => {
1291
+ const algOid = parseAlgorithmOID(state);
1292
+ if (bytesEqual(algOid, [43, 101, 110])) {
1293
+ return "X25519";
1294
+ }
1295
+ if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
1296
+ throw new Error("Unsupported key algorithm");
1297
+ }
1298
+ expectTag(state, 6, "Expected curve OID");
1299
+ const curveOidLen = parseLength(state);
1300
+ const curveOid = getSubarray(state, curveOidLen);
1301
+ for (const { name, oid } of [
1302
+ { name: "P-256", oid: [42, 134, 72, 206, 61, 3, 1, 7] },
1303
+ { name: "P-384", oid: [43, 129, 4, 0, 34] },
1304
+ { name: "P-521", oid: [43, 129, 4, 0, 35] }
1305
+ ]) {
1306
+ if (bytesEqual(curveOid, oid)) {
1307
+ return name;
1308
+ }
697
1309
  }
698
- return new Set(algorithms);
699
- }
700
-
701
- // node_modules/jose/dist/webapi/lib/check_key_type.js
702
- var tag = (key) => key?.[Symbol.toStringTag];
703
- var jwkMatchesOp = (alg, key, usage) => {
704
- if (key.use !== undefined) {
705
- let expected;
706
- switch (usage) {
707
- case "sign":
708
- case "verify":
709
- expected = "sig";
710
- break;
711
- case "encrypt":
712
- case "decrypt":
1310
+ throw new Error("Unsupported named curve");
1311
+ }, genericImport = async (keyFormat, keyData, alg, options) => {
1312
+ let algorithm;
1313
+ let keyUsages;
1314
+ const isPublic = keyFormat === "spki";
1315
+ const getSigUsages = () => isPublic ? ["verify"] : ["sign"];
1316
+ const getEncUsages = () => isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
1317
+ switch (alg) {
1318
+ case "PS256":
1319
+ case "PS384":
1320
+ case "PS512":
1321
+ algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` };
1322
+ keyUsages = getSigUsages();
1323
+ break;
1324
+ case "RS256":
1325
+ case "RS384":
1326
+ case "RS512":
1327
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` };
1328
+ keyUsages = getSigUsages();
1329
+ break;
1330
+ case "RSA-OAEP":
1331
+ case "RSA-OAEP-256":
1332
+ case "RSA-OAEP-384":
1333
+ case "RSA-OAEP-512":
1334
+ algorithm = {
1335
+ name: "RSA-OAEP",
1336
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
1337
+ };
1338
+ keyUsages = getEncUsages();
1339
+ break;
1340
+ case "ES256":
1341
+ case "ES384":
1342
+ case "ES512": {
1343
+ const curveMap = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
1344
+ algorithm = { name: "ECDSA", namedCurve: curveMap[alg] };
1345
+ keyUsages = getSigUsages();
1346
+ break;
1347
+ }
1348
+ case "ECDH-ES":
1349
+ case "ECDH-ES+A128KW":
1350
+ case "ECDH-ES+A192KW":
1351
+ case "ECDH-ES+A256KW": {
1352
+ try {
1353
+ const namedCurve = options.getNamedCurve(keyData);
1354
+ algorithm = namedCurve === "X25519" ? { name: "X25519" } : { name: "ECDH", namedCurve };
1355
+ } catch (cause) {
1356
+ throw new JOSENotSupported("Invalid or unsupported key format");
1357
+ }
1358
+ keyUsages = isPublic ? [] : ["deriveBits"];
1359
+ break;
1360
+ }
1361
+ case "Ed25519":
1362
+ case "EdDSA":
1363
+ algorithm = { name: "Ed25519" };
1364
+ keyUsages = getSigUsages();
1365
+ break;
1366
+ case "ML-DSA-44":
1367
+ case "ML-DSA-65":
1368
+ case "ML-DSA-87":
1369
+ algorithm = { name: alg };
1370
+ keyUsages = getSigUsages();
1371
+ break;
1372
+ default:
1373
+ throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
1374
+ }
1375
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
1376
+ }, processPEMData = (pem, pattern) => {
1377
+ return decodeBase64(pem.replace(pattern, ""));
1378
+ }, fromPKCS8 = (pem, alg, options) => {
1379
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
1380
+ let opts = options;
1381
+ if (alg?.startsWith?.("ECDH-ES")) {
1382
+ opts ||= {};
1383
+ opts.getNamedCurve = (keyData2) => {
1384
+ const state = createASN1State(keyData2);
1385
+ parsePKCS8Header(state);
1386
+ return parseECAlgorithmIdentifier(state);
1387
+ };
1388
+ }
1389
+ return genericImport("pkcs8", keyData, alg, opts);
1390
+ }, fromSPKI = (pem, alg, options) => {
1391
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);
1392
+ let opts = options;
1393
+ if (alg?.startsWith?.("ECDH-ES")) {
1394
+ opts ||= {};
1395
+ opts.getNamedCurve = (keyData2) => {
1396
+ const state = createASN1State(keyData2);
1397
+ parseSPKIHeader(state);
1398
+ return parseECAlgorithmIdentifier(state);
1399
+ };
1400
+ }
1401
+ return genericImport("spki", keyData, alg, opts);
1402
+ }, fromX509 = (pem, alg, options) => {
1403
+ let spki;
1404
+ try {
1405
+ spki = extractX509SPKI(pem);
1406
+ } catch (cause) {
1407
+ throw new TypeError("Failed to parse the X.509 certificate", { cause });
1408
+ }
1409
+ return fromSPKI(formatPEM(encodeBase64(spki), "PUBLIC KEY"), alg, options);
1410
+ };
1411
+ var init_asn1 = __esm(() => {
1412
+ init_errors();
1413
+ });
1414
+
1415
+ // node_modules/jose/dist/webapi/key/import.js
1416
+ async function importSPKI(spki, alg, options) {
1417
+ if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) {
1418
+ throw new TypeError('"spki" must be SPKI formatted string');
1419
+ }
1420
+ return fromSPKI(spki, alg, options);
1421
+ }
1422
+ async function importX509(x509, alg, options) {
1423
+ if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) {
1424
+ throw new TypeError('"x509" must be X.509 formatted string');
1425
+ }
1426
+ return fromX509(x509, alg, options);
1427
+ }
1428
+ async function importPKCS8(pkcs8, alg, options) {
1429
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
1430
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
1431
+ }
1432
+ return fromPKCS8(pkcs8, alg, options);
1433
+ }
1434
+ async function importJWK(jwk, alg, options) {
1435
+ if (!isObject(jwk)) {
1436
+ throw new TypeError("JWK must be an object");
1437
+ }
1438
+ let ext;
1439
+ alg ??= jwk.alg;
1440
+ ext ??= options?.extractable ?? jwk.ext;
1441
+ switch (jwk.kty) {
1442
+ case "oct":
1443
+ if (typeof jwk.k !== "string" || !jwk.k) {
1444
+ throw new TypeError('missing "k" (Key Value) Parameter value');
1445
+ }
1446
+ return decode(jwk.k);
1447
+ case "RSA":
1448
+ if ("oth" in jwk && jwk.oth !== undefined) {
1449
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
1450
+ }
1451
+ return jwkToKey({ ...jwk, alg, ext });
1452
+ case "AKP": {
1453
+ if (typeof jwk.alg !== "string" || !jwk.alg) {
1454
+ throw new TypeError('missing "alg" (Algorithm) Parameter value');
1455
+ }
1456
+ if (alg !== undefined && alg !== jwk.alg) {
1457
+ throw new TypeError("JWK alg and alg option value mismatch");
1458
+ }
1459
+ return jwkToKey({ ...jwk, ext });
1460
+ }
1461
+ case "EC":
1462
+ case "OKP":
1463
+ return jwkToKey({ ...jwk, alg, ext });
1464
+ default:
1465
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
1466
+ }
1467
+ }
1468
+ var init_import = __esm(() => {
1469
+ init_base64url();
1470
+ init_asn1();
1471
+ init_jwk_to_key();
1472
+ init_errors();
1473
+ });
1474
+
1475
+ // node_modules/jose/dist/webapi/lib/key_to_jwk.js
1476
+ async function keyToJWK(key) {
1477
+ if (isKeyObject(key)) {
1478
+ if (key.type === "secret") {
1479
+ key = key.export();
1480
+ } else {
1481
+ return key.export({ format: "jwk" });
1482
+ }
1483
+ }
1484
+ if (key instanceof Uint8Array) {
1485
+ return {
1486
+ kty: "oct",
1487
+ k: encode2(key)
1488
+ };
1489
+ }
1490
+ if (!isCryptoKey(key)) {
1491
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
1492
+ }
1493
+ if (!key.extractable) {
1494
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
1495
+ }
1496
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
1497
+ if (jwk.kty === "AKP") {
1498
+ jwk.alg = alg;
1499
+ }
1500
+ return jwk;
1501
+ }
1502
+ var init_key_to_jwk = __esm(() => {
1503
+ init_base64url();
1504
+ });
1505
+
1506
+ // node_modules/jose/dist/webapi/key/export.js
1507
+ async function exportSPKI(key) {
1508
+ return toSPKI(key);
1509
+ }
1510
+ async function exportPKCS8(key) {
1511
+ return toPKCS8(key);
1512
+ }
1513
+ async function exportJWK(key) {
1514
+ return keyToJWK(key);
1515
+ }
1516
+ var init_export = __esm(() => {
1517
+ init_asn1();
1518
+ init_key_to_jwk();
1519
+ });
1520
+
1521
+ // node_modules/jose/dist/webapi/lib/aesgcmkw.js
1522
+ async function wrap3(alg, key, cek, iv) {
1523
+ const jweAlgorithm = alg.slice(0, 7);
1524
+ const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array);
1525
+ return {
1526
+ encryptedKey: wrapped.ciphertext,
1527
+ iv: encode2(wrapped.iv),
1528
+ tag: encode2(wrapped.tag)
1529
+ };
1530
+ }
1531
+ async function unwrap3(alg, key, encryptedKey, iv, tag) {
1532
+ const jweAlgorithm = alg.slice(0, 7);
1533
+ return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array);
1534
+ }
1535
+ var init_aesgcmkw = __esm(() => {
1536
+ init_content_encryption();
1537
+ init_base64url();
1538
+ });
1539
+
1540
+ // node_modules/jose/dist/webapi/lib/key_management.js
1541
+ function assertEncryptedKey(encryptedKey) {
1542
+ if (encryptedKey === undefined)
1543
+ throw new JWEInvalid("JWE Encrypted Key missing");
1544
+ }
1545
+ async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
1546
+ switch (alg) {
1547
+ case "dir": {
1548
+ if (encryptedKey !== undefined)
1549
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
1550
+ return key;
1551
+ }
1552
+ case "ECDH-ES":
1553
+ if (encryptedKey !== undefined)
1554
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
1555
+ case "ECDH-ES+A128KW":
1556
+ case "ECDH-ES+A192KW":
1557
+ case "ECDH-ES+A256KW": {
1558
+ if (!isObject(joseHeader.epk))
1559
+ throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
1560
+ assertCryptoKey(key);
1561
+ if (!allowed(key))
1562
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
1563
+ const epk = await importJWK(joseHeader.epk, alg);
1564
+ assertCryptoKey(epk);
1565
+ let partyUInfo;
1566
+ let partyVInfo;
1567
+ if (joseHeader.apu !== undefined) {
1568
+ if (typeof joseHeader.apu !== "string")
1569
+ throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
1570
+ partyUInfo = decodeBase64url(joseHeader.apu, "apu", JWEInvalid);
1571
+ }
1572
+ if (joseHeader.apv !== undefined) {
1573
+ if (typeof joseHeader.apv !== "string")
1574
+ throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
1575
+ partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid);
1576
+ }
1577
+ const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
1578
+ if (alg === "ECDH-ES")
1579
+ return sharedSecret;
1580
+ assertEncryptedKey(encryptedKey);
1581
+ return unwrap(alg.slice(-6), sharedSecret, encryptedKey);
1582
+ }
1583
+ case "RSA-OAEP":
1584
+ case "RSA-OAEP-256":
1585
+ case "RSA-OAEP-384":
1586
+ case "RSA-OAEP-512": {
1587
+ assertEncryptedKey(encryptedKey);
1588
+ assertCryptoKey(key);
1589
+ return decrypt2(alg, key, encryptedKey);
1590
+ }
1591
+ case "PBES2-HS256+A128KW":
1592
+ case "PBES2-HS384+A192KW":
1593
+ case "PBES2-HS512+A256KW": {
1594
+ assertEncryptedKey(encryptedKey);
1595
+ if (typeof joseHeader.p2c !== "number")
1596
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
1597
+ const p2cLimit = options?.maxPBES2Count || 1e4;
1598
+ if (joseHeader.p2c > p2cLimit)
1599
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
1600
+ if (typeof joseHeader.p2s !== "string")
1601
+ throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
1602
+ let p2s;
1603
+ p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid);
1604
+ return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s);
1605
+ }
1606
+ case "A128KW":
1607
+ case "A192KW":
1608
+ case "A256KW": {
1609
+ assertEncryptedKey(encryptedKey);
1610
+ return unwrap(alg, key, encryptedKey);
1611
+ }
1612
+ case "A128GCMKW":
1613
+ case "A192GCMKW":
1614
+ case "A256GCMKW": {
1615
+ assertEncryptedKey(encryptedKey);
1616
+ if (typeof joseHeader.iv !== "string")
1617
+ throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
1618
+ if (typeof joseHeader.tag !== "string")
1619
+ throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
1620
+ let iv;
1621
+ iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid);
1622
+ let tag;
1623
+ tag = decodeBase64url(joseHeader.tag, "tag", JWEInvalid);
1624
+ return unwrap3(alg, key, encryptedKey, iv, tag);
1625
+ }
1626
+ default: {
1627
+ throw new JOSENotSupported(unsupportedAlgHeader);
1628
+ }
1629
+ }
1630
+ }
1631
+ async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
1632
+ let encryptedKey;
1633
+ let parameters;
1634
+ let cek;
1635
+ switch (alg) {
1636
+ case "dir": {
1637
+ cek = key;
1638
+ break;
1639
+ }
1640
+ case "ECDH-ES":
1641
+ case "ECDH-ES+A128KW":
1642
+ case "ECDH-ES+A192KW":
1643
+ case "ECDH-ES+A256KW": {
1644
+ assertCryptoKey(key);
1645
+ if (!allowed(key)) {
1646
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
1647
+ }
1648
+ const { apu, apv } = providedParameters;
1649
+ let ephemeralKey;
1650
+ if (providedParameters.epk) {
1651
+ ephemeralKey = await normalizeKey(providedParameters.epk, alg);
1652
+ } else {
1653
+ ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
1654
+ }
1655
+ const { x, y, crv, kty } = await exportJWK(ephemeralKey);
1656
+ const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
1657
+ parameters = { epk: { x, crv, kty } };
1658
+ if (kty === "EC")
1659
+ parameters.epk.y = y;
1660
+ if (apu)
1661
+ parameters.apu = encode2(apu);
1662
+ if (apv)
1663
+ parameters.apv = encode2(apv);
1664
+ if (alg === "ECDH-ES") {
1665
+ cek = sharedSecret;
1666
+ break;
1667
+ }
1668
+ cek = providedCek || generateCek(enc);
1669
+ const kwAlg = alg.slice(-6);
1670
+ encryptedKey = await wrap(kwAlg, sharedSecret, cek);
1671
+ break;
1672
+ }
1673
+ case "RSA-OAEP":
1674
+ case "RSA-OAEP-256":
1675
+ case "RSA-OAEP-384":
1676
+ case "RSA-OAEP-512": {
1677
+ cek = providedCek || generateCek(enc);
1678
+ assertCryptoKey(key);
1679
+ encryptedKey = await encrypt2(alg, key, cek);
1680
+ break;
1681
+ }
1682
+ case "PBES2-HS256+A128KW":
1683
+ case "PBES2-HS384+A192KW":
1684
+ case "PBES2-HS512+A256KW": {
1685
+ cek = providedCek || generateCek(enc);
1686
+ const { p2c, p2s } = providedParameters;
1687
+ ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s));
1688
+ break;
1689
+ }
1690
+ case "A128KW":
1691
+ case "A192KW":
1692
+ case "A256KW": {
1693
+ cek = providedCek || generateCek(enc);
1694
+ encryptedKey = await wrap(alg, key, cek);
1695
+ break;
1696
+ }
1697
+ case "A128GCMKW":
1698
+ case "A192GCMKW":
1699
+ case "A256GCMKW": {
1700
+ cek = providedCek || generateCek(enc);
1701
+ const { iv } = providedParameters;
1702
+ ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv));
1703
+ break;
1704
+ }
1705
+ default: {
1706
+ throw new JOSENotSupported(unsupportedAlgHeader);
1707
+ }
1708
+ }
1709
+ return { cek, encryptedKey, parameters };
1710
+ }
1711
+ var unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value';
1712
+ var init_key_management = __esm(() => {
1713
+ init_aeskw();
1714
+ init_ecdhes();
1715
+ init_pbes2kw();
1716
+ init_rsaes();
1717
+ init_base64url();
1718
+ init_normalize_key();
1719
+ init_errors();
1720
+ init_helpers();
1721
+ init_content_encryption();
1722
+ init_import();
1723
+ init_export();
1724
+ init_aesgcmkw();
1725
+ });
1726
+
1727
+ // node_modules/jose/dist/webapi/lib/validate_crit.js
1728
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
1729
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
1730
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
1731
+ }
1732
+ if (!protectedHeader || protectedHeader.crit === undefined) {
1733
+ return new Set;
1734
+ }
1735
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
1736
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
1737
+ }
1738
+ let recognized;
1739
+ if (recognizedOption !== undefined) {
1740
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
1741
+ } else {
1742
+ recognized = recognizedDefault;
1743
+ }
1744
+ for (const parameter of protectedHeader.crit) {
1745
+ if (!recognized.has(parameter)) {
1746
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
1747
+ }
1748
+ if (joseHeader[parameter] === undefined) {
1749
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
1750
+ }
1751
+ if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
1752
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
1753
+ }
1754
+ }
1755
+ return new Set(protectedHeader.crit);
1756
+ }
1757
+ var init_validate_crit = __esm(() => {
1758
+ init_errors();
1759
+ });
1760
+
1761
+ // node_modules/jose/dist/webapi/lib/validate_algorithms.js
1762
+ function validateAlgorithms(option, algorithms) {
1763
+ if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
1764
+ throw new TypeError(`"${option}" option must be an array of strings`);
1765
+ }
1766
+ if (!algorithms) {
1767
+ return;
1768
+ }
1769
+ return new Set(algorithms);
1770
+ }
1771
+
1772
+ // node_modules/jose/dist/webapi/lib/check_key_type.js
1773
+ function checkKeyType(alg, key, usage) {
1774
+ switch (alg.substring(0, 2)) {
1775
+ case "A1":
1776
+ case "A2":
1777
+ case "di":
1778
+ case "HS":
1779
+ case "PB":
1780
+ symmetricTypeCheck(alg, key, usage);
1781
+ break;
1782
+ default:
1783
+ asymmetricTypeCheck(alg, key, usage);
1784
+ }
1785
+ }
1786
+ var tag = (key) => key?.[Symbol.toStringTag], jwkMatchesOp = (alg, key, usage) => {
1787
+ if (key.use !== undefined) {
1788
+ let expected;
1789
+ switch (usage) {
1790
+ case "sign":
1791
+ case "verify":
1792
+ expected = "sig";
1793
+ break;
1794
+ case "encrypt":
1795
+ case "decrypt":
713
1796
  expected = "enc";
714
1797
  break;
715
1798
  }
@@ -750,8 +1833,7 @@ var jwkMatchesOp = (alg, key, usage) => {
750
1833
  }
751
1834
  }
752
1835
  return true;
753
- };
754
- var symmetricTypeCheck = (alg, key, usage) => {
1836
+ }, symmetricTypeCheck = (alg, key, usage) => {
755
1837
  if (key instanceof Uint8Array)
756
1838
  return;
757
1839
  if (isJWK(key)) {
@@ -765,8 +1847,7 @@ var symmetricTypeCheck = (alg, key, usage) => {
765
1847
  if (key.type !== "secret") {
766
1848
  throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
767
1849
  }
768
- };
769
- var asymmetricTypeCheck = (alg, key, usage) => {
1850
+ }, asymmetricTypeCheck = (alg, key, usage) => {
770
1851
  if (isJWK(key)) {
771
1852
  switch (usage) {
772
1853
  case "decrypt":
@@ -804,96 +1885,685 @@ var asymmetricTypeCheck = (alg, key, usage) => {
804
1885
  }
805
1886
  }
806
1887
  };
807
- function checkKeyType(alg, key, usage) {
808
- switch (alg.substring(0, 2)) {
809
- case "A1":
810
- case "A2":
811
- case "di":
812
- case "HS":
813
- case "PB":
814
- symmetricTypeCheck(alg, key, usage);
1888
+ var init_check_key_type = () => {};
1889
+
1890
+ // node_modules/jose/dist/webapi/lib/deflate.js
1891
+ function supported(name) {
1892
+ if (typeof globalThis[name] === "undefined") {
1893
+ throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`);
1894
+ }
1895
+ }
1896
+ async function compress(input) {
1897
+ supported("CompressionStream");
1898
+ const cs = new CompressionStream("deflate-raw");
1899
+ const writer = cs.writable.getWriter();
1900
+ writer.write(input).catch(() => {});
1901
+ writer.close().catch(() => {});
1902
+ const chunks = [];
1903
+ const reader = cs.readable.getReader();
1904
+ for (;; ) {
1905
+ const { value, done } = await reader.read();
1906
+ if (done)
815
1907
  break;
816
- default:
817
- asymmetricTypeCheck(alg, key, usage);
1908
+ chunks.push(value);
1909
+ }
1910
+ return concat(...chunks);
1911
+ }
1912
+ async function decompress(input, maxLength) {
1913
+ supported("DecompressionStream");
1914
+ const ds = new DecompressionStream("deflate-raw");
1915
+ const writer = ds.writable.getWriter();
1916
+ writer.write(input).catch(() => {});
1917
+ writer.close().catch(() => {});
1918
+ const chunks = [];
1919
+ let length = 0;
1920
+ const reader = ds.readable.getReader();
1921
+ for (;; ) {
1922
+ const { value, done } = await reader.read();
1923
+ if (done)
1924
+ break;
1925
+ chunks.push(value);
1926
+ length += value.byteLength;
1927
+ if (maxLength !== Infinity && length > maxLength) {
1928
+ throw new JWEInvalid("Decompressed plaintext exceeded the configured limit");
1929
+ }
818
1930
  }
1931
+ return concat(...chunks);
819
1932
  }
1933
+ var init_deflate = __esm(() => {
1934
+ init_errors();
1935
+ init_buffer_utils();
1936
+ });
820
1937
 
821
- // node_modules/jose/dist/webapi/jws/flattened/verify.js
822
- async function flattenedVerify(jws, key, options) {
823
- if (!isObject(jws)) {
824
- throw new JWSInvalid("Flattened JWS must be an object");
1938
+ // node_modules/jose/dist/webapi/jwe/flattened/decrypt.js
1939
+ async function flattenedDecrypt(jwe, key, options) {
1940
+ if (!isObject(jwe)) {
1941
+ throw new JWEInvalid("Flattened JWE must be an object");
825
1942
  }
826
- if (jws.protected === undefined && jws.header === undefined) {
827
- throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
1943
+ if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
1944
+ throw new JWEInvalid("JOSE Header missing");
828
1945
  }
829
- if (jws.protected !== undefined && typeof jws.protected !== "string") {
830
- throw new JWSInvalid("JWS Protected Header incorrect type");
1946
+ if (jwe.iv !== undefined && typeof jwe.iv !== "string") {
1947
+ throw new JWEInvalid("JWE Initialization Vector incorrect type");
831
1948
  }
832
- if (jws.payload === undefined) {
833
- throw new JWSInvalid("JWS Payload missing");
1949
+ if (typeof jwe.ciphertext !== "string") {
1950
+ throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
834
1951
  }
835
- if (typeof jws.signature !== "string") {
836
- throw new JWSInvalid("JWS Signature missing or incorrect type");
1952
+ if (jwe.tag !== undefined && typeof jwe.tag !== "string") {
1953
+ throw new JWEInvalid("JWE Authentication Tag incorrect type");
837
1954
  }
838
- if (jws.header !== undefined && !isObject(jws.header)) {
839
- throw new JWSInvalid("JWS Unprotected Header incorrect type");
1955
+ if (jwe.protected !== undefined && typeof jwe.protected !== "string") {
1956
+ throw new JWEInvalid("JWE Protected Header incorrect type");
840
1957
  }
841
- let parsedProt = {};
842
- if (jws.protected) {
1958
+ if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== "string") {
1959
+ throw new JWEInvalid("JWE Encrypted Key incorrect type");
1960
+ }
1961
+ if (jwe.aad !== undefined && typeof jwe.aad !== "string") {
1962
+ throw new JWEInvalid("JWE AAD incorrect type");
1963
+ }
1964
+ if (jwe.header !== undefined && !isObject(jwe.header)) {
1965
+ throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
1966
+ }
1967
+ if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {
1968
+ throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
1969
+ }
1970
+ let parsedProt;
1971
+ if (jwe.protected) {
843
1972
  try {
844
- const protectedHeader = decode(jws.protected);
845
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
1973
+ const protectedHeader2 = decode(jwe.protected);
1974
+ parsedProt = JSON.parse(decoder.decode(protectedHeader2));
846
1975
  } catch {
847
- throw new JWSInvalid("JWS Protected Header is invalid");
1976
+ throw new JWEInvalid("JWE Protected Header is invalid");
848
1977
  }
849
1978
  }
850
- if (!isDisjoint(parsedProt, jws.header)) {
851
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1979
+ if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
1980
+ throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
852
1981
  }
853
1982
  const joseHeader = {
854
1983
  ...parsedProt,
855
- ...jws.header
1984
+ ...jwe.header,
1985
+ ...jwe.unprotected
856
1986
  };
857
- const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
858
- let b64 = true;
859
- if (extensions.has("b64")) {
860
- b64 = parsedProt.b64;
861
- if (typeof b64 !== "boolean") {
862
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
863
- }
1987
+ validateCrit(JWEInvalid, new Map, options?.crit, parsedProt, joseHeader);
1988
+ if (joseHeader.zip !== undefined && joseHeader.zip !== "DEF") {
1989
+ throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
864
1990
  }
865
- const { alg } = joseHeader;
1991
+ if (joseHeader.zip !== undefined && !parsedProt?.zip) {
1992
+ throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
1993
+ }
1994
+ const { alg, enc } = joseHeader;
866
1995
  if (typeof alg !== "string" || !alg) {
867
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1996
+ throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
868
1997
  }
869
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
870
- if (algorithms && !algorithms.has(alg)) {
1998
+ if (typeof enc !== "string" || !enc) {
1999
+ throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
2000
+ }
2001
+ const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms);
2002
+ const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
2003
+ if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) {
871
2004
  throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
872
2005
  }
873
- if (b64) {
874
- if (typeof jws.payload !== "string") {
875
- throw new JWSInvalid("JWS Payload must be a string");
876
- }
877
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
878
- throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
2006
+ if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
2007
+ throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
2008
+ }
2009
+ let encryptedKey;
2010
+ if (jwe.encrypted_key !== undefined) {
2011
+ encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid);
879
2012
  }
880
2013
  let resolvedKey = false;
881
2014
  if (typeof key === "function") {
882
- key = await key(parsedProt, jws);
2015
+ key = await key(parsedProt, jwe);
883
2016
  resolvedKey = true;
884
2017
  }
885
- checkKeyType(alg, key, "verify");
886
- const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array, encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
887
- const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
2018
+ checkKeyType(alg === "dir" ? enc : alg, key, "decrypt");
888
2019
  const k = await normalizeKey(key, alg);
889
- const verified = await verify(alg, k, signature, data);
890
- if (!verified) {
891
- throw new JWSSignatureVerificationFailed;
2020
+ let cek;
2021
+ try {
2022
+ cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);
2023
+ } catch (err) {
2024
+ if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
2025
+ throw err;
2026
+ }
2027
+ cek = generateCek(enc);
892
2028
  }
893
- let payload;
894
- if (b64) {
895
- payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
896
- } else if (typeof jws.payload === "string") {
2029
+ let iv;
2030
+ let tag2;
2031
+ if (jwe.iv !== undefined) {
2032
+ iv = decodeBase64url(jwe.iv, "iv", JWEInvalid);
2033
+ }
2034
+ if (jwe.tag !== undefined) {
2035
+ tag2 = decodeBase64url(jwe.tag, "tag", JWEInvalid);
2036
+ }
2037
+ const protectedHeader = jwe.protected !== undefined ? encode(jwe.protected) : new Uint8Array;
2038
+ let additionalData;
2039
+ if (jwe.aad !== undefined) {
2040
+ additionalData = concat(protectedHeader, encode("."), encode(jwe.aad));
2041
+ } else {
2042
+ additionalData = protectedHeader;
2043
+ }
2044
+ const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid);
2045
+ const plaintext = await decrypt(enc, cek, ciphertext, iv, tag2, additionalData);
2046
+ const result = { plaintext };
2047
+ if (joseHeader.zip === "DEF") {
2048
+ const maxDecompressedLength = options?.maxDecompressedLength ?? 250000;
2049
+ if (maxDecompressedLength === 0) {
2050
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
2051
+ }
2052
+ if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) {
2053
+ throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");
2054
+ }
2055
+ result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => {
2056
+ if (cause instanceof JWEInvalid)
2057
+ throw cause;
2058
+ throw new JWEInvalid("Failed to decompress plaintext", { cause });
2059
+ });
2060
+ }
2061
+ if (jwe.protected !== undefined) {
2062
+ result.protectedHeader = parsedProt;
2063
+ }
2064
+ if (jwe.aad !== undefined) {
2065
+ result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid);
2066
+ }
2067
+ if (jwe.unprotected !== undefined) {
2068
+ result.sharedUnprotectedHeader = jwe.unprotected;
2069
+ }
2070
+ if (jwe.header !== undefined) {
2071
+ result.unprotectedHeader = jwe.header;
2072
+ }
2073
+ if (resolvedKey) {
2074
+ return { ...result, key: k };
2075
+ }
2076
+ return result;
2077
+ }
2078
+ var init_decrypt = __esm(() => {
2079
+ init_base64url();
2080
+ init_content_encryption();
2081
+ init_helpers();
2082
+ init_errors();
2083
+ init_key_management();
2084
+ init_buffer_utils();
2085
+ init_content_encryption();
2086
+ init_validate_crit();
2087
+ init_normalize_key();
2088
+ init_check_key_type();
2089
+ init_deflate();
2090
+ });
2091
+
2092
+ // node_modules/jose/dist/webapi/jwe/compact/decrypt.js
2093
+ async function compactDecrypt(jwe, key, options) {
2094
+ if (jwe instanceof Uint8Array) {
2095
+ jwe = decoder.decode(jwe);
2096
+ }
2097
+ if (typeof jwe !== "string") {
2098
+ throw new JWEInvalid("Compact JWE must be a string or Uint8Array");
2099
+ }
2100
+ const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split(".");
2101
+ if (length !== 5) {
2102
+ throw new JWEInvalid("Invalid Compact JWE");
2103
+ }
2104
+ const decrypted = await flattenedDecrypt({
2105
+ ciphertext,
2106
+ iv: iv || undefined,
2107
+ protected: protectedHeader,
2108
+ tag: tag2 || undefined,
2109
+ encrypted_key: encryptedKey || undefined
2110
+ }, key, options);
2111
+ const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
2112
+ if (typeof key === "function") {
2113
+ return { ...result, key: decrypted.key };
2114
+ }
2115
+ return result;
2116
+ }
2117
+ var init_decrypt2 = __esm(() => {
2118
+ init_decrypt();
2119
+ init_errors();
2120
+ init_buffer_utils();
2121
+ });
2122
+
2123
+ // node_modules/jose/dist/webapi/jwe/general/decrypt.js
2124
+ async function generalDecrypt(jwe, key, options) {
2125
+ if (!isObject(jwe)) {
2126
+ throw new JWEInvalid("General JWE must be an object");
2127
+ }
2128
+ if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) {
2129
+ throw new JWEInvalid("JWE Recipients missing or incorrect type");
2130
+ }
2131
+ if (!jwe.recipients.length) {
2132
+ throw new JWEInvalid("JWE Recipients has no members");
2133
+ }
2134
+ for (const recipient of jwe.recipients) {
2135
+ try {
2136
+ return await flattenedDecrypt({
2137
+ aad: jwe.aad,
2138
+ ciphertext: jwe.ciphertext,
2139
+ encrypted_key: recipient.encrypted_key,
2140
+ header: recipient.header,
2141
+ iv: jwe.iv,
2142
+ protected: jwe.protected,
2143
+ tag: jwe.tag,
2144
+ unprotected: jwe.unprotected
2145
+ }, key, options);
2146
+ } catch {}
2147
+ }
2148
+ throw new JWEDecryptionFailed;
2149
+ }
2150
+ var init_decrypt3 = __esm(() => {
2151
+ init_decrypt();
2152
+ init_errors();
2153
+ });
2154
+
2155
+ // node_modules/jose/dist/webapi/jwe/flattened/encrypt.js
2156
+ class FlattenedEncrypt {
2157
+ #plaintext;
2158
+ #protectedHeader;
2159
+ #sharedUnprotectedHeader;
2160
+ #unprotectedHeader;
2161
+ #aad;
2162
+ #cek;
2163
+ #iv;
2164
+ #keyManagementParameters;
2165
+ constructor(plaintext) {
2166
+ if (!(plaintext instanceof Uint8Array)) {
2167
+ throw new TypeError("plaintext must be an instance of Uint8Array");
2168
+ }
2169
+ this.#plaintext = plaintext;
2170
+ }
2171
+ setKeyManagementParameters(parameters) {
2172
+ assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters");
2173
+ this.#keyManagementParameters = parameters;
2174
+ return this;
2175
+ }
2176
+ setProtectedHeader(protectedHeader) {
2177
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
2178
+ this.#protectedHeader = protectedHeader;
2179
+ return this;
2180
+ }
2181
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
2182
+ assertNotSet(this.#sharedUnprotectedHeader, "setSharedUnprotectedHeader");
2183
+ this.#sharedUnprotectedHeader = sharedUnprotectedHeader;
2184
+ return this;
2185
+ }
2186
+ setUnprotectedHeader(unprotectedHeader) {
2187
+ assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
2188
+ this.#unprotectedHeader = unprotectedHeader;
2189
+ return this;
2190
+ }
2191
+ setAdditionalAuthenticatedData(aad) {
2192
+ this.#aad = aad;
2193
+ return this;
2194
+ }
2195
+ setContentEncryptionKey(cek) {
2196
+ assertNotSet(this.#cek, "setContentEncryptionKey");
2197
+ this.#cek = cek;
2198
+ return this;
2199
+ }
2200
+ setInitializationVector(iv) {
2201
+ assertNotSet(this.#iv, "setInitializationVector");
2202
+ this.#iv = iv;
2203
+ return this;
2204
+ }
2205
+ async encrypt(key, options) {
2206
+ if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) {
2207
+ throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
2208
+ }
2209
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {
2210
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
2211
+ }
2212
+ const joseHeader = {
2213
+ ...this.#protectedHeader,
2214
+ ...this.#unprotectedHeader,
2215
+ ...this.#sharedUnprotectedHeader
2216
+ };
2217
+ validateCrit(JWEInvalid, new Map, options?.crit, this.#protectedHeader, joseHeader);
2218
+ if (joseHeader.zip !== undefined && joseHeader.zip !== "DEF") {
2219
+ throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
2220
+ }
2221
+ if (joseHeader.zip !== undefined && !this.#protectedHeader?.zip) {
2222
+ throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
2223
+ }
2224
+ const { alg, enc } = joseHeader;
2225
+ if (typeof alg !== "string" || !alg) {
2226
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
2227
+ }
2228
+ if (typeof enc !== "string" || !enc) {
2229
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
2230
+ }
2231
+ let encryptedKey;
2232
+ if (this.#cek && (alg === "dir" || alg === "ECDH-ES")) {
2233
+ throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
2234
+ }
2235
+ checkKeyType(alg === "dir" ? enc : alg, key, "encrypt");
2236
+ let cek;
2237
+ {
2238
+ let parameters;
2239
+ const k = await normalizeKey(key, alg);
2240
+ ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters));
2241
+ if (parameters) {
2242
+ if (options && unprotected in options) {
2243
+ if (!this.#unprotectedHeader) {
2244
+ this.setUnprotectedHeader(parameters);
2245
+ } else {
2246
+ this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters };
2247
+ }
2248
+ } else if (!this.#protectedHeader) {
2249
+ this.setProtectedHeader(parameters);
2250
+ } else {
2251
+ this.#protectedHeader = { ...this.#protectedHeader, ...parameters };
2252
+ }
2253
+ }
2254
+ }
2255
+ let additionalData;
2256
+ let protectedHeaderS;
2257
+ let protectedHeaderB;
2258
+ let aadMember;
2259
+ if (this.#protectedHeader) {
2260
+ protectedHeaderS = encode2(JSON.stringify(this.#protectedHeader));
2261
+ protectedHeaderB = encode(protectedHeaderS);
2262
+ } else {
2263
+ protectedHeaderS = "";
2264
+ protectedHeaderB = new Uint8Array;
2265
+ }
2266
+ if (this.#aad) {
2267
+ aadMember = encode2(this.#aad);
2268
+ const aadMemberBytes = encode(aadMember);
2269
+ additionalData = concat(protectedHeaderB, encode("."), aadMemberBytes);
2270
+ } else {
2271
+ additionalData = protectedHeaderB;
2272
+ }
2273
+ let plaintext = this.#plaintext;
2274
+ if (joseHeader.zip === "DEF") {
2275
+ plaintext = await compress(plaintext).catch((cause) => {
2276
+ throw new JWEInvalid("Failed to compress plaintext", { cause });
2277
+ });
2278
+ }
2279
+ const { ciphertext, tag: tag2, iv } = await encrypt(enc, plaintext, cek, this.#iv, additionalData);
2280
+ const jwe = {
2281
+ ciphertext: encode2(ciphertext)
2282
+ };
2283
+ if (iv) {
2284
+ jwe.iv = encode2(iv);
2285
+ }
2286
+ if (tag2) {
2287
+ jwe.tag = encode2(tag2);
2288
+ }
2289
+ if (encryptedKey) {
2290
+ jwe.encrypted_key = encode2(encryptedKey);
2291
+ }
2292
+ if (aadMember) {
2293
+ jwe.aad = aadMember;
2294
+ }
2295
+ if (this.#protectedHeader) {
2296
+ jwe.protected = protectedHeaderS;
2297
+ }
2298
+ if (this.#sharedUnprotectedHeader) {
2299
+ jwe.unprotected = this.#sharedUnprotectedHeader;
2300
+ }
2301
+ if (this.#unprotectedHeader) {
2302
+ jwe.header = this.#unprotectedHeader;
2303
+ }
2304
+ return jwe;
2305
+ }
2306
+ }
2307
+ var init_encrypt = __esm(() => {
2308
+ init_base64url();
2309
+ init_helpers();
2310
+ init_content_encryption();
2311
+ init_key_management();
2312
+ init_errors();
2313
+ init_buffer_utils();
2314
+ init_validate_crit();
2315
+ init_normalize_key();
2316
+ init_check_key_type();
2317
+ init_deflate();
2318
+ });
2319
+
2320
+ // node_modules/jose/dist/webapi/jwe/general/encrypt.js
2321
+ class IndividualRecipient {
2322
+ #parent;
2323
+ unprotectedHeader;
2324
+ keyManagementParameters;
2325
+ key;
2326
+ options;
2327
+ constructor(enc, key, options) {
2328
+ this.#parent = enc;
2329
+ this.key = key;
2330
+ this.options = options;
2331
+ }
2332
+ setUnprotectedHeader(unprotectedHeader) {
2333
+ assertNotSet(this.unprotectedHeader, "setUnprotectedHeader");
2334
+ this.unprotectedHeader = unprotectedHeader;
2335
+ return this;
2336
+ }
2337
+ setKeyManagementParameters(parameters) {
2338
+ assertNotSet(this.keyManagementParameters, "setKeyManagementParameters");
2339
+ this.keyManagementParameters = parameters;
2340
+ return this;
2341
+ }
2342
+ addRecipient(...args) {
2343
+ return this.#parent.addRecipient(...args);
2344
+ }
2345
+ encrypt(...args) {
2346
+ return this.#parent.encrypt(...args);
2347
+ }
2348
+ done() {
2349
+ return this.#parent;
2350
+ }
2351
+ }
2352
+
2353
+ class GeneralEncrypt {
2354
+ #plaintext;
2355
+ #recipients = [];
2356
+ #protectedHeader;
2357
+ #unprotectedHeader;
2358
+ #aad;
2359
+ constructor(plaintext) {
2360
+ this.#plaintext = plaintext;
2361
+ }
2362
+ addRecipient(key, options) {
2363
+ const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
2364
+ this.#recipients.push(recipient);
2365
+ return recipient;
2366
+ }
2367
+ setProtectedHeader(protectedHeader) {
2368
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
2369
+ this.#protectedHeader = protectedHeader;
2370
+ return this;
2371
+ }
2372
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
2373
+ assertNotSet(this.#unprotectedHeader, "setSharedUnprotectedHeader");
2374
+ this.#unprotectedHeader = sharedUnprotectedHeader;
2375
+ return this;
2376
+ }
2377
+ setAdditionalAuthenticatedData(aad) {
2378
+ this.#aad = aad;
2379
+ return this;
2380
+ }
2381
+ async encrypt() {
2382
+ if (!this.#recipients.length) {
2383
+ throw new JWEInvalid("at least one recipient must be added");
2384
+ }
2385
+ if (this.#recipients.length === 1) {
2386
+ const [recipient] = this.#recipients;
2387
+ const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options });
2388
+ const jwe2 = {
2389
+ ciphertext: flattened.ciphertext,
2390
+ iv: flattened.iv,
2391
+ recipients: [{}],
2392
+ tag: flattened.tag
2393
+ };
2394
+ if (flattened.aad)
2395
+ jwe2.aad = flattened.aad;
2396
+ if (flattened.protected)
2397
+ jwe2.protected = flattened.protected;
2398
+ if (flattened.unprotected)
2399
+ jwe2.unprotected = flattened.unprotected;
2400
+ if (flattened.encrypted_key)
2401
+ jwe2.recipients[0].encrypted_key = flattened.encrypted_key;
2402
+ if (flattened.header)
2403
+ jwe2.recipients[0].header = flattened.header;
2404
+ return jwe2;
2405
+ }
2406
+ let enc;
2407
+ for (let i = 0;i < this.#recipients.length; i++) {
2408
+ const recipient = this.#recipients[i];
2409
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, recipient.unprotectedHeader)) {
2410
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
2411
+ }
2412
+ const joseHeader = {
2413
+ ...this.#protectedHeader,
2414
+ ...this.#unprotectedHeader,
2415
+ ...recipient.unprotectedHeader
2416
+ };
2417
+ const { alg } = joseHeader;
2418
+ if (typeof alg !== "string" || !alg) {
2419
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
2420
+ }
2421
+ if (alg === "dir" || alg === "ECDH-ES") {
2422
+ throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
2423
+ }
2424
+ if (typeof joseHeader.enc !== "string" || !joseHeader.enc) {
2425
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
2426
+ }
2427
+ if (!enc) {
2428
+ enc = joseHeader.enc;
2429
+ } else if (enc !== joseHeader.enc) {
2430
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
2431
+ }
2432
+ validateCrit(JWEInvalid, new Map, recipient.options.crit, this.#protectedHeader, joseHeader);
2433
+ if (joseHeader.zip !== undefined && joseHeader.zip !== "DEF") {
2434
+ throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
2435
+ }
2436
+ if (joseHeader.zip !== undefined && !this.#protectedHeader?.zip) {
2437
+ throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
2438
+ }
2439
+ }
2440
+ const cek = generateCek(enc);
2441
+ const jwe = {
2442
+ ciphertext: "",
2443
+ recipients: []
2444
+ };
2445
+ for (let i = 0;i < this.#recipients.length; i++) {
2446
+ const recipient = this.#recipients[i];
2447
+ const target = {};
2448
+ jwe.recipients.push(target);
2449
+ if (i === 0) {
2450
+ 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, {
2451
+ ...recipient.options,
2452
+ [unprotected]: true
2453
+ });
2454
+ jwe.ciphertext = flattened.ciphertext;
2455
+ jwe.iv = flattened.iv;
2456
+ jwe.tag = flattened.tag;
2457
+ if (flattened.aad)
2458
+ jwe.aad = flattened.aad;
2459
+ if (flattened.protected)
2460
+ jwe.protected = flattened.protected;
2461
+ if (flattened.unprotected)
2462
+ jwe.unprotected = flattened.unprotected;
2463
+ target.encrypted_key = flattened.encrypted_key;
2464
+ if (flattened.header)
2465
+ target.header = flattened.header;
2466
+ continue;
2467
+ }
2468
+ const alg = recipient.unprotectedHeader?.alg || this.#protectedHeader?.alg || this.#unprotectedHeader?.alg;
2469
+ checkKeyType(alg === "dir" ? enc : alg, recipient.key, "encrypt");
2470
+ const k = await normalizeKey(recipient.key, alg);
2471
+ const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters);
2472
+ target.encrypted_key = encode2(encryptedKey);
2473
+ if (recipient.unprotectedHeader || parameters)
2474
+ target.header = { ...recipient.unprotectedHeader, ...parameters };
2475
+ }
2476
+ return jwe;
2477
+ }
2478
+ }
2479
+ var init_encrypt2 = __esm(() => {
2480
+ init_encrypt();
2481
+ init_helpers();
2482
+ init_errors();
2483
+ init_content_encryption();
2484
+ init_key_management();
2485
+ init_base64url();
2486
+ init_validate_crit();
2487
+ init_normalize_key();
2488
+ init_check_key_type();
2489
+ });
2490
+
2491
+ // node_modules/jose/dist/webapi/jws/flattened/verify.js
2492
+ async function flattenedVerify(jws, key, options) {
2493
+ if (!isObject(jws)) {
2494
+ throw new JWSInvalid("Flattened JWS must be an object");
2495
+ }
2496
+ if (jws.protected === undefined && jws.header === undefined) {
2497
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
2498
+ }
2499
+ if (jws.protected !== undefined && typeof jws.protected !== "string") {
2500
+ throw new JWSInvalid("JWS Protected Header incorrect type");
2501
+ }
2502
+ if (jws.payload === undefined) {
2503
+ throw new JWSInvalid("JWS Payload missing");
2504
+ }
2505
+ if (typeof jws.signature !== "string") {
2506
+ throw new JWSInvalid("JWS Signature missing or incorrect type");
2507
+ }
2508
+ if (jws.header !== undefined && !isObject(jws.header)) {
2509
+ throw new JWSInvalid("JWS Unprotected Header incorrect type");
2510
+ }
2511
+ let parsedProt = {};
2512
+ if (jws.protected) {
2513
+ try {
2514
+ const protectedHeader = decode(jws.protected);
2515
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
2516
+ } catch {
2517
+ throw new JWSInvalid("JWS Protected Header is invalid");
2518
+ }
2519
+ }
2520
+ if (!isDisjoint(parsedProt, jws.header)) {
2521
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
2522
+ }
2523
+ const joseHeader = {
2524
+ ...parsedProt,
2525
+ ...jws.header
2526
+ };
2527
+ const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
2528
+ let b64 = true;
2529
+ if (extensions.has("b64")) {
2530
+ b64 = parsedProt.b64;
2531
+ if (typeof b64 !== "boolean") {
2532
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
2533
+ }
2534
+ }
2535
+ const { alg } = joseHeader;
2536
+ if (typeof alg !== "string" || !alg) {
2537
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
2538
+ }
2539
+ const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
2540
+ if (algorithms && !algorithms.has(alg)) {
2541
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
2542
+ }
2543
+ if (b64) {
2544
+ if (typeof jws.payload !== "string") {
2545
+ throw new JWSInvalid("JWS Payload must be a string");
2546
+ }
2547
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
2548
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
2549
+ }
2550
+ let resolvedKey = false;
2551
+ if (typeof key === "function") {
2552
+ key = await key(parsedProt, jws);
2553
+ resolvedKey = true;
2554
+ }
2555
+ checkKeyType(alg, key, "verify");
2556
+ const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array, encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
2557
+ const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
2558
+ const k = await normalizeKey(key, alg);
2559
+ const verified = await verify(alg, k, signature, data);
2560
+ if (!verified) {
2561
+ throw new JWSSignatureVerificationFailed;
2562
+ }
2563
+ let payload;
2564
+ if (b64) {
2565
+ payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
2566
+ } else if (typeof jws.payload === "string") {
897
2567
  payload = encoder.encode(jws.payload);
898
2568
  } else {
899
2569
  payload = jws.payload;
@@ -910,6 +2580,16 @@ async function flattenedVerify(jws, key, options) {
910
2580
  }
911
2581
  return result;
912
2582
  }
2583
+ var init_verify = __esm(() => {
2584
+ init_base64url();
2585
+ init_signing();
2586
+ init_errors();
2587
+ init_buffer_utils();
2588
+ init_helpers();
2589
+ init_check_key_type();
2590
+ init_validate_crit();
2591
+ init_normalize_key();
2592
+ });
913
2593
 
914
2594
  // node_modules/jose/dist/webapi/jws/compact/verify.js
915
2595
  async function compactVerify(jws, key, options) {
@@ -930,15 +2610,38 @@ async function compactVerify(jws, key, options) {
930
2610
  }
931
2611
  return result;
932
2612
  }
2613
+ var init_verify2 = __esm(() => {
2614
+ init_verify();
2615
+ init_errors();
2616
+ init_buffer_utils();
2617
+ });
2618
+
2619
+ // node_modules/jose/dist/webapi/jws/general/verify.js
2620
+ async function generalVerify(jws, key, options) {
2621
+ if (!isObject(jws)) {
2622
+ throw new JWSInvalid("General JWS must be an object");
2623
+ }
2624
+ if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) {
2625
+ throw new JWSInvalid("JWS Signatures missing or incorrect type");
2626
+ }
2627
+ for (const signature of jws.signatures) {
2628
+ try {
2629
+ return await flattenedVerify({
2630
+ header: signature.header,
2631
+ payload: jws.payload,
2632
+ protected: signature.protected,
2633
+ signature: signature.signature
2634
+ }, key, options);
2635
+ } catch {}
2636
+ }
2637
+ throw new JWSSignatureVerificationFailed;
2638
+ }
2639
+ var init_verify3 = __esm(() => {
2640
+ init_verify();
2641
+ init_errors();
2642
+ });
933
2643
 
934
2644
  // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
935
- var epoch = (date) => Math.floor(date.getTime() / 1000);
936
- var minute = 60;
937
- var hour = minute * 60;
938
- var day = hour * 24;
939
- var week = day * 7;
940
- var year = day * 365.25;
941
- var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
942
2645
  function secs(str) {
943
2646
  const matched = REGEX.exec(str);
944
2647
  if (!matched || matched[4] && matched[1]) {
@@ -994,21 +2697,6 @@ function validateInput(label, input) {
994
2697
  }
995
2698
  return input;
996
2699
  }
997
- var normalizeTyp = (value) => {
998
- if (value.includes("/")) {
999
- return value.toLowerCase();
1000
- }
1001
- return `application/${value.toLowerCase()}`;
1002
- };
1003
- var checkAudiencePresence = (audPayload, audOption) => {
1004
- if (typeof audPayload === "string") {
1005
- return audOption.includes(audPayload);
1006
- }
1007
- if (Array.isArray(audPayload)) {
1008
- return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
1009
- }
1010
- return false;
1011
- };
1012
2700
  function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
1013
2701
  let payload;
1014
2702
  try {
@@ -1155,126 +2843,831 @@ class JWTClaimsBuilder {
1155
2843
  }
1156
2844
  }
1157
2845
  }
2846
+ var epoch = (date) => Math.floor(date.getTime() / 1000), minute = 60, hour, day, week, year, REGEX, normalizeTyp = (value) => {
2847
+ if (value.includes("/")) {
2848
+ return value.toLowerCase();
2849
+ }
2850
+ return `application/${value.toLowerCase()}`;
2851
+ }, checkAudiencePresence = (audPayload, audOption) => {
2852
+ if (typeof audPayload === "string") {
2853
+ return audOption.includes(audPayload);
2854
+ }
2855
+ if (Array.isArray(audPayload)) {
2856
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
2857
+ }
2858
+ return false;
2859
+ };
2860
+ var init_jwt_claims_set = __esm(() => {
2861
+ init_errors();
2862
+ init_buffer_utils();
2863
+ hour = minute * 60;
2864
+ day = hour * 24;
2865
+ week = day * 7;
2866
+ year = day * 365.25;
2867
+ REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
2868
+ });
2869
+
2870
+ // node_modules/jose/dist/webapi/jwt/verify.js
2871
+ async function jwtVerify(jwt, key, options) {
2872
+ const verified = await compactVerify(jwt, key, options);
2873
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
2874
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
2875
+ }
2876
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
2877
+ const result = { payload, protectedHeader: verified.protectedHeader };
2878
+ if (typeof key === "function") {
2879
+ return { ...result, key: verified.key };
2880
+ }
2881
+ return result;
2882
+ }
2883
+ var init_verify4 = __esm(() => {
2884
+ init_verify2();
2885
+ init_jwt_claims_set();
2886
+ init_errors();
2887
+ });
2888
+
2889
+ // node_modules/jose/dist/webapi/jwt/decrypt.js
2890
+ async function jwtDecrypt(jwt, key, options) {
2891
+ const decrypted = await compactDecrypt(jwt, key, options);
2892
+ const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options);
2893
+ const { protectedHeader } = decrypted;
2894
+ if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {
2895
+ throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch");
2896
+ }
2897
+ if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {
2898
+ throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch");
2899
+ }
2900
+ if (protectedHeader.aud !== undefined && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
2901
+ throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch");
2902
+ }
2903
+ const result = { payload, protectedHeader };
2904
+ if (typeof key === "function") {
2905
+ return { ...result, key: decrypted.key };
2906
+ }
2907
+ return result;
2908
+ }
2909
+ var init_decrypt4 = __esm(() => {
2910
+ init_decrypt2();
2911
+ init_jwt_claims_set();
2912
+ init_errors();
2913
+ });
2914
+
2915
+ // node_modules/jose/dist/webapi/jwe/compact/encrypt.js
2916
+ class CompactEncrypt {
2917
+ #flattened;
2918
+ constructor(plaintext) {
2919
+ this.#flattened = new FlattenedEncrypt(plaintext);
2920
+ }
2921
+ setContentEncryptionKey(cek) {
2922
+ this.#flattened.setContentEncryptionKey(cek);
2923
+ return this;
2924
+ }
2925
+ setInitializationVector(iv) {
2926
+ this.#flattened.setInitializationVector(iv);
2927
+ return this;
2928
+ }
2929
+ setProtectedHeader(protectedHeader) {
2930
+ this.#flattened.setProtectedHeader(protectedHeader);
2931
+ return this;
2932
+ }
2933
+ setKeyManagementParameters(parameters) {
2934
+ this.#flattened.setKeyManagementParameters(parameters);
2935
+ return this;
2936
+ }
2937
+ async encrypt(key, options) {
2938
+ const jwe = await this.#flattened.encrypt(key, options);
2939
+ return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join(".");
2940
+ }
2941
+ }
2942
+ var init_encrypt3 = __esm(() => {
2943
+ init_encrypt();
2944
+ });
2945
+
2946
+ // node_modules/jose/dist/webapi/jws/flattened/sign.js
2947
+ class FlattenedSign {
2948
+ #payload;
2949
+ #protectedHeader;
2950
+ #unprotectedHeader;
2951
+ constructor(payload) {
2952
+ if (!(payload instanceof Uint8Array)) {
2953
+ throw new TypeError("payload must be an instance of Uint8Array");
2954
+ }
2955
+ this.#payload = payload;
2956
+ }
2957
+ setProtectedHeader(protectedHeader) {
2958
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
2959
+ this.#protectedHeader = protectedHeader;
2960
+ return this;
2961
+ }
2962
+ setUnprotectedHeader(unprotectedHeader) {
2963
+ assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
2964
+ this.#unprotectedHeader = unprotectedHeader;
2965
+ return this;
2966
+ }
2967
+ async sign(key, options) {
2968
+ if (!this.#protectedHeader && !this.#unprotectedHeader) {
2969
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
2970
+ }
2971
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {
2972
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
2973
+ }
2974
+ const joseHeader = {
2975
+ ...this.#protectedHeader,
2976
+ ...this.#unprotectedHeader
2977
+ };
2978
+ const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
2979
+ let b64 = true;
2980
+ if (extensions.has("b64")) {
2981
+ b64 = this.#protectedHeader.b64;
2982
+ if (typeof b64 !== "boolean") {
2983
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
2984
+ }
2985
+ }
2986
+ const { alg } = joseHeader;
2987
+ if (typeof alg !== "string" || !alg) {
2988
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
2989
+ }
2990
+ checkKeyType(alg, key, "sign");
2991
+ let payloadS;
2992
+ let payloadB;
2993
+ if (b64) {
2994
+ payloadS = encode2(this.#payload);
2995
+ payloadB = encode(payloadS);
2996
+ } else {
2997
+ payloadB = this.#payload;
2998
+ payloadS = "";
2999
+ }
3000
+ let protectedHeaderString;
3001
+ let protectedHeaderBytes;
3002
+ if (this.#protectedHeader) {
3003
+ protectedHeaderString = encode2(JSON.stringify(this.#protectedHeader));
3004
+ protectedHeaderBytes = encode(protectedHeaderString);
3005
+ } else {
3006
+ protectedHeaderString = "";
3007
+ protectedHeaderBytes = new Uint8Array;
3008
+ }
3009
+ const data = concat(protectedHeaderBytes, encode("."), payloadB);
3010
+ const k = await normalizeKey(key, alg);
3011
+ const signature = await sign(alg, k, data);
3012
+ const jws = {
3013
+ signature: encode2(signature),
3014
+ payload: payloadS
3015
+ };
3016
+ if (this.#unprotectedHeader) {
3017
+ jws.header = this.#unprotectedHeader;
3018
+ }
3019
+ if (this.#protectedHeader) {
3020
+ jws.protected = protectedHeaderString;
3021
+ }
3022
+ return jws;
3023
+ }
3024
+ }
3025
+ var init_sign = __esm(() => {
3026
+ init_base64url();
3027
+ init_signing();
3028
+ init_errors();
3029
+ init_buffer_utils();
3030
+ init_check_key_type();
3031
+ init_validate_crit();
3032
+ init_normalize_key();
3033
+ init_helpers();
3034
+ });
3035
+
3036
+ // node_modules/jose/dist/webapi/jws/compact/sign.js
3037
+ class CompactSign {
3038
+ #flattened;
3039
+ constructor(payload) {
3040
+ this.#flattened = new FlattenedSign(payload);
3041
+ }
3042
+ setProtectedHeader(protectedHeader) {
3043
+ this.#flattened.setProtectedHeader(protectedHeader);
3044
+ return this;
3045
+ }
3046
+ async sign(key, options) {
3047
+ const jws = await this.#flattened.sign(key, options);
3048
+ if (jws.payload === undefined) {
3049
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
3050
+ }
3051
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
3052
+ }
3053
+ }
3054
+ var init_sign2 = __esm(() => {
3055
+ init_sign();
3056
+ });
3057
+
3058
+ // node_modules/jose/dist/webapi/jws/general/sign.js
3059
+ class IndividualSignature {
3060
+ #parent;
3061
+ protectedHeader;
3062
+ unprotectedHeader;
3063
+ options;
3064
+ key;
3065
+ constructor(sig, key, options) {
3066
+ this.#parent = sig;
3067
+ this.key = key;
3068
+ this.options = options;
3069
+ }
3070
+ setProtectedHeader(protectedHeader) {
3071
+ assertNotSet(this.protectedHeader, "setProtectedHeader");
3072
+ this.protectedHeader = protectedHeader;
3073
+ return this;
3074
+ }
3075
+ setUnprotectedHeader(unprotectedHeader) {
3076
+ assertNotSet(this.unprotectedHeader, "setUnprotectedHeader");
3077
+ this.unprotectedHeader = unprotectedHeader;
3078
+ return this;
3079
+ }
3080
+ addSignature(...args) {
3081
+ return this.#parent.addSignature(...args);
3082
+ }
3083
+ sign(...args) {
3084
+ return this.#parent.sign(...args);
3085
+ }
3086
+ done() {
3087
+ return this.#parent;
3088
+ }
3089
+ }
3090
+
3091
+ class GeneralSign {
3092
+ #payload;
3093
+ #signatures = [];
3094
+ constructor(payload) {
3095
+ this.#payload = payload;
3096
+ }
3097
+ addSignature(key, options) {
3098
+ const signature = new IndividualSignature(this, key, options);
3099
+ this.#signatures.push(signature);
3100
+ return signature;
3101
+ }
3102
+ async sign() {
3103
+ if (!this.#signatures.length) {
3104
+ throw new JWSInvalid("at least one signature must be added");
3105
+ }
3106
+ const jws = {
3107
+ signatures: [],
3108
+ payload: ""
3109
+ };
3110
+ for (let i = 0;i < this.#signatures.length; i++) {
3111
+ const signature = this.#signatures[i];
3112
+ const flattened = new FlattenedSign(this.#payload);
3113
+ flattened.setProtectedHeader(signature.protectedHeader);
3114
+ flattened.setUnprotectedHeader(signature.unprotectedHeader);
3115
+ const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
3116
+ if (i === 0) {
3117
+ jws.payload = payload;
3118
+ } else if (jws.payload !== payload) {
3119
+ throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");
3120
+ }
3121
+ jws.signatures.push(rest);
3122
+ }
3123
+ return jws;
3124
+ }
3125
+ }
3126
+ var init_sign3 = __esm(() => {
3127
+ init_sign();
3128
+ init_errors();
3129
+ init_helpers();
3130
+ });
3131
+
3132
+ // node_modules/jose/dist/webapi/jwt/sign.js
3133
+ class SignJWT {
3134
+ #protectedHeader;
3135
+ #jwt;
3136
+ constructor(payload = {}) {
3137
+ this.#jwt = new JWTClaimsBuilder(payload);
3138
+ }
3139
+ setIssuer(issuer) {
3140
+ this.#jwt.iss = issuer;
3141
+ return this;
3142
+ }
3143
+ setSubject(subject) {
3144
+ this.#jwt.sub = subject;
3145
+ return this;
3146
+ }
3147
+ setAudience(audience) {
3148
+ this.#jwt.aud = audience;
3149
+ return this;
3150
+ }
3151
+ setJti(jwtId) {
3152
+ this.#jwt.jti = jwtId;
3153
+ return this;
3154
+ }
3155
+ setNotBefore(input) {
3156
+ this.#jwt.nbf = input;
3157
+ return this;
3158
+ }
3159
+ setExpirationTime(input) {
3160
+ this.#jwt.exp = input;
3161
+ return this;
3162
+ }
3163
+ setIssuedAt(input) {
3164
+ this.#jwt.iat = input;
3165
+ return this;
3166
+ }
3167
+ setProtectedHeader(protectedHeader) {
3168
+ this.#protectedHeader = protectedHeader;
3169
+ return this;
3170
+ }
3171
+ async sign(key, options) {
3172
+ const sig = new CompactSign(this.#jwt.data());
3173
+ sig.setProtectedHeader(this.#protectedHeader);
3174
+ if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) {
3175
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3176
+ }
3177
+ return sig.sign(key, options);
3178
+ }
3179
+ }
3180
+ var init_sign4 = __esm(() => {
3181
+ init_sign2();
3182
+ init_errors();
3183
+ init_jwt_claims_set();
3184
+ });
3185
+
3186
+ // node_modules/jose/dist/webapi/jwt/encrypt.js
3187
+ class EncryptJWT {
3188
+ #cek;
3189
+ #iv;
3190
+ #keyManagementParameters;
3191
+ #protectedHeader;
3192
+ #replicateIssuerAsHeader;
3193
+ #replicateSubjectAsHeader;
3194
+ #replicateAudienceAsHeader;
3195
+ #jwt;
3196
+ constructor(payload = {}) {
3197
+ this.#jwt = new JWTClaimsBuilder(payload);
3198
+ }
3199
+ setIssuer(issuer) {
3200
+ this.#jwt.iss = issuer;
3201
+ return this;
3202
+ }
3203
+ setSubject(subject) {
3204
+ this.#jwt.sub = subject;
3205
+ return this;
3206
+ }
3207
+ setAudience(audience) {
3208
+ this.#jwt.aud = audience;
3209
+ return this;
3210
+ }
3211
+ setJti(jwtId) {
3212
+ this.#jwt.jti = jwtId;
3213
+ return this;
3214
+ }
3215
+ setNotBefore(input) {
3216
+ this.#jwt.nbf = input;
3217
+ return this;
3218
+ }
3219
+ setExpirationTime(input) {
3220
+ this.#jwt.exp = input;
3221
+ return this;
3222
+ }
3223
+ setIssuedAt(input) {
3224
+ this.#jwt.iat = input;
3225
+ return this;
3226
+ }
3227
+ setProtectedHeader(protectedHeader) {
3228
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
3229
+ this.#protectedHeader = protectedHeader;
3230
+ return this;
3231
+ }
3232
+ setKeyManagementParameters(parameters) {
3233
+ assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters");
3234
+ this.#keyManagementParameters = parameters;
3235
+ return this;
3236
+ }
3237
+ setContentEncryptionKey(cek) {
3238
+ assertNotSet(this.#cek, "setContentEncryptionKey");
3239
+ this.#cek = cek;
3240
+ return this;
3241
+ }
3242
+ setInitializationVector(iv) {
3243
+ assertNotSet(this.#iv, "setInitializationVector");
3244
+ this.#iv = iv;
3245
+ return this;
3246
+ }
3247
+ replicateIssuerAsHeader() {
3248
+ this.#replicateIssuerAsHeader = true;
3249
+ return this;
3250
+ }
3251
+ replicateSubjectAsHeader() {
3252
+ this.#replicateSubjectAsHeader = true;
3253
+ return this;
3254
+ }
3255
+ replicateAudienceAsHeader() {
3256
+ this.#replicateAudienceAsHeader = true;
3257
+ return this;
3258
+ }
3259
+ async encrypt(key, options) {
3260
+ const enc = new CompactEncrypt(this.#jwt.data());
3261
+ if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) {
3262
+ this.#protectedHeader = {
3263
+ ...this.#protectedHeader,
3264
+ iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : undefined,
3265
+ sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : undefined,
3266
+ aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : undefined
3267
+ };
3268
+ }
3269
+ enc.setProtectedHeader(this.#protectedHeader);
3270
+ if (this.#iv) {
3271
+ enc.setInitializationVector(this.#iv);
3272
+ }
3273
+ if (this.#cek) {
3274
+ enc.setContentEncryptionKey(this.#cek);
3275
+ }
3276
+ if (this.#keyManagementParameters) {
3277
+ enc.setKeyManagementParameters(this.#keyManagementParameters);
3278
+ }
3279
+ return enc.encrypt(key, options);
3280
+ }
3281
+ }
3282
+ var init_encrypt4 = __esm(() => {
3283
+ init_encrypt3();
3284
+ init_jwt_claims_set();
3285
+ init_helpers();
3286
+ });
3287
+
3288
+ // node_modules/jose/dist/webapi/jwk/thumbprint.js
3289
+ async function calculateJwkThumbprint(key, digestAlgorithm) {
3290
+ let jwk;
3291
+ if (isJWK(key)) {
3292
+ jwk = key;
3293
+ } else if (isKeyLike(key)) {
3294
+ jwk = await exportJWK(key);
3295
+ } else {
3296
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
3297
+ }
3298
+ digestAlgorithm ??= "sha256";
3299
+ if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") {
3300
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
3301
+ }
3302
+ let components;
3303
+ switch (jwk.kty) {
3304
+ case "AKP":
3305
+ check(jwk.alg, '"alg" (Algorithm) Parameter');
3306
+ check(jwk.pub, '"pub" (Public key) Parameter');
3307
+ components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
3308
+ break;
3309
+ case "EC":
3310
+ check(jwk.crv, '"crv" (Curve) Parameter');
3311
+ check(jwk.x, '"x" (X Coordinate) Parameter');
3312
+ check(jwk.y, '"y" (Y Coordinate) Parameter');
3313
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
3314
+ break;
3315
+ case "OKP":
3316
+ check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
3317
+ check(jwk.x, '"x" (Public Key) Parameter');
3318
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
3319
+ break;
3320
+ case "RSA":
3321
+ check(jwk.e, '"e" (Exponent) Parameter');
3322
+ check(jwk.n, '"n" (Modulus) Parameter');
3323
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
3324
+ break;
3325
+ case "oct":
3326
+ check(jwk.k, '"k" (Key Value) Parameter');
3327
+ components = { k: jwk.k, kty: jwk.kty };
3328
+ break;
3329
+ default:
3330
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
3331
+ }
3332
+ const data = encode(JSON.stringify(components));
3333
+ return encode2(await digest(digestAlgorithm, data));
3334
+ }
3335
+ async function calculateJwkThumbprintUri(key, digestAlgorithm) {
3336
+ digestAlgorithm ??= "sha256";
3337
+ const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);
3338
+ return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
3339
+ }
3340
+ var check = (value, description) => {
3341
+ if (typeof value !== "string" || !value) {
3342
+ throw new JWKInvalid(`${description} missing or invalid`);
3343
+ }
3344
+ };
3345
+ var init_thumbprint = __esm(() => {
3346
+ init_helpers();
3347
+ init_base64url();
3348
+ init_errors();
3349
+ init_buffer_utils();
3350
+ init_export();
3351
+ });
3352
+
3353
+ // node_modules/jose/dist/webapi/jwk/embedded.js
3354
+ async function EmbeddedJWK(protectedHeader, token) {
3355
+ const joseHeader = {
3356
+ ...protectedHeader,
3357
+ ...token?.header
3358
+ };
3359
+ if (!isObject(joseHeader.jwk)) {
3360
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
3361
+ }
3362
+ const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
3363
+ if (key instanceof Uint8Array || key.type !== "public") {
3364
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
3365
+ }
3366
+ return key;
3367
+ }
3368
+ var init_embedded = __esm(() => {
3369
+ init_import();
3370
+ init_errors();
3371
+ });
3372
+
3373
+ // node_modules/jose/dist/webapi/jwks/local.js
3374
+ function getKtyFromAlg(alg) {
3375
+ switch (typeof alg === "string" && alg.slice(0, 2)) {
3376
+ case "RS":
3377
+ case "PS":
3378
+ return "RSA";
3379
+ case "ES":
3380
+ return "EC";
3381
+ case "Ed":
3382
+ return "OKP";
3383
+ case "ML":
3384
+ return "AKP";
3385
+ default:
3386
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
3387
+ }
3388
+ }
3389
+ function isJWKSLike(jwks) {
3390
+ return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
3391
+ }
3392
+ function isJWKLike(key) {
3393
+ return isObject(key);
3394
+ }
3395
+
3396
+ class LocalJWKSet {
3397
+ #jwks;
3398
+ #cached = new WeakMap;
3399
+ constructor(jwks) {
3400
+ if (!isJWKSLike(jwks)) {
3401
+ throw new JWKSInvalid("JSON Web Key Set malformed");
3402
+ }
3403
+ this.#jwks = structuredClone(jwks);
3404
+ }
3405
+ jwks() {
3406
+ return this.#jwks;
3407
+ }
3408
+ async getKey(protectedHeader, token) {
3409
+ const { alg, kid } = { ...protectedHeader, ...token?.header };
3410
+ const kty = getKtyFromAlg(alg);
3411
+ const candidates = this.#jwks.keys.filter((jwk2) => {
3412
+ let candidate = kty === jwk2.kty;
3413
+ if (candidate && typeof kid === "string") {
3414
+ candidate = kid === jwk2.kid;
3415
+ }
3416
+ if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) {
3417
+ candidate = alg === jwk2.alg;
3418
+ }
3419
+ if (candidate && typeof jwk2.use === "string") {
3420
+ candidate = jwk2.use === "sig";
3421
+ }
3422
+ if (candidate && Array.isArray(jwk2.key_ops)) {
3423
+ candidate = jwk2.key_ops.includes("verify");
3424
+ }
3425
+ if (candidate) {
3426
+ switch (alg) {
3427
+ case "ES256":
3428
+ candidate = jwk2.crv === "P-256";
3429
+ break;
3430
+ case "ES384":
3431
+ candidate = jwk2.crv === "P-384";
3432
+ break;
3433
+ case "ES512":
3434
+ candidate = jwk2.crv === "P-521";
3435
+ break;
3436
+ case "Ed25519":
3437
+ case "EdDSA":
3438
+ candidate = jwk2.crv === "Ed25519";
3439
+ break;
3440
+ }
3441
+ }
3442
+ return candidate;
3443
+ });
3444
+ const { 0: jwk, length } = candidates;
3445
+ if (length === 0) {
3446
+ throw new JWKSNoMatchingKey;
3447
+ }
3448
+ if (length !== 1) {
3449
+ const error = new JWKSMultipleMatchingKeys;
3450
+ const _cached = this.#cached;
3451
+ error[Symbol.asyncIterator] = async function* () {
3452
+ for (const jwk2 of candidates) {
3453
+ try {
3454
+ yield await importWithAlgCache(_cached, jwk2, alg);
3455
+ } catch {}
3456
+ }
3457
+ };
3458
+ throw error;
3459
+ }
3460
+ return importWithAlgCache(this.#cached, jwk, alg);
3461
+ }
3462
+ }
3463
+ async function importWithAlgCache(cache2, jwk, alg) {
3464
+ const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk);
3465
+ if (cached[alg] === undefined) {
3466
+ const key = await importJWK({ ...jwk, ext: true }, alg);
3467
+ if (key instanceof Uint8Array || key.type !== "public") {
3468
+ throw new JWKSInvalid("JSON Web Key Set members must be public keys");
3469
+ }
3470
+ cached[alg] = key;
3471
+ }
3472
+ return cached[alg];
3473
+ }
3474
+ function createLocalJWKSet(jwks) {
3475
+ const set = new LocalJWKSet(jwks);
3476
+ const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
3477
+ Object.defineProperties(localJWKSet, {
3478
+ jwks: {
3479
+ value: () => structuredClone(set.jwks()),
3480
+ enumerable: false,
3481
+ configurable: false,
3482
+ writable: false
3483
+ }
3484
+ });
3485
+ return localJWKSet;
3486
+ }
3487
+ var init_local = __esm(() => {
3488
+ init_import();
3489
+ init_errors();
3490
+ });
1158
3491
 
1159
- // node_modules/jose/dist/webapi/jwt/verify.js
1160
- async function jwtVerify(jwt, key, options) {
1161
- const verified = await compactVerify(jwt, key, options);
1162
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
1163
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3492
+ // node_modules/jose/dist/webapi/jwks/remote.js
3493
+ function isCloudflareWorkers() {
3494
+ return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
3495
+ }
3496
+ async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
3497
+ const response = await fetchImpl(url, {
3498
+ method: "GET",
3499
+ signal,
3500
+ redirect: "manual",
3501
+ headers
3502
+ }).catch((err) => {
3503
+ if (err.name === "TimeoutError") {
3504
+ throw new JWKSTimeout;
3505
+ }
3506
+ throw err;
3507
+ });
3508
+ if (response.status !== 200) {
3509
+ throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
1164
3510
  }
1165
- const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
1166
- const result = { payload, protectedHeader: verified.protectedHeader };
1167
- if (typeof key === "function") {
1168
- return { ...result, key: verified.key };
3511
+ try {
3512
+ return await response.json();
3513
+ } catch {
3514
+ throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
1169
3515
  }
1170
- return result;
1171
3516
  }
1172
- // node_modules/jose/dist/webapi/jws/flattened/sign.js
1173
- class FlattenedSign {
1174
- #payload;
1175
- #protectedHeader;
1176
- #unprotectedHeader;
1177
- constructor(payload) {
1178
- if (!(payload instanceof Uint8Array)) {
1179
- throw new TypeError("payload must be an instance of Uint8Array");
1180
- }
1181
- this.#payload = payload;
3517
+ function isFreshJwksCache(input, cacheMaxAge) {
3518
+ if (typeof input !== "object" || input === null) {
3519
+ return false;
1182
3520
  }
1183
- setProtectedHeader(protectedHeader) {
1184
- assertNotSet(this.#protectedHeader, "setProtectedHeader");
1185
- this.#protectedHeader = protectedHeader;
1186
- return this;
3521
+ if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) {
3522
+ return false;
1187
3523
  }
1188
- setUnprotectedHeader(unprotectedHeader) {
1189
- assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
1190
- this.#unprotectedHeader = unprotectedHeader;
1191
- return this;
3524
+ if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) {
3525
+ return false;
1192
3526
  }
1193
- async sign(key, options) {
1194
- if (!this.#protectedHeader && !this.#unprotectedHeader) {
1195
- throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
1196
- }
1197
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {
1198
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
3527
+ return true;
3528
+ }
3529
+
3530
+ class RemoteJWKSet {
3531
+ #url;
3532
+ #timeoutDuration;
3533
+ #cooldownDuration;
3534
+ #cacheMaxAge;
3535
+ #jwksTimestamp;
3536
+ #pendingFetch;
3537
+ #headers;
3538
+ #customFetch;
3539
+ #local;
3540
+ #cache;
3541
+ constructor(url, options) {
3542
+ if (!(url instanceof URL)) {
3543
+ throw new TypeError("url must be an instance of URL");
1199
3544
  }
1200
- const joseHeader = {
1201
- ...this.#protectedHeader,
1202
- ...this.#unprotectedHeader
1203
- };
1204
- const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
1205
- let b64 = true;
1206
- if (extensions.has("b64")) {
1207
- b64 = this.#protectedHeader.b64;
1208
- if (typeof b64 !== "boolean") {
1209
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1210
- }
3545
+ this.#url = new URL(url.href);
3546
+ this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5000;
3547
+ this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 30000;
3548
+ this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 600000;
3549
+ this.#headers = new Headers(options?.headers);
3550
+ if (USER_AGENT && !this.#headers.has("User-Agent")) {
3551
+ this.#headers.set("User-Agent", USER_AGENT);
1211
3552
  }
1212
- const { alg } = joseHeader;
1213
- if (typeof alg !== "string" || !alg) {
1214
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
3553
+ if (!this.#headers.has("accept")) {
3554
+ this.#headers.set("accept", "application/json");
3555
+ this.#headers.append("accept", "application/jwk-set+json");
1215
3556
  }
1216
- checkKeyType(alg, key, "sign");
1217
- let payloadS;
1218
- let payloadB;
1219
- if (b64) {
1220
- payloadS = encode2(this.#payload);
1221
- payloadB = encode(payloadS);
1222
- } else {
1223
- payloadB = this.#payload;
1224
- payloadS = "";
3557
+ this.#customFetch = options?.[customFetch];
3558
+ if (options?.[jwksCache] !== undefined) {
3559
+ this.#cache = options?.[jwksCache];
3560
+ if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
3561
+ this.#jwksTimestamp = this.#cache.uat;
3562
+ this.#local = createLocalJWKSet(this.#cache.jwks);
3563
+ }
1225
3564
  }
1226
- let protectedHeaderString;
1227
- let protectedHeaderBytes;
1228
- if (this.#protectedHeader) {
1229
- protectedHeaderString = encode2(JSON.stringify(this.#protectedHeader));
1230
- protectedHeaderBytes = encode(protectedHeaderString);
1231
- } else {
1232
- protectedHeaderString = "";
1233
- protectedHeaderBytes = new Uint8Array;
3565
+ }
3566
+ pendingFetch() {
3567
+ return !!this.#pendingFetch;
3568
+ }
3569
+ coolingDown() {
3570
+ return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false;
3571
+ }
3572
+ fresh() {
3573
+ return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false;
3574
+ }
3575
+ jwks() {
3576
+ return this.#local?.jwks();
3577
+ }
3578
+ async getKey(protectedHeader, token) {
3579
+ if (!this.#local || !this.fresh()) {
3580
+ await this.reload();
1234
3581
  }
1235
- const data = concat(protectedHeaderBytes, encode("."), payloadB);
1236
- const k = await normalizeKey(key, alg);
1237
- const signature = await sign(alg, k, data);
1238
- const jws = {
1239
- signature: encode2(signature),
1240
- payload: payloadS
1241
- };
1242
- if (this.#unprotectedHeader) {
1243
- jws.header = this.#unprotectedHeader;
3582
+ try {
3583
+ return await this.#local(protectedHeader, token);
3584
+ } catch (err) {
3585
+ if (err instanceof JWKSNoMatchingKey) {
3586
+ if (this.coolingDown() === false) {
3587
+ await this.reload();
3588
+ return this.#local(protectedHeader, token);
3589
+ }
3590
+ }
3591
+ throw err;
1244
3592
  }
1245
- if (this.#protectedHeader) {
1246
- jws.protected = protectedHeaderString;
3593
+ }
3594
+ async reload() {
3595
+ if (this.#pendingFetch && isCloudflareWorkers()) {
3596
+ this.#pendingFetch = undefined;
1247
3597
  }
1248
- return jws;
3598
+ this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => {
3599
+ this.#local = createLocalJWKSet(json);
3600
+ if (this.#cache) {
3601
+ this.#cache.uat = Date.now();
3602
+ this.#cache.jwks = json;
3603
+ }
3604
+ this.#jwksTimestamp = Date.now();
3605
+ this.#pendingFetch = undefined;
3606
+ }).catch((err) => {
3607
+ this.#pendingFetch = undefined;
3608
+ throw err;
3609
+ });
3610
+ await this.#pendingFetch;
1249
3611
  }
1250
3612
  }
1251
-
1252
- // node_modules/jose/dist/webapi/jws/compact/sign.js
1253
- class CompactSign {
1254
- #flattened;
1255
- constructor(payload) {
1256
- this.#flattened = new FlattenedSign(payload);
1257
- }
1258
- setProtectedHeader(protectedHeader) {
1259
- this.#flattened.setProtectedHeader(protectedHeader);
1260
- return this;
1261
- }
1262
- async sign(key, options) {
1263
- const jws = await this.#flattened.sign(key, options);
1264
- if (jws.payload === undefined) {
1265
- throw new TypeError("use the flattened module for creating JWS with b64: false");
3613
+ function createRemoteJWKSet(url, options) {
3614
+ const set = new RemoteJWKSet(url, options);
3615
+ const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
3616
+ Object.defineProperties(remoteJWKSet, {
3617
+ coolingDown: {
3618
+ get: () => set.coolingDown(),
3619
+ enumerable: true,
3620
+ configurable: false
3621
+ },
3622
+ fresh: {
3623
+ get: () => set.fresh(),
3624
+ enumerable: true,
3625
+ configurable: false
3626
+ },
3627
+ reload: {
3628
+ value: () => set.reload(),
3629
+ enumerable: true,
3630
+ configurable: false,
3631
+ writable: false
3632
+ },
3633
+ reloading: {
3634
+ get: () => set.pendingFetch(),
3635
+ enumerable: true,
3636
+ configurable: false
3637
+ },
3638
+ jwks: {
3639
+ value: () => set.jwks(),
3640
+ enumerable: true,
3641
+ configurable: false,
3642
+ writable: false
1266
3643
  }
1267
- return `${jws.protected}.${jws.payload}.${jws.signature}`;
1268
- }
3644
+ });
3645
+ return remoteJWKSet;
1269
3646
  }
3647
+ var USER_AGENT, customFetch, jwksCache;
3648
+ var init_remote = __esm(() => {
3649
+ init_errors();
3650
+ init_local();
3651
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
3652
+ const NAME = "jose";
3653
+ const VERSION = "v6.2.2";
3654
+ USER_AGENT = `${NAME}/${VERSION}`;
3655
+ }
3656
+ customFetch = Symbol();
3657
+ jwksCache = Symbol();
3658
+ });
1270
3659
 
1271
- // node_modules/jose/dist/webapi/jwt/sign.js
1272
- class SignJWT {
1273
- #protectedHeader;
3660
+ // node_modules/jose/dist/webapi/jwt/unsecured.js
3661
+ class UnsecuredJWT {
1274
3662
  #jwt;
1275
3663
  constructor(payload = {}) {
1276
3664
  this.#jwt = new JWTClaimsBuilder(payload);
1277
3665
  }
3666
+ encode() {
3667
+ const header = encode2(JSON.stringify({ alg: "none" }));
3668
+ const payload = encode2(this.#jwt.data());
3669
+ return `${header}.${payload}.`;
3670
+ }
1278
3671
  setIssuer(issuer) {
1279
3672
  this.#jwt.iss = issuer;
1280
3673
  return this;
@@ -1303,20 +3696,322 @@ class SignJWT {
1303
3696
  this.#jwt.iat = input;
1304
3697
  return this;
1305
3698
  }
1306
- setProtectedHeader(protectedHeader) {
1307
- this.#protectedHeader = protectedHeader;
1308
- return this;
3699
+ static decode(jwt, options) {
3700
+ if (typeof jwt !== "string") {
3701
+ throw new JWTInvalid("Unsecured JWT must be a string");
3702
+ }
3703
+ const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split(".");
3704
+ if (length !== 3 || signature !== "") {
3705
+ throw new JWTInvalid("Invalid Unsecured JWT");
3706
+ }
3707
+ let header;
3708
+ try {
3709
+ header = JSON.parse(decoder.decode(decode(encodedHeader)));
3710
+ if (header.alg !== "none")
3711
+ throw new Error;
3712
+ } catch {
3713
+ throw new JWTInvalid("Invalid Unsecured JWT");
3714
+ }
3715
+ const payload = validateClaimsSet(header, decode(encodedPayload), options);
3716
+ return { payload, header };
1309
3717
  }
1310
- async sign(key, options) {
1311
- const sig = new CompactSign(this.#jwt.data());
1312
- sig.setProtectedHeader(this.#protectedHeader);
1313
- if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) {
1314
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3718
+ }
3719
+ var init_unsecured = __esm(() => {
3720
+ init_base64url();
3721
+ init_buffer_utils();
3722
+ init_errors();
3723
+ init_jwt_claims_set();
3724
+ });
3725
+
3726
+ // node_modules/jose/dist/webapi/util/decode_protected_header.js
3727
+ function decodeProtectedHeader(token) {
3728
+ let protectedB64u;
3729
+ if (typeof token === "string") {
3730
+ const parts = token.split(".");
3731
+ if (parts.length === 3 || parts.length === 5) {
3732
+ [protectedB64u] = parts;
1315
3733
  }
1316
- return sig.sign(key, options);
3734
+ } else if (typeof token === "object" && token) {
3735
+ if ("protected" in token) {
3736
+ protectedB64u = token.protected;
3737
+ } else {
3738
+ throw new TypeError("Token does not contain a Protected Header");
3739
+ }
3740
+ }
3741
+ try {
3742
+ if (typeof protectedB64u !== "string" || !protectedB64u) {
3743
+ throw new Error;
3744
+ }
3745
+ const result = JSON.parse(decoder.decode(decode(protectedB64u)));
3746
+ if (!isObject(result)) {
3747
+ throw new Error;
3748
+ }
3749
+ return result;
3750
+ } catch {
3751
+ throw new TypeError("Invalid Token or Protected Header formatting");
3752
+ }
3753
+ }
3754
+ var init_decode_protected_header = __esm(() => {
3755
+ init_base64url();
3756
+ init_buffer_utils();
3757
+ });
3758
+
3759
+ // node_modules/jose/dist/webapi/util/decode_jwt.js
3760
+ function decodeJwt(jwt) {
3761
+ if (typeof jwt !== "string")
3762
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
3763
+ const { 1: payload, length } = jwt.split(".");
3764
+ if (length === 5)
3765
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
3766
+ if (length !== 3)
3767
+ throw new JWTInvalid("Invalid JWT");
3768
+ if (!payload)
3769
+ throw new JWTInvalid("JWTs must contain a payload");
3770
+ let decoded;
3771
+ try {
3772
+ decoded = decode(payload);
3773
+ } catch {
3774
+ throw new JWTInvalid("Failed to base64url decode the payload");
3775
+ }
3776
+ let result;
3777
+ try {
3778
+ result = JSON.parse(decoder.decode(decoded));
3779
+ } catch {
3780
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
3781
+ }
3782
+ if (!isObject(result))
3783
+ throw new JWTInvalid("Invalid JWT Claims Set");
3784
+ return result;
3785
+ }
3786
+ var init_decode_jwt = __esm(() => {
3787
+ init_base64url();
3788
+ init_buffer_utils();
3789
+ init_errors();
3790
+ });
3791
+
3792
+ // node_modules/jose/dist/webapi/key/generate_key_pair.js
3793
+ function getModulusLengthOption(options) {
3794
+ const modulusLength = options?.modulusLength ?? 2048;
3795
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
3796
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
3797
+ }
3798
+ return modulusLength;
3799
+ }
3800
+ async function generateKeyPair(alg, options) {
3801
+ let algorithm;
3802
+ let keyUsages;
3803
+ switch (alg) {
3804
+ case "PS256":
3805
+ case "PS384":
3806
+ case "PS512":
3807
+ algorithm = {
3808
+ name: "RSA-PSS",
3809
+ hash: `SHA-${alg.slice(-3)}`,
3810
+ publicExponent: Uint8Array.of(1, 0, 1),
3811
+ modulusLength: getModulusLengthOption(options)
3812
+ };
3813
+ keyUsages = ["sign", "verify"];
3814
+ break;
3815
+ case "RS256":
3816
+ case "RS384":
3817
+ case "RS512":
3818
+ algorithm = {
3819
+ name: "RSASSA-PKCS1-v1_5",
3820
+ hash: `SHA-${alg.slice(-3)}`,
3821
+ publicExponent: Uint8Array.of(1, 0, 1),
3822
+ modulusLength: getModulusLengthOption(options)
3823
+ };
3824
+ keyUsages = ["sign", "verify"];
3825
+ break;
3826
+ case "RSA-OAEP":
3827
+ case "RSA-OAEP-256":
3828
+ case "RSA-OAEP-384":
3829
+ case "RSA-OAEP-512":
3830
+ algorithm = {
3831
+ name: "RSA-OAEP",
3832
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
3833
+ publicExponent: Uint8Array.of(1, 0, 1),
3834
+ modulusLength: getModulusLengthOption(options)
3835
+ };
3836
+ keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"];
3837
+ break;
3838
+ case "ES256":
3839
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
3840
+ keyUsages = ["sign", "verify"];
3841
+ break;
3842
+ case "ES384":
3843
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
3844
+ keyUsages = ["sign", "verify"];
3845
+ break;
3846
+ case "ES512":
3847
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
3848
+ keyUsages = ["sign", "verify"];
3849
+ break;
3850
+ case "Ed25519":
3851
+ case "EdDSA": {
3852
+ keyUsages = ["sign", "verify"];
3853
+ algorithm = { name: "Ed25519" };
3854
+ break;
3855
+ }
3856
+ case "ML-DSA-44":
3857
+ case "ML-DSA-65":
3858
+ case "ML-DSA-87": {
3859
+ keyUsages = ["sign", "verify"];
3860
+ algorithm = { name: alg };
3861
+ break;
3862
+ }
3863
+ case "ECDH-ES":
3864
+ case "ECDH-ES+A128KW":
3865
+ case "ECDH-ES+A192KW":
3866
+ case "ECDH-ES+A256KW": {
3867
+ keyUsages = ["deriveBits"];
3868
+ const crv = options?.crv ?? "P-256";
3869
+ switch (crv) {
3870
+ case "P-256":
3871
+ case "P-384":
3872
+ case "P-521": {
3873
+ algorithm = { name: "ECDH", namedCurve: crv };
3874
+ break;
3875
+ }
3876
+ case "X25519":
3877
+ algorithm = { name: "X25519" };
3878
+ break;
3879
+ default:
3880
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
3881
+ }
3882
+ break;
3883
+ }
3884
+ default:
3885
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
3886
+ }
3887
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
3888
+ }
3889
+ var init_generate_key_pair = __esm(() => {
3890
+ init_errors();
3891
+ });
3892
+
3893
+ // node_modules/jose/dist/webapi/key/generate_secret.js
3894
+ async function generateSecret(alg, options) {
3895
+ let length;
3896
+ let algorithm;
3897
+ let keyUsages;
3898
+ switch (alg) {
3899
+ case "HS256":
3900
+ case "HS384":
3901
+ case "HS512":
3902
+ length = parseInt(alg.slice(-3), 10);
3903
+ algorithm = { name: "HMAC", hash: `SHA-${length}`, length };
3904
+ keyUsages = ["sign", "verify"];
3905
+ break;
3906
+ case "A128CBC-HS256":
3907
+ case "A192CBC-HS384":
3908
+ case "A256CBC-HS512":
3909
+ length = parseInt(alg.slice(-3), 10);
3910
+ return crypto.getRandomValues(new Uint8Array(length >> 3));
3911
+ case "A128KW":
3912
+ case "A192KW":
3913
+ case "A256KW":
3914
+ length = parseInt(alg.slice(1, 4), 10);
3915
+ algorithm = { name: "AES-KW", length };
3916
+ keyUsages = ["wrapKey", "unwrapKey"];
3917
+ break;
3918
+ case "A128GCMKW":
3919
+ case "A192GCMKW":
3920
+ case "A256GCMKW":
3921
+ case "A128GCM":
3922
+ case "A192GCM":
3923
+ case "A256GCM":
3924
+ length = parseInt(alg.slice(1, 4), 10);
3925
+ algorithm = { name: "AES-GCM", length };
3926
+ keyUsages = ["encrypt", "decrypt"];
3927
+ break;
3928
+ default:
3929
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1317
3930
  }
3931
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
1318
3932
  }
3933
+ var init_generate_secret = __esm(() => {
3934
+ init_errors();
3935
+ });
3936
+
3937
+ // node_modules/jose/dist/webapi/index.js
3938
+ var exports_webapi = {};
3939
+ __export(exports_webapi, {
3940
+ jwtVerify: () => jwtVerify,
3941
+ jwtDecrypt: () => jwtDecrypt,
3942
+ jwksCache: () => jwksCache,
3943
+ importX509: () => importX509,
3944
+ importSPKI: () => importSPKI,
3945
+ importPKCS8: () => importPKCS8,
3946
+ importJWK: () => importJWK,
3947
+ generateSecret: () => generateSecret,
3948
+ generateKeyPair: () => generateKeyPair,
3949
+ generalVerify: () => generalVerify,
3950
+ generalDecrypt: () => generalDecrypt,
3951
+ flattenedVerify: () => flattenedVerify,
3952
+ flattenedDecrypt: () => flattenedDecrypt,
3953
+ exportSPKI: () => exportSPKI,
3954
+ exportPKCS8: () => exportPKCS8,
3955
+ exportJWK: () => exportJWK,
3956
+ errors: () => exports_errors,
3957
+ decodeProtectedHeader: () => decodeProtectedHeader,
3958
+ decodeJwt: () => decodeJwt,
3959
+ customFetch: () => customFetch,
3960
+ cryptoRuntime: () => cryptoRuntime,
3961
+ createRemoteJWKSet: () => createRemoteJWKSet,
3962
+ createLocalJWKSet: () => createLocalJWKSet,
3963
+ compactVerify: () => compactVerify,
3964
+ compactDecrypt: () => compactDecrypt,
3965
+ calculateJwkThumbprintUri: () => calculateJwkThumbprintUri,
3966
+ calculateJwkThumbprint: () => calculateJwkThumbprint,
3967
+ base64url: () => exports_base64url,
3968
+ UnsecuredJWT: () => UnsecuredJWT,
3969
+ SignJWT: () => SignJWT,
3970
+ GeneralSign: () => GeneralSign,
3971
+ GeneralEncrypt: () => GeneralEncrypt,
3972
+ FlattenedSign: () => FlattenedSign,
3973
+ FlattenedEncrypt: () => FlattenedEncrypt,
3974
+ EncryptJWT: () => EncryptJWT,
3975
+ EmbeddedJWK: () => EmbeddedJWK,
3976
+ CompactSign: () => CompactSign,
3977
+ CompactEncrypt: () => CompactEncrypt
3978
+ });
3979
+ var cryptoRuntime = "WebCryptoAPI";
3980
+ var init_webapi = __esm(() => {
3981
+ init_decrypt2();
3982
+ init_decrypt();
3983
+ init_decrypt3();
3984
+ init_encrypt2();
3985
+ init_verify2();
3986
+ init_verify();
3987
+ init_verify3();
3988
+ init_verify4();
3989
+ init_decrypt4();
3990
+ init_encrypt3();
3991
+ init_encrypt();
3992
+ init_sign2();
3993
+ init_sign();
3994
+ init_sign3();
3995
+ init_sign4();
3996
+ init_encrypt4();
3997
+ init_thumbprint();
3998
+ init_embedded();
3999
+ init_local();
4000
+ init_remote();
4001
+ init_unsecured();
4002
+ init_export();
4003
+ init_import();
4004
+ init_decode_protected_header();
4005
+ init_decode_jwt();
4006
+ init_errors();
4007
+ init_generate_key_pair();
4008
+ init_generate_secret();
4009
+ init_base64url();
4010
+ });
4011
+
1319
4012
  // src/middleware.ts
4013
+ init_webapi();
4014
+ init_webapi();
1320
4015
  var logger = (options = {}) => {
1321
4016
  const {
1322
4017
  enabled = true,
@@ -1531,7 +4226,7 @@ var apiKey = (options) => {
1531
4226
  return next();
1532
4227
  };
1533
4228
  };
1534
- var compress = (options) => {
4229
+ var compress2 = (options) => {
1535
4230
  const threshold = options?.threshold || 1024;
1536
4231
  const filter = options?.filter || (() => true);
1537
4232
  return async (req, next) => {
@@ -1609,15 +4304,122 @@ var session = (options) => {
1609
4304
  });
1610
4305
  };
1611
4306
  };
4307
+ var secureHeaders = (options) => {
4308
+ const opts = options ?? {};
4309
+ return async (req, next) => {
4310
+ const response = await next();
4311
+ if (!response)
4312
+ return response;
4313
+ const headers = new Headers(response.headers);
4314
+ headers.set("X-Frame-Options", opts.xFrameOptions ?? "SAMEORIGIN");
4315
+ headers.set("X-XSS-Protection", opts.xXssProtection ?? "1; mode=block");
4316
+ headers.set("Referrer-Policy", opts.referrerPolicy ?? "strict-origin-when-cross-origin");
4317
+ if (opts.xContentTypeOptions !== false)
4318
+ headers.set("X-Content-Type-Options", "nosniff");
4319
+ if (opts.strictTransportSecurity !== "")
4320
+ headers.set("Strict-Transport-Security", opts.strictTransportSecurity ?? "max-age=31536000; includeSubDomains");
4321
+ if (opts.permissionsPolicy)
4322
+ headers.set("Permissions-Policy", opts.permissionsPolicy);
4323
+ if (opts.contentSecurityPolicy)
4324
+ headers.set("Content-Security-Policy", opts.contentSecurityPolicy);
4325
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
4326
+ };
4327
+ };
4328
+ var timeout = (ms, message2 = "Request Timeout") => {
4329
+ return async (req, next) => {
4330
+ let timer;
4331
+ const timeoutPromise = new Promise((resolve) => {
4332
+ timer = setTimeout(() => resolve(new Response(JSON.stringify({ error: message2 }), {
4333
+ status: 408,
4334
+ headers: { "Content-Type": "application/json" }
4335
+ })), ms);
4336
+ });
4337
+ try {
4338
+ const result = await Promise.race([next(), timeoutPromise]);
4339
+ return result;
4340
+ } finally {
4341
+ clearTimeout(timer);
4342
+ }
4343
+ };
4344
+ };
4345
+ var requestId = (options) => {
4346
+ const header = options?.header ?? "X-Request-ID";
4347
+ const generate = options?.generator ?? (() => crypto.randomUUID());
4348
+ return async (req, next) => {
4349
+ const id = req.headers.get(header) ?? generate();
4350
+ req.id = id;
4351
+ const response = await next();
4352
+ if (!response)
4353
+ return response;
4354
+ const headers = new Headers(response.headers);
4355
+ headers.set(header, id);
4356
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
4357
+ };
4358
+ };
4359
+ var ipRestriction = (options) => {
4360
+ const allow = options.allowList ? new Set(options.allowList) : null;
4361
+ const deny = options.denyList ? new Set(options.denyList) : null;
4362
+ return async (req, next) => {
4363
+ const ip = req.ip ?? "127.0.0.1";
4364
+ if (deny && deny.has(ip))
4365
+ return new Response(JSON.stringify({ error: "Forbidden" }), { status: 403, headers: { "Content-Type": "application/json" } });
4366
+ if (allow && !allow.has(ip))
4367
+ return new Response(JSON.stringify({ error: "Forbidden" }), { status: 403, headers: { "Content-Type": "application/json" } });
4368
+ return next();
4369
+ };
4370
+ };
4371
+ var serveStatic = (root) => {
4372
+ const base = root.replace(/\/$/, "");
4373
+ return async (req, next) => {
4374
+ if (req.method !== "GET" && req.method !== "HEAD")
4375
+ return next();
4376
+ const pathname = new URL(req.url).pathname;
4377
+ const filePath = base + pathname;
4378
+ const file = Bun.file(filePath);
4379
+ if (await file.exists()) {
4380
+ return new Response(file);
4381
+ }
4382
+ if (!pathname.includes(".")) {
4383
+ const index = Bun.file(filePath.replace(/\/$/, "") + "/index.html");
4384
+ if (await index.exists())
4385
+ return new Response(index);
4386
+ }
4387
+ return next();
4388
+ };
4389
+ };
4390
+ var jwks = (jwksUrl, options) => {
4391
+ const JWKS = createRemoteJWKSet(new URL(jwksUrl));
4392
+ return async (req, next) => {
4393
+ const auth2 = req.headers.get("authorization");
4394
+ req.user = undefined;
4395
+ if (auth2?.startsWith("Bearer ")) {
4396
+ const token = auth2.slice(7).trim();
4397
+ try {
4398
+ const { jwtVerify: jwtVerify2 } = await Promise.resolve().then(() => (init_webapi(), exports_webapi));
4399
+ const { payload } = await jwtVerify2(token, JWKS, {
4400
+ algorithms: options?.algorithms ?? ["RS256", "RS512", "ES256", "ES512"]
4401
+ });
4402
+ req.user = payload;
4403
+ } catch {}
4404
+ }
4405
+ return next();
4406
+ };
4407
+ };
1612
4408
  export {
1613
4409
  validate,
4410
+ timeout,
1614
4411
  signJWT,
1615
4412
  session,
4413
+ serveStatic,
4414
+ secureHeaders,
4415
+ requestId,
1616
4416
  rateLimit,
1617
4417
  logger,
1618
4418
  jwt,
4419
+ jwks,
4420
+ ipRestriction,
1619
4421
  cors,
1620
- compress,
4422
+ compress2 as compress,
1621
4423
  auth,
1622
4424
  apiKey
1623
4425
  };