@multi-agent-protocol/sdk 0.1.10 → 0.1.11

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.
package/dist/server.js CHANGED
@@ -1,6 +1,4349 @@
1
1
  import { monotonicFactory, ulid } from 'ulid';
2
2
  import { z } from 'zod';
3
3
 
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __esm = (fn, res) => function __init() {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ };
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+
14
+ // ../../../node_modules/jose/dist/webapi/lib/buffer_utils.js
15
+ function concat(...buffers) {
16
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
17
+ const buf = new Uint8Array(size);
18
+ let i = 0;
19
+ for (const buffer of buffers) {
20
+ buf.set(buffer, i);
21
+ i += buffer.length;
22
+ }
23
+ return buf;
24
+ }
25
+ function writeUInt32BE(buf, value, offset) {
26
+ if (value < 0 || value >= MAX_INT32) {
27
+ throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
28
+ }
29
+ buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);
30
+ }
31
+ function uint64be(value) {
32
+ const high = Math.floor(value / MAX_INT32);
33
+ const low = value % MAX_INT32;
34
+ const buf = new Uint8Array(8);
35
+ writeUInt32BE(buf, high, 0);
36
+ writeUInt32BE(buf, low, 4);
37
+ return buf;
38
+ }
39
+ function uint32be(value) {
40
+ const buf = new Uint8Array(4);
41
+ writeUInt32BE(buf, value);
42
+ return buf;
43
+ }
44
+ function encode(string) {
45
+ const bytes = new Uint8Array(string.length);
46
+ for (let i = 0; i < string.length; i++) {
47
+ const code = string.charCodeAt(i);
48
+ if (code > 127) {
49
+ throw new TypeError("non-ASCII string encountered in encode()");
50
+ }
51
+ bytes[i] = code;
52
+ }
53
+ return bytes;
54
+ }
55
+ var encoder, decoder, MAX_INT32;
56
+ var init_buffer_utils = __esm({
57
+ "../../../node_modules/jose/dist/webapi/lib/buffer_utils.js"() {
58
+ encoder = new TextEncoder();
59
+ decoder = new TextDecoder();
60
+ MAX_INT32 = 2 ** 32;
61
+ }
62
+ });
63
+
64
+ // ../../../node_modules/jose/dist/webapi/lib/base64.js
65
+ function encodeBase64(input) {
66
+ if (Uint8Array.prototype.toBase64) {
67
+ return input.toBase64();
68
+ }
69
+ const CHUNK_SIZE = 32768;
70
+ const arr = [];
71
+ for (let i = 0; i < input.length; i += CHUNK_SIZE) {
72
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
73
+ }
74
+ return btoa(arr.join(""));
75
+ }
76
+ function decodeBase64(encoded) {
77
+ if (Uint8Array.fromBase64) {
78
+ return Uint8Array.fromBase64(encoded);
79
+ }
80
+ const binary = atob(encoded);
81
+ const bytes = new Uint8Array(binary.length);
82
+ for (let i = 0; i < binary.length; i++) {
83
+ bytes[i] = binary.charCodeAt(i);
84
+ }
85
+ return bytes;
86
+ }
87
+ var init_base64 = __esm({
88
+ "../../../node_modules/jose/dist/webapi/lib/base64.js"() {
89
+ }
90
+ });
91
+
92
+ // ../../../node_modules/jose/dist/webapi/util/base64url.js
93
+ var base64url_exports = {};
94
+ __export(base64url_exports, {
95
+ decode: () => decode,
96
+ encode: () => encode2
97
+ });
98
+ function decode(input) {
99
+ if (Uint8Array.fromBase64) {
100
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
101
+ alphabet: "base64url"
102
+ });
103
+ }
104
+ let encoded = input;
105
+ if (encoded instanceof Uint8Array) {
106
+ encoded = decoder.decode(encoded);
107
+ }
108
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
109
+ try {
110
+ return decodeBase64(encoded);
111
+ } catch {
112
+ throw new TypeError("The input to be decoded is not correctly encoded.");
113
+ }
114
+ }
115
+ function encode2(input) {
116
+ let unencoded = input;
117
+ if (typeof unencoded === "string") {
118
+ unencoded = encoder.encode(unencoded);
119
+ }
120
+ if (Uint8Array.prototype.toBase64) {
121
+ return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
122
+ }
123
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
124
+ }
125
+ var init_base64url = __esm({
126
+ "../../../node_modules/jose/dist/webapi/util/base64url.js"() {
127
+ init_buffer_utils();
128
+ init_base64();
129
+ }
130
+ });
131
+
132
+ // ../../../node_modules/jose/dist/webapi/util/errors.js
133
+ var errors_exports = {};
134
+ __export(errors_exports, {
135
+ JOSEAlgNotAllowed: () => JOSEAlgNotAllowed,
136
+ JOSEError: () => JOSEError,
137
+ JOSENotSupported: () => JOSENotSupported,
138
+ JWEDecryptionFailed: () => JWEDecryptionFailed,
139
+ JWEInvalid: () => JWEInvalid,
140
+ JWKInvalid: () => JWKInvalid,
141
+ JWKSInvalid: () => JWKSInvalid,
142
+ JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
143
+ JWKSNoMatchingKey: () => JWKSNoMatchingKey,
144
+ JWKSTimeout: () => JWKSTimeout,
145
+ JWSInvalid: () => JWSInvalid,
146
+ JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
147
+ JWTClaimValidationFailed: () => JWTClaimValidationFailed,
148
+ JWTExpired: () => JWTExpired,
149
+ JWTInvalid: () => JWTInvalid
150
+ });
151
+ var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed;
152
+ var init_errors = __esm({
153
+ "../../../node_modules/jose/dist/webapi/util/errors.js"() {
154
+ JOSEError = class extends Error {
155
+ static code = "ERR_JOSE_GENERIC";
156
+ code = "ERR_JOSE_GENERIC";
157
+ constructor(message2, options) {
158
+ super(message2, options);
159
+ this.name = this.constructor.name;
160
+ Error.captureStackTrace?.(this, this.constructor);
161
+ }
162
+ };
163
+ JWTClaimValidationFailed = class extends JOSEError {
164
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
165
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
166
+ claim;
167
+ reason;
168
+ payload;
169
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
170
+ super(message2, { cause: { claim, reason, payload } });
171
+ this.claim = claim;
172
+ this.reason = reason;
173
+ this.payload = payload;
174
+ }
175
+ };
176
+ JWTExpired = class extends JOSEError {
177
+ static code = "ERR_JWT_EXPIRED";
178
+ code = "ERR_JWT_EXPIRED";
179
+ claim;
180
+ reason;
181
+ payload;
182
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
183
+ super(message2, { cause: { claim, reason, payload } });
184
+ this.claim = claim;
185
+ this.reason = reason;
186
+ this.payload = payload;
187
+ }
188
+ };
189
+ JOSEAlgNotAllowed = class extends JOSEError {
190
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
191
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
192
+ };
193
+ JOSENotSupported = class extends JOSEError {
194
+ static code = "ERR_JOSE_NOT_SUPPORTED";
195
+ code = "ERR_JOSE_NOT_SUPPORTED";
196
+ };
197
+ JWEDecryptionFailed = class extends JOSEError {
198
+ static code = "ERR_JWE_DECRYPTION_FAILED";
199
+ code = "ERR_JWE_DECRYPTION_FAILED";
200
+ constructor(message2 = "decryption operation failed", options) {
201
+ super(message2, options);
202
+ }
203
+ };
204
+ JWEInvalid = class extends JOSEError {
205
+ static code = "ERR_JWE_INVALID";
206
+ code = "ERR_JWE_INVALID";
207
+ };
208
+ JWSInvalid = class extends JOSEError {
209
+ static code = "ERR_JWS_INVALID";
210
+ code = "ERR_JWS_INVALID";
211
+ };
212
+ JWTInvalid = class extends JOSEError {
213
+ static code = "ERR_JWT_INVALID";
214
+ code = "ERR_JWT_INVALID";
215
+ };
216
+ JWKInvalid = class extends JOSEError {
217
+ static code = "ERR_JWK_INVALID";
218
+ code = "ERR_JWK_INVALID";
219
+ };
220
+ JWKSInvalid = class extends JOSEError {
221
+ static code = "ERR_JWKS_INVALID";
222
+ code = "ERR_JWKS_INVALID";
223
+ };
224
+ JWKSNoMatchingKey = class extends JOSEError {
225
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
226
+ code = "ERR_JWKS_NO_MATCHING_KEY";
227
+ constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
228
+ super(message2, options);
229
+ }
230
+ };
231
+ JWKSMultipleMatchingKeys = class extends JOSEError {
232
+ [Symbol.asyncIterator];
233
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
234
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
235
+ constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
236
+ super(message2, options);
237
+ }
238
+ };
239
+ JWKSTimeout = class extends JOSEError {
240
+ static code = "ERR_JWKS_TIMEOUT";
241
+ code = "ERR_JWKS_TIMEOUT";
242
+ constructor(message2 = "request timed out", options) {
243
+ super(message2, options);
244
+ }
245
+ };
246
+ JWSSignatureVerificationFailed = class extends JOSEError {
247
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
248
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
249
+ constructor(message2 = "signature verification failed", options) {
250
+ super(message2, options);
251
+ }
252
+ };
253
+ }
254
+ });
255
+
256
+ // ../../../node_modules/jose/dist/webapi/lib/iv.js
257
+ function bitLength(alg) {
258
+ switch (alg) {
259
+ case "A128GCM":
260
+ case "A128GCMKW":
261
+ case "A192GCM":
262
+ case "A192GCMKW":
263
+ case "A256GCM":
264
+ case "A256GCMKW":
265
+ return 96;
266
+ case "A128CBC-HS256":
267
+ case "A192CBC-HS384":
268
+ case "A256CBC-HS512":
269
+ return 128;
270
+ default:
271
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
272
+ }
273
+ }
274
+ var generateIv;
275
+ var init_iv = __esm({
276
+ "../../../node_modules/jose/dist/webapi/lib/iv.js"() {
277
+ init_errors();
278
+ generateIv = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
279
+ }
280
+ });
281
+
282
+ // ../../../node_modules/jose/dist/webapi/lib/check_iv_length.js
283
+ function checkIvLength(enc, iv) {
284
+ if (iv.length << 3 !== bitLength(enc)) {
285
+ throw new JWEInvalid("Invalid Initialization Vector length");
286
+ }
287
+ }
288
+ var init_check_iv_length = __esm({
289
+ "../../../node_modules/jose/dist/webapi/lib/check_iv_length.js"() {
290
+ init_errors();
291
+ init_iv();
292
+ }
293
+ });
294
+
295
+ // ../../../node_modules/jose/dist/webapi/lib/check_cek_length.js
296
+ function checkCekLength(cek, expected) {
297
+ const actual = cek.byteLength << 3;
298
+ if (actual !== expected) {
299
+ throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
300
+ }
301
+ }
302
+ var init_check_cek_length = __esm({
303
+ "../../../node_modules/jose/dist/webapi/lib/check_cek_length.js"() {
304
+ init_errors();
305
+ }
306
+ });
307
+
308
+ // ../../../node_modules/jose/dist/webapi/lib/crypto_key.js
309
+ function getHashLength(hash) {
310
+ return parseInt(hash.name.slice(4), 10);
311
+ }
312
+ function getNamedCurve(alg) {
313
+ switch (alg) {
314
+ case "ES256":
315
+ return "P-256";
316
+ case "ES384":
317
+ return "P-384";
318
+ case "ES512":
319
+ return "P-521";
320
+ default:
321
+ throw new Error("unreachable");
322
+ }
323
+ }
324
+ function checkUsage(key, usage) {
325
+ if (usage && !key.usages.includes(usage)) {
326
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
327
+ }
328
+ }
329
+ function checkSigCryptoKey(key, alg, usage) {
330
+ switch (alg) {
331
+ case "HS256":
332
+ case "HS384":
333
+ case "HS512": {
334
+ if (!isAlgorithm(key.algorithm, "HMAC"))
335
+ throw unusable("HMAC");
336
+ const expected = parseInt(alg.slice(2), 10);
337
+ const actual = getHashLength(key.algorithm.hash);
338
+ if (actual !== expected)
339
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
340
+ break;
341
+ }
342
+ case "RS256":
343
+ case "RS384":
344
+ case "RS512": {
345
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
346
+ throw unusable("RSASSA-PKCS1-v1_5");
347
+ const expected = parseInt(alg.slice(2), 10);
348
+ const actual = getHashLength(key.algorithm.hash);
349
+ if (actual !== expected)
350
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
351
+ break;
352
+ }
353
+ case "PS256":
354
+ case "PS384":
355
+ case "PS512": {
356
+ if (!isAlgorithm(key.algorithm, "RSA-PSS"))
357
+ throw unusable("RSA-PSS");
358
+ const expected = parseInt(alg.slice(2), 10);
359
+ const actual = getHashLength(key.algorithm.hash);
360
+ if (actual !== expected)
361
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
362
+ break;
363
+ }
364
+ case "Ed25519":
365
+ case "EdDSA": {
366
+ if (!isAlgorithm(key.algorithm, "Ed25519"))
367
+ throw unusable("Ed25519");
368
+ break;
369
+ }
370
+ case "ML-DSA-44":
371
+ case "ML-DSA-65":
372
+ case "ML-DSA-87": {
373
+ if (!isAlgorithm(key.algorithm, alg))
374
+ throw unusable(alg);
375
+ break;
376
+ }
377
+ case "ES256":
378
+ case "ES384":
379
+ case "ES512": {
380
+ if (!isAlgorithm(key.algorithm, "ECDSA"))
381
+ throw unusable("ECDSA");
382
+ const expected = getNamedCurve(alg);
383
+ const actual = key.algorithm.namedCurve;
384
+ if (actual !== expected)
385
+ throw unusable(expected, "algorithm.namedCurve");
386
+ break;
387
+ }
388
+ default:
389
+ throw new TypeError("CryptoKey does not support this operation");
390
+ }
391
+ checkUsage(key, usage);
392
+ }
393
+ function checkEncCryptoKey(key, alg, usage) {
394
+ switch (alg) {
395
+ case "A128GCM":
396
+ case "A192GCM":
397
+ case "A256GCM": {
398
+ if (!isAlgorithm(key.algorithm, "AES-GCM"))
399
+ throw unusable("AES-GCM");
400
+ const expected = parseInt(alg.slice(1, 4), 10);
401
+ const actual = key.algorithm.length;
402
+ if (actual !== expected)
403
+ throw unusable(expected, "algorithm.length");
404
+ break;
405
+ }
406
+ case "A128KW":
407
+ case "A192KW":
408
+ case "A256KW": {
409
+ if (!isAlgorithm(key.algorithm, "AES-KW"))
410
+ throw unusable("AES-KW");
411
+ const expected = parseInt(alg.slice(1, 4), 10);
412
+ const actual = key.algorithm.length;
413
+ if (actual !== expected)
414
+ throw unusable(expected, "algorithm.length");
415
+ break;
416
+ }
417
+ case "ECDH": {
418
+ switch (key.algorithm.name) {
419
+ case "ECDH":
420
+ case "X25519":
421
+ break;
422
+ default:
423
+ throw unusable("ECDH or X25519");
424
+ }
425
+ break;
426
+ }
427
+ case "PBES2-HS256+A128KW":
428
+ case "PBES2-HS384+A192KW":
429
+ case "PBES2-HS512+A256KW":
430
+ if (!isAlgorithm(key.algorithm, "PBKDF2"))
431
+ throw unusable("PBKDF2");
432
+ break;
433
+ case "RSA-OAEP":
434
+ case "RSA-OAEP-256":
435
+ case "RSA-OAEP-384":
436
+ case "RSA-OAEP-512": {
437
+ if (!isAlgorithm(key.algorithm, "RSA-OAEP"))
438
+ throw unusable("RSA-OAEP");
439
+ const expected = parseInt(alg.slice(9), 10) || 1;
440
+ const actual = getHashLength(key.algorithm.hash);
441
+ if (actual !== expected)
442
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
443
+ break;
444
+ }
445
+ default:
446
+ throw new TypeError("CryptoKey does not support this operation");
447
+ }
448
+ checkUsage(key, usage);
449
+ }
450
+ var unusable, isAlgorithm;
451
+ var init_crypto_key = __esm({
452
+ "../../../node_modules/jose/dist/webapi/lib/crypto_key.js"() {
453
+ unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
454
+ isAlgorithm = (algorithm, name) => algorithm.name === name;
455
+ }
456
+ });
457
+
458
+ // ../../../node_modules/jose/dist/webapi/lib/invalid_key_input.js
459
+ function message(msg, actual, ...types) {
460
+ types = types.filter(Boolean);
461
+ if (types.length > 2) {
462
+ const last = types.pop();
463
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
464
+ } else if (types.length === 2) {
465
+ msg += `one of type ${types[0]} or ${types[1]}.`;
466
+ } else {
467
+ msg += `of type ${types[0]}.`;
468
+ }
469
+ if (actual == null) {
470
+ msg += ` Received ${actual}`;
471
+ } else if (typeof actual === "function" && actual.name) {
472
+ msg += ` Received function ${actual.name}`;
473
+ } else if (typeof actual === "object" && actual != null) {
474
+ if (actual.constructor?.name) {
475
+ msg += ` Received an instance of ${actual.constructor.name}`;
476
+ }
477
+ }
478
+ return msg;
479
+ }
480
+ var invalidKeyInput, withAlg;
481
+ var init_invalid_key_input = __esm({
482
+ "../../../node_modules/jose/dist/webapi/lib/invalid_key_input.js"() {
483
+ invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
484
+ withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
485
+ }
486
+ });
487
+
488
+ // ../../../node_modules/jose/dist/webapi/lib/is_key_like.js
489
+ function assertCryptoKey(key) {
490
+ if (!isCryptoKey(key)) {
491
+ throw new Error("CryptoKey instance expected");
492
+ }
493
+ }
494
+ var isCryptoKey, isKeyObject, isKeyLike;
495
+ var init_is_key_like = __esm({
496
+ "../../../node_modules/jose/dist/webapi/lib/is_key_like.js"() {
497
+ isCryptoKey = (key) => {
498
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
499
+ return true;
500
+ try {
501
+ return key instanceof CryptoKey;
502
+ } catch {
503
+ return false;
504
+ }
505
+ };
506
+ isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
507
+ isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
508
+ }
509
+ });
510
+
511
+ // ../../../node_modules/jose/dist/webapi/lib/decrypt.js
512
+ async function timingSafeEqual(a, b) {
513
+ if (!(a instanceof Uint8Array)) {
514
+ throw new TypeError("First argument must be a buffer");
515
+ }
516
+ if (!(b instanceof Uint8Array)) {
517
+ throw new TypeError("Second argument must be a buffer");
518
+ }
519
+ const algorithm = { name: "HMAC", hash: "SHA-256" };
520
+ const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]);
521
+ const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
522
+ const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
523
+ let out = 0;
524
+ let i = -1;
525
+ while (++i < 32) {
526
+ out |= aHmac[i] ^ bHmac[i];
527
+ }
528
+ return out === 0;
529
+ }
530
+ async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
531
+ if (!(cek instanceof Uint8Array)) {
532
+ throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
533
+ }
534
+ const keySize = parseInt(enc.slice(1, 4), 10);
535
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]);
536
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
537
+ hash: `SHA-${keySize << 1}`,
538
+ name: "HMAC"
539
+ }, false, ["sign"]);
540
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
541
+ const expectedTag = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
542
+ let macCheckPassed;
543
+ try {
544
+ macCheckPassed = await timingSafeEqual(tag2, expectedTag);
545
+ } catch {
546
+ }
547
+ if (!macCheckPassed) {
548
+ throw new JWEDecryptionFailed();
549
+ }
550
+ let plaintext;
551
+ try {
552
+ plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext));
553
+ } catch {
554
+ }
555
+ if (!plaintext) {
556
+ throw new JWEDecryptionFailed();
557
+ }
558
+ return plaintext;
559
+ }
560
+ async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
561
+ let encKey;
562
+ if (cek instanceof Uint8Array) {
563
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
564
+ } else {
565
+ checkEncCryptoKey(cek, enc, "decrypt");
566
+ encKey = cek;
567
+ }
568
+ try {
569
+ return new Uint8Array(await crypto.subtle.decrypt({
570
+ additionalData: aad,
571
+ iv,
572
+ name: "AES-GCM",
573
+ tagLength: 128
574
+ }, encKey, concat(ciphertext, tag2)));
575
+ } catch {
576
+ throw new JWEDecryptionFailed();
577
+ }
578
+ }
579
+ async function decrypt(enc, cek, ciphertext, iv, tag2, aad) {
580
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
581
+ throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
582
+ }
583
+ if (!iv) {
584
+ throw new JWEInvalid("JWE Initialization Vector missing");
585
+ }
586
+ if (!tag2) {
587
+ throw new JWEInvalid("JWE Authentication Tag missing");
588
+ }
589
+ checkIvLength(enc, iv);
590
+ switch (enc) {
591
+ case "A128CBC-HS256":
592
+ case "A192CBC-HS384":
593
+ case "A256CBC-HS512":
594
+ if (cek instanceof Uint8Array)
595
+ checkCekLength(cek, parseInt(enc.slice(-3), 10));
596
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad);
597
+ case "A128GCM":
598
+ case "A192GCM":
599
+ case "A256GCM":
600
+ if (cek instanceof Uint8Array)
601
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
602
+ return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad);
603
+ default:
604
+ throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
605
+ }
606
+ }
607
+ var init_decrypt = __esm({
608
+ "../../../node_modules/jose/dist/webapi/lib/decrypt.js"() {
609
+ init_buffer_utils();
610
+ init_check_iv_length();
611
+ init_check_cek_length();
612
+ init_errors();
613
+ init_crypto_key();
614
+ init_invalid_key_input();
615
+ init_is_key_like();
616
+ }
617
+ });
618
+
619
+ // ../../../node_modules/jose/dist/webapi/lib/is_disjoint.js
620
+ function isDisjoint(...headers) {
621
+ const sources = headers.filter(Boolean);
622
+ if (sources.length === 0 || sources.length === 1) {
623
+ return true;
624
+ }
625
+ let acc;
626
+ for (const header of sources) {
627
+ const parameters = Object.keys(header);
628
+ if (!acc || acc.size === 0) {
629
+ acc = new Set(parameters);
630
+ continue;
631
+ }
632
+ for (const parameter of parameters) {
633
+ if (acc.has(parameter)) {
634
+ return false;
635
+ }
636
+ acc.add(parameter);
637
+ }
638
+ }
639
+ return true;
640
+ }
641
+ var init_is_disjoint = __esm({
642
+ "../../../node_modules/jose/dist/webapi/lib/is_disjoint.js"() {
643
+ }
644
+ });
645
+
646
+ // ../../../node_modules/jose/dist/webapi/lib/is_object.js
647
+ function isObject(input) {
648
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
649
+ return false;
650
+ }
651
+ if (Object.getPrototypeOf(input) === null) {
652
+ return true;
653
+ }
654
+ let proto = input;
655
+ while (Object.getPrototypeOf(proto) !== null) {
656
+ proto = Object.getPrototypeOf(proto);
657
+ }
658
+ return Object.getPrototypeOf(input) === proto;
659
+ }
660
+ var isObjectLike;
661
+ var init_is_object = __esm({
662
+ "../../../node_modules/jose/dist/webapi/lib/is_object.js"() {
663
+ isObjectLike = (value) => typeof value === "object" && value !== null;
664
+ }
665
+ });
666
+
667
+ // ../../../node_modules/jose/dist/webapi/lib/aeskw.js
668
+ function checkKeySize(key, alg) {
669
+ if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
670
+ throw new TypeError(`Invalid key size for alg: ${alg}`);
671
+ }
672
+ }
673
+ function getCryptoKey(key, alg, usage) {
674
+ if (key instanceof Uint8Array) {
675
+ return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]);
676
+ }
677
+ checkEncCryptoKey(key, alg, usage);
678
+ return key;
679
+ }
680
+ async function wrap(alg, key, cek) {
681
+ const cryptoKey = await getCryptoKey(key, alg, "wrapKey");
682
+ checkKeySize(cryptoKey, alg);
683
+ const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
684
+ return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
685
+ }
686
+ async function unwrap(alg, key, encryptedKey) {
687
+ const cryptoKey = await getCryptoKey(key, alg, "unwrapKey");
688
+ checkKeySize(cryptoKey, alg);
689
+ const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
690
+ return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
691
+ }
692
+ var init_aeskw = __esm({
693
+ "../../../node_modules/jose/dist/webapi/lib/aeskw.js"() {
694
+ init_crypto_key();
695
+ }
696
+ });
697
+
698
+ // ../../../node_modules/jose/dist/webapi/lib/digest.js
699
+ async function digest(algorithm, data) {
700
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
701
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
702
+ }
703
+ var init_digest = __esm({
704
+ "../../../node_modules/jose/dist/webapi/lib/digest.js"() {
705
+ }
706
+ });
707
+
708
+ // ../../../node_modules/jose/dist/webapi/lib/ecdhes.js
709
+ function lengthAndInput(input) {
710
+ return concat(uint32be(input.length), input);
711
+ }
712
+ async function concatKdf(Z, L, OtherInfo) {
713
+ const dkLen = L >> 3;
714
+ const hashLen = 32;
715
+ const reps = Math.ceil(dkLen / hashLen);
716
+ const dk = new Uint8Array(reps * hashLen);
717
+ for (let i = 1; i <= reps; i++) {
718
+ const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);
719
+ hashInput.set(uint32be(i), 0);
720
+ hashInput.set(Z, 4);
721
+ hashInput.set(OtherInfo, 4 + Z.length);
722
+ const hashResult = await digest("sha256", hashInput);
723
+ dk.set(hashResult, (i - 1) * hashLen);
724
+ }
725
+ return dk.slice(0, dkLen);
726
+ }
727
+ async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {
728
+ checkEncCryptoKey(publicKey, "ECDH");
729
+ checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
730
+ const algorithmID = lengthAndInput(encode(algorithm));
731
+ const partyUInfo = lengthAndInput(apu);
732
+ const partyVInfo = lengthAndInput(apv);
733
+ const suppPubInfo = uint32be(keyLength);
734
+ const suppPrivInfo = new Uint8Array();
735
+ const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
736
+ const Z = new Uint8Array(await crypto.subtle.deriveBits({
737
+ name: publicKey.algorithm.name,
738
+ public: publicKey
739
+ }, privateKey, getEcdhBitLength(publicKey)));
740
+ return concatKdf(Z, keyLength, otherInfo);
741
+ }
742
+ function getEcdhBitLength(publicKey) {
743
+ if (publicKey.algorithm.name === "X25519") {
744
+ return 256;
745
+ }
746
+ return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
747
+ }
748
+ function allowed(key) {
749
+ switch (key.algorithm.namedCurve) {
750
+ case "P-256":
751
+ case "P-384":
752
+ case "P-521":
753
+ return true;
754
+ default:
755
+ return key.algorithm.name === "X25519";
756
+ }
757
+ }
758
+ var init_ecdhes = __esm({
759
+ "../../../node_modules/jose/dist/webapi/lib/ecdhes.js"() {
760
+ init_buffer_utils();
761
+ init_crypto_key();
762
+ init_digest();
763
+ }
764
+ });
765
+
766
+ // ../../../node_modules/jose/dist/webapi/lib/pbes2kw.js
767
+ function getCryptoKey2(key, alg) {
768
+ if (key instanceof Uint8Array) {
769
+ return crypto.subtle.importKey("raw", key, "PBKDF2", false, [
770
+ "deriveBits"
771
+ ]);
772
+ }
773
+ checkEncCryptoKey(key, alg, "deriveBits");
774
+ return key;
775
+ }
776
+ async function deriveKey2(p2s, alg, p2c, key) {
777
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
778
+ throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
779
+ }
780
+ const salt = concatSalt(alg, p2s);
781
+ const keylen = parseInt(alg.slice(13, 16), 10);
782
+ const subtleAlg = {
783
+ hash: `SHA-${alg.slice(8, 11)}`,
784
+ iterations: p2c,
785
+ name: "PBKDF2",
786
+ salt
787
+ };
788
+ const cryptoKey = await getCryptoKey2(key, alg);
789
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
790
+ }
791
+ async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
792
+ const derived = await deriveKey2(p2s, alg, p2c, key);
793
+ const encryptedKey = await wrap(alg.slice(-6), derived, cek);
794
+ return { encryptedKey, p2c, p2s: encode2(p2s) };
795
+ }
796
+ async function unwrap2(alg, key, encryptedKey, p2c, p2s) {
797
+ const derived = await deriveKey2(p2s, alg, p2c, key);
798
+ return unwrap(alg.slice(-6), derived, encryptedKey);
799
+ }
800
+ var concatSalt;
801
+ var init_pbes2kw = __esm({
802
+ "../../../node_modules/jose/dist/webapi/lib/pbes2kw.js"() {
803
+ init_base64url();
804
+ init_aeskw();
805
+ init_crypto_key();
806
+ init_buffer_utils();
807
+ init_errors();
808
+ concatSalt = (alg, p2sInput) => concat(encode(alg), Uint8Array.of(0), p2sInput);
809
+ }
810
+ });
811
+
812
+ // ../../../node_modules/jose/dist/webapi/lib/check_key_length.js
813
+ function checkKeyLength(alg, key) {
814
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
815
+ const { modulusLength } = key.algorithm;
816
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
817
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
818
+ }
819
+ }
820
+ }
821
+ var init_check_key_length = __esm({
822
+ "../../../node_modules/jose/dist/webapi/lib/check_key_length.js"() {
823
+ }
824
+ });
825
+
826
+ // ../../../node_modules/jose/dist/webapi/lib/rsaes.js
827
+ async function encrypt(alg, key, cek) {
828
+ checkEncCryptoKey(key, alg, "encrypt");
829
+ checkKeyLength(alg, key);
830
+ return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
831
+ }
832
+ async function decrypt2(alg, key, encryptedKey) {
833
+ checkEncCryptoKey(key, alg, "decrypt");
834
+ checkKeyLength(alg, key);
835
+ return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
836
+ }
837
+ var subtleAlgorithm;
838
+ var init_rsaes = __esm({
839
+ "../../../node_modules/jose/dist/webapi/lib/rsaes.js"() {
840
+ init_crypto_key();
841
+ init_check_key_length();
842
+ init_errors();
843
+ subtleAlgorithm = (alg) => {
844
+ switch (alg) {
845
+ case "RSA-OAEP":
846
+ case "RSA-OAEP-256":
847
+ case "RSA-OAEP-384":
848
+ case "RSA-OAEP-512":
849
+ return "RSA-OAEP";
850
+ default:
851
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
852
+ }
853
+ };
854
+ }
855
+ });
856
+
857
+ // ../../../node_modules/jose/dist/webapi/lib/cek.js
858
+ function cekLength(alg) {
859
+ switch (alg) {
860
+ case "A128GCM":
861
+ return 128;
862
+ case "A192GCM":
863
+ return 192;
864
+ case "A256GCM":
865
+ case "A128CBC-HS256":
866
+ return 256;
867
+ case "A192CBC-HS384":
868
+ return 384;
869
+ case "A256CBC-HS512":
870
+ return 512;
871
+ default:
872
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
873
+ }
874
+ }
875
+ var generateCek;
876
+ var init_cek = __esm({
877
+ "../../../node_modules/jose/dist/webapi/lib/cek.js"() {
878
+ init_errors();
879
+ generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3));
880
+ }
881
+ });
882
+
883
+ // ../../../node_modules/jose/dist/webapi/lib/asn1.js
884
+ function parsePKCS8Header(state) {
885
+ expectTag(state, 48, "Invalid PKCS#8 structure");
886
+ parseLength(state);
887
+ expectTag(state, 2, "Expected version field");
888
+ const verLen = parseLength(state);
889
+ state.pos += verLen;
890
+ expectTag(state, 48, "Expected algorithm identifier");
891
+ const algIdLen = parseLength(state);
892
+ const algIdStart = state.pos;
893
+ return { algIdStart, algIdLength: algIdLen };
894
+ }
895
+ function parseSPKIHeader(state) {
896
+ expectTag(state, 48, "Invalid SPKI structure");
897
+ parseLength(state);
898
+ expectTag(state, 48, "Expected algorithm identifier");
899
+ const algIdLen = parseLength(state);
900
+ const algIdStart = state.pos;
901
+ return { algIdStart, algIdLength: algIdLen };
902
+ }
903
+ function spkiFromX509(buf) {
904
+ const state = createASN1State(buf);
905
+ expectTag(state, 48, "Invalid certificate structure");
906
+ parseLength(state);
907
+ expectTag(state, 48, "Invalid tbsCertificate structure");
908
+ parseLength(state);
909
+ if (buf[state.pos] === 160) {
910
+ skipElement(state, 6);
911
+ } else {
912
+ skipElement(state, 5);
913
+ }
914
+ const spkiStart = state.pos;
915
+ expectTag(state, 48, "Invalid SPKI structure");
916
+ const spkiContentLen = parseLength(state);
917
+ return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));
918
+ }
919
+ function extractX509SPKI(x509) {
920
+ const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g);
921
+ return spkiFromX509(derBytes);
922
+ }
923
+ var formatPEM, genericExport, toSPKI, toPKCS8, bytesEqual, createASN1State, parseLength, skipElement, expectTag, getSubarray, parseAlgorithmOID, parseECAlgorithmIdentifier, genericImport, processPEMData, fromPKCS8, fromSPKI, fromX509;
924
+ var init_asn1 = __esm({
925
+ "../../../node_modules/jose/dist/webapi/lib/asn1.js"() {
926
+ init_invalid_key_input();
927
+ init_base64();
928
+ init_errors();
929
+ init_is_key_like();
930
+ formatPEM = (b64, descriptor) => {
931
+ const newlined = (b64.match(/.{1,64}/g) || []).join("\n");
932
+ return `-----BEGIN ${descriptor}-----
933
+ ${newlined}
934
+ -----END ${descriptor}-----`;
935
+ };
936
+ genericExport = async (keyType, keyFormat, key) => {
937
+ if (isKeyObject(key)) {
938
+ if (key.type !== keyType) {
939
+ throw new TypeError(`key is not a ${keyType} key`);
940
+ }
941
+ return key.export({ format: "pem", type: keyFormat });
942
+ }
943
+ if (!isCryptoKey(key)) {
944
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject"));
945
+ }
946
+ if (!key.extractable) {
947
+ throw new TypeError("CryptoKey is not extractable");
948
+ }
949
+ if (key.type !== keyType) {
950
+ throw new TypeError(`key is not a ${keyType} key`);
951
+ }
952
+ return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
953
+ };
954
+ toSPKI = (key) => genericExport("public", "spki", key);
955
+ toPKCS8 = (key) => genericExport("private", "pkcs8", key);
956
+ bytesEqual = (a, b) => {
957
+ if (a.byteLength !== b.length)
958
+ return false;
959
+ for (let i = 0; i < a.byteLength; i++) {
960
+ if (a[i] !== b[i])
961
+ return false;
962
+ }
963
+ return true;
964
+ };
965
+ createASN1State = (data) => ({ data, pos: 0 });
966
+ parseLength = (state) => {
967
+ const first = state.data[state.pos++];
968
+ if (first & 128) {
969
+ const lengthOfLen = first & 127;
970
+ let length = 0;
971
+ for (let i = 0; i < lengthOfLen; i++) {
972
+ length = length << 8 | state.data[state.pos++];
973
+ }
974
+ return length;
975
+ }
976
+ return first;
977
+ };
978
+ skipElement = (state, count = 1) => {
979
+ if (count <= 0)
980
+ return;
981
+ state.pos++;
982
+ const length = parseLength(state);
983
+ state.pos += length;
984
+ if (count > 1) {
985
+ skipElement(state, count - 1);
986
+ }
987
+ };
988
+ expectTag = (state, expectedTag, errorMessage) => {
989
+ if (state.data[state.pos++] !== expectedTag) {
990
+ throw new Error(errorMessage);
991
+ }
992
+ };
993
+ getSubarray = (state, length) => {
994
+ const result = state.data.subarray(state.pos, state.pos + length);
995
+ state.pos += length;
996
+ return result;
997
+ };
998
+ parseAlgorithmOID = (state) => {
999
+ expectTag(state, 6, "Expected algorithm OID");
1000
+ const oidLen = parseLength(state);
1001
+ return getSubarray(state, oidLen);
1002
+ };
1003
+ parseECAlgorithmIdentifier = (state) => {
1004
+ const algOid = parseAlgorithmOID(state);
1005
+ if (bytesEqual(algOid, [43, 101, 110])) {
1006
+ return "X25519";
1007
+ }
1008
+ if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
1009
+ throw new Error("Unsupported key algorithm");
1010
+ }
1011
+ expectTag(state, 6, "Expected curve OID");
1012
+ const curveOidLen = parseLength(state);
1013
+ const curveOid = getSubarray(state, curveOidLen);
1014
+ for (const { name, oid } of [
1015
+ { name: "P-256", oid: [42, 134, 72, 206, 61, 3, 1, 7] },
1016
+ { name: "P-384", oid: [43, 129, 4, 0, 34] },
1017
+ { name: "P-521", oid: [43, 129, 4, 0, 35] }
1018
+ ]) {
1019
+ if (bytesEqual(curveOid, oid)) {
1020
+ return name;
1021
+ }
1022
+ }
1023
+ throw new Error("Unsupported named curve");
1024
+ };
1025
+ genericImport = async (keyFormat, keyData, alg, options) => {
1026
+ let algorithm;
1027
+ let keyUsages;
1028
+ const isPublic = keyFormat === "spki";
1029
+ const getSigUsages = () => isPublic ? ["verify"] : ["sign"];
1030
+ const getEncUsages = () => isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
1031
+ switch (alg) {
1032
+ case "PS256":
1033
+ case "PS384":
1034
+ case "PS512":
1035
+ algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` };
1036
+ keyUsages = getSigUsages();
1037
+ break;
1038
+ case "RS256":
1039
+ case "RS384":
1040
+ case "RS512":
1041
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` };
1042
+ keyUsages = getSigUsages();
1043
+ break;
1044
+ case "RSA-OAEP":
1045
+ case "RSA-OAEP-256":
1046
+ case "RSA-OAEP-384":
1047
+ case "RSA-OAEP-512":
1048
+ algorithm = {
1049
+ name: "RSA-OAEP",
1050
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
1051
+ };
1052
+ keyUsages = getEncUsages();
1053
+ break;
1054
+ case "ES256":
1055
+ case "ES384":
1056
+ case "ES512": {
1057
+ const curveMap = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
1058
+ algorithm = { name: "ECDSA", namedCurve: curveMap[alg] };
1059
+ keyUsages = getSigUsages();
1060
+ break;
1061
+ }
1062
+ case "ECDH-ES":
1063
+ case "ECDH-ES+A128KW":
1064
+ case "ECDH-ES+A192KW":
1065
+ case "ECDH-ES+A256KW": {
1066
+ try {
1067
+ const namedCurve = options.getNamedCurve(keyData);
1068
+ algorithm = namedCurve === "X25519" ? { name: "X25519" } : { name: "ECDH", namedCurve };
1069
+ } catch (cause) {
1070
+ throw new JOSENotSupported("Invalid or unsupported key format");
1071
+ }
1072
+ keyUsages = isPublic ? [] : ["deriveBits"];
1073
+ break;
1074
+ }
1075
+ case "Ed25519":
1076
+ case "EdDSA":
1077
+ algorithm = { name: "Ed25519" };
1078
+ keyUsages = getSigUsages();
1079
+ break;
1080
+ case "ML-DSA-44":
1081
+ case "ML-DSA-65":
1082
+ case "ML-DSA-87":
1083
+ algorithm = { name: alg };
1084
+ keyUsages = getSigUsages();
1085
+ break;
1086
+ default:
1087
+ throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
1088
+ }
1089
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
1090
+ };
1091
+ processPEMData = (pem, pattern) => {
1092
+ return decodeBase64(pem.replace(pattern, ""));
1093
+ };
1094
+ fromPKCS8 = (pem, alg, options) => {
1095
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
1096
+ let opts = options;
1097
+ if (alg?.startsWith?.("ECDH-ES")) {
1098
+ opts ||= {};
1099
+ opts.getNamedCurve = (keyData2) => {
1100
+ const state = createASN1State(keyData2);
1101
+ parsePKCS8Header(state);
1102
+ return parseECAlgorithmIdentifier(state);
1103
+ };
1104
+ }
1105
+ return genericImport("pkcs8", keyData, alg, opts);
1106
+ };
1107
+ fromSPKI = (pem, alg, options) => {
1108
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);
1109
+ let opts = options;
1110
+ if (alg?.startsWith?.("ECDH-ES")) {
1111
+ opts ||= {};
1112
+ opts.getNamedCurve = (keyData2) => {
1113
+ const state = createASN1State(keyData2);
1114
+ parseSPKIHeader(state);
1115
+ return parseECAlgorithmIdentifier(state);
1116
+ };
1117
+ }
1118
+ return genericImport("spki", keyData, alg, opts);
1119
+ };
1120
+ fromX509 = (pem, alg, options) => {
1121
+ let spki;
1122
+ try {
1123
+ spki = extractX509SPKI(pem);
1124
+ } catch (cause) {
1125
+ throw new TypeError("Failed to parse the X.509 certificate", { cause });
1126
+ }
1127
+ return fromSPKI(formatPEM(encodeBase64(spki), "PUBLIC KEY"), alg, options);
1128
+ };
1129
+ }
1130
+ });
1131
+
1132
+ // ../../../node_modules/jose/dist/webapi/lib/jwk_to_key.js
1133
+ function subtleMapping(jwk) {
1134
+ let algorithm;
1135
+ let keyUsages;
1136
+ switch (jwk.kty) {
1137
+ case "AKP": {
1138
+ switch (jwk.alg) {
1139
+ case "ML-DSA-44":
1140
+ case "ML-DSA-65":
1141
+ case "ML-DSA-87":
1142
+ algorithm = { name: jwk.alg };
1143
+ keyUsages = jwk.priv ? ["sign"] : ["verify"];
1144
+ break;
1145
+ default:
1146
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1147
+ }
1148
+ break;
1149
+ }
1150
+ case "RSA": {
1151
+ switch (jwk.alg) {
1152
+ case "PS256":
1153
+ case "PS384":
1154
+ case "PS512":
1155
+ algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
1156
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
1157
+ break;
1158
+ case "RS256":
1159
+ case "RS384":
1160
+ case "RS512":
1161
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
1162
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
1163
+ break;
1164
+ case "RSA-OAEP":
1165
+ case "RSA-OAEP-256":
1166
+ case "RSA-OAEP-384":
1167
+ case "RSA-OAEP-512":
1168
+ algorithm = {
1169
+ name: "RSA-OAEP",
1170
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
1171
+ };
1172
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
1173
+ break;
1174
+ default:
1175
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1176
+ }
1177
+ break;
1178
+ }
1179
+ case "EC": {
1180
+ switch (jwk.alg) {
1181
+ case "ES256":
1182
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
1183
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
1184
+ break;
1185
+ case "ES384":
1186
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
1187
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
1188
+ break;
1189
+ case "ES512":
1190
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
1191
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
1192
+ break;
1193
+ case "ECDH-ES":
1194
+ case "ECDH-ES+A128KW":
1195
+ case "ECDH-ES+A192KW":
1196
+ case "ECDH-ES+A256KW":
1197
+ algorithm = { name: "ECDH", namedCurve: jwk.crv };
1198
+ keyUsages = jwk.d ? ["deriveBits"] : [];
1199
+ break;
1200
+ default:
1201
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1202
+ }
1203
+ break;
1204
+ }
1205
+ case "OKP": {
1206
+ switch (jwk.alg) {
1207
+ case "Ed25519":
1208
+ case "EdDSA":
1209
+ algorithm = { name: "Ed25519" };
1210
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
1211
+ break;
1212
+ case "ECDH-ES":
1213
+ case "ECDH-ES+A128KW":
1214
+ case "ECDH-ES+A192KW":
1215
+ case "ECDH-ES+A256KW":
1216
+ algorithm = { name: jwk.crv };
1217
+ keyUsages = jwk.d ? ["deriveBits"] : [];
1218
+ break;
1219
+ default:
1220
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1221
+ }
1222
+ break;
1223
+ }
1224
+ default:
1225
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
1226
+ }
1227
+ return { algorithm, keyUsages };
1228
+ }
1229
+ async function jwkToKey(jwk) {
1230
+ if (!jwk.alg) {
1231
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
1232
+ }
1233
+ const { algorithm, keyUsages } = subtleMapping(jwk);
1234
+ const keyData = { ...jwk };
1235
+ if (keyData.kty !== "AKP") {
1236
+ delete keyData.alg;
1237
+ }
1238
+ delete keyData.use;
1239
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
1240
+ }
1241
+ var init_jwk_to_key = __esm({
1242
+ "../../../node_modules/jose/dist/webapi/lib/jwk_to_key.js"() {
1243
+ init_errors();
1244
+ }
1245
+ });
1246
+
1247
+ // ../../../node_modules/jose/dist/webapi/key/import.js
1248
+ async function importSPKI(spki, alg, options) {
1249
+ if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) {
1250
+ throw new TypeError('"spki" must be SPKI formatted string');
1251
+ }
1252
+ return fromSPKI(spki, alg, options);
1253
+ }
1254
+ async function importX509(x509, alg, options) {
1255
+ if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) {
1256
+ throw new TypeError('"x509" must be X.509 formatted string');
1257
+ }
1258
+ return fromX509(x509, alg, options);
1259
+ }
1260
+ async function importPKCS8(pkcs8, alg, options) {
1261
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
1262
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
1263
+ }
1264
+ return fromPKCS8(pkcs8, alg, options);
1265
+ }
1266
+ async function importJWK(jwk, alg, options) {
1267
+ if (!isObject(jwk)) {
1268
+ throw new TypeError("JWK must be an object");
1269
+ }
1270
+ let ext;
1271
+ alg ??= jwk.alg;
1272
+ ext ??= options?.extractable ?? jwk.ext;
1273
+ switch (jwk.kty) {
1274
+ case "oct":
1275
+ if (typeof jwk.k !== "string" || !jwk.k) {
1276
+ throw new TypeError('missing "k" (Key Value) Parameter value');
1277
+ }
1278
+ return decode(jwk.k);
1279
+ case "RSA":
1280
+ if ("oth" in jwk && jwk.oth !== void 0) {
1281
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
1282
+ }
1283
+ return jwkToKey({ ...jwk, alg, ext });
1284
+ case "AKP": {
1285
+ if (typeof jwk.alg !== "string" || !jwk.alg) {
1286
+ throw new TypeError('missing "alg" (Algorithm) Parameter value');
1287
+ }
1288
+ if (alg !== void 0 && alg !== jwk.alg) {
1289
+ throw new TypeError("JWK alg and alg option value mismatch");
1290
+ }
1291
+ return jwkToKey({ ...jwk, ext });
1292
+ }
1293
+ case "EC":
1294
+ case "OKP":
1295
+ return jwkToKey({ ...jwk, alg, ext });
1296
+ default:
1297
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
1298
+ }
1299
+ }
1300
+ var init_import = __esm({
1301
+ "../../../node_modules/jose/dist/webapi/key/import.js"() {
1302
+ init_base64url();
1303
+ init_asn1();
1304
+ init_jwk_to_key();
1305
+ init_errors();
1306
+ init_is_object();
1307
+ }
1308
+ });
1309
+
1310
+ // ../../../node_modules/jose/dist/webapi/lib/encrypt.js
1311
+ async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
1312
+ if (!(cek instanceof Uint8Array)) {
1313
+ throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
1314
+ }
1315
+ const keySize = parseInt(enc.slice(1, 4), 10);
1316
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]);
1317
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
1318
+ hash: `SHA-${keySize << 1}`,
1319
+ name: "HMAC"
1320
+ }, false, ["sign"]);
1321
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
1322
+ iv,
1323
+ name: "AES-CBC"
1324
+ }, encKey, plaintext));
1325
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
1326
+ const tag2 = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
1327
+ return { ciphertext, tag: tag2, iv };
1328
+ }
1329
+ async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
1330
+ let encKey;
1331
+ if (cek instanceof Uint8Array) {
1332
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
1333
+ } else {
1334
+ checkEncCryptoKey(cek, enc, "encrypt");
1335
+ encKey = cek;
1336
+ }
1337
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
1338
+ additionalData: aad,
1339
+ iv,
1340
+ name: "AES-GCM",
1341
+ tagLength: 128
1342
+ }, encKey, plaintext));
1343
+ const tag2 = encrypted.slice(-16);
1344
+ const ciphertext = encrypted.slice(0, -16);
1345
+ return { ciphertext, tag: tag2, iv };
1346
+ }
1347
+ async function encrypt2(enc, plaintext, cek, iv, aad) {
1348
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
1349
+ throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
1350
+ }
1351
+ if (iv) {
1352
+ checkIvLength(enc, iv);
1353
+ } else {
1354
+ iv = generateIv(enc);
1355
+ }
1356
+ switch (enc) {
1357
+ case "A128CBC-HS256":
1358
+ case "A192CBC-HS384":
1359
+ case "A256CBC-HS512":
1360
+ if (cek instanceof Uint8Array) {
1361
+ checkCekLength(cek, parseInt(enc.slice(-3), 10));
1362
+ }
1363
+ return cbcEncrypt(enc, plaintext, cek, iv, aad);
1364
+ case "A128GCM":
1365
+ case "A192GCM":
1366
+ case "A256GCM":
1367
+ if (cek instanceof Uint8Array) {
1368
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
1369
+ }
1370
+ return gcmEncrypt(enc, plaintext, cek, iv, aad);
1371
+ default:
1372
+ throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
1373
+ }
1374
+ }
1375
+ var init_encrypt = __esm({
1376
+ "../../../node_modules/jose/dist/webapi/lib/encrypt.js"() {
1377
+ init_buffer_utils();
1378
+ init_check_iv_length();
1379
+ init_check_cek_length();
1380
+ init_crypto_key();
1381
+ init_invalid_key_input();
1382
+ init_iv();
1383
+ init_errors();
1384
+ init_is_key_like();
1385
+ }
1386
+ });
1387
+
1388
+ // ../../../node_modules/jose/dist/webapi/lib/aesgcmkw.js
1389
+ async function wrap3(alg, key, cek, iv) {
1390
+ const jweAlgorithm = alg.slice(0, 7);
1391
+ const wrapped = await encrypt2(jweAlgorithm, cek, key, iv, new Uint8Array());
1392
+ return {
1393
+ encryptedKey: wrapped.ciphertext,
1394
+ iv: encode2(wrapped.iv),
1395
+ tag: encode2(wrapped.tag)
1396
+ };
1397
+ }
1398
+ async function unwrap3(alg, key, encryptedKey, iv, tag2) {
1399
+ const jweAlgorithm = alg.slice(0, 7);
1400
+ return decrypt(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array());
1401
+ }
1402
+ var init_aesgcmkw = __esm({
1403
+ "../../../node_modules/jose/dist/webapi/lib/aesgcmkw.js"() {
1404
+ init_encrypt();
1405
+ init_decrypt();
1406
+ init_base64url();
1407
+ }
1408
+ });
1409
+
1410
+ // ../../../node_modules/jose/dist/webapi/lib/decrypt_key_management.js
1411
+ async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
1412
+ switch (alg) {
1413
+ case "dir": {
1414
+ if (encryptedKey !== void 0)
1415
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
1416
+ return key;
1417
+ }
1418
+ case "ECDH-ES":
1419
+ if (encryptedKey !== void 0)
1420
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
1421
+ case "ECDH-ES+A128KW":
1422
+ case "ECDH-ES+A192KW":
1423
+ case "ECDH-ES+A256KW": {
1424
+ if (!isObject(joseHeader.epk))
1425
+ throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
1426
+ assertCryptoKey(key);
1427
+ if (!allowed(key))
1428
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
1429
+ const epk = await importJWK(joseHeader.epk, alg);
1430
+ assertCryptoKey(epk);
1431
+ let partyUInfo;
1432
+ let partyVInfo;
1433
+ if (joseHeader.apu !== void 0) {
1434
+ if (typeof joseHeader.apu !== "string")
1435
+ throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
1436
+ try {
1437
+ partyUInfo = decode(joseHeader.apu);
1438
+ } catch {
1439
+ throw new JWEInvalid("Failed to base64url decode the apu");
1440
+ }
1441
+ }
1442
+ if (joseHeader.apv !== void 0) {
1443
+ if (typeof joseHeader.apv !== "string")
1444
+ throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
1445
+ try {
1446
+ partyVInfo = decode(joseHeader.apv);
1447
+ } catch {
1448
+ throw new JWEInvalid("Failed to base64url decode the apv");
1449
+ }
1450
+ }
1451
+ 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);
1452
+ if (alg === "ECDH-ES")
1453
+ return sharedSecret;
1454
+ if (encryptedKey === void 0)
1455
+ throw new JWEInvalid("JWE Encrypted Key missing");
1456
+ return unwrap(alg.slice(-6), sharedSecret, encryptedKey);
1457
+ }
1458
+ case "RSA-OAEP":
1459
+ case "RSA-OAEP-256":
1460
+ case "RSA-OAEP-384":
1461
+ case "RSA-OAEP-512": {
1462
+ if (encryptedKey === void 0)
1463
+ throw new JWEInvalid("JWE Encrypted Key missing");
1464
+ assertCryptoKey(key);
1465
+ return decrypt2(alg, key, encryptedKey);
1466
+ }
1467
+ case "PBES2-HS256+A128KW":
1468
+ case "PBES2-HS384+A192KW":
1469
+ case "PBES2-HS512+A256KW": {
1470
+ if (encryptedKey === void 0)
1471
+ throw new JWEInvalid("JWE Encrypted Key missing");
1472
+ if (typeof joseHeader.p2c !== "number")
1473
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
1474
+ const p2cLimit = options?.maxPBES2Count || 1e4;
1475
+ if (joseHeader.p2c > p2cLimit)
1476
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
1477
+ if (typeof joseHeader.p2s !== "string")
1478
+ throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
1479
+ let p2s;
1480
+ try {
1481
+ p2s = decode(joseHeader.p2s);
1482
+ } catch {
1483
+ throw new JWEInvalid("Failed to base64url decode the p2s");
1484
+ }
1485
+ return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s);
1486
+ }
1487
+ case "A128KW":
1488
+ case "A192KW":
1489
+ case "A256KW": {
1490
+ if (encryptedKey === void 0)
1491
+ throw new JWEInvalid("JWE Encrypted Key missing");
1492
+ return unwrap(alg, key, encryptedKey);
1493
+ }
1494
+ case "A128GCMKW":
1495
+ case "A192GCMKW":
1496
+ case "A256GCMKW": {
1497
+ if (encryptedKey === void 0)
1498
+ throw new JWEInvalid("JWE Encrypted Key missing");
1499
+ if (typeof joseHeader.iv !== "string")
1500
+ throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
1501
+ if (typeof joseHeader.tag !== "string")
1502
+ throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
1503
+ let iv;
1504
+ try {
1505
+ iv = decode(joseHeader.iv);
1506
+ } catch {
1507
+ throw new JWEInvalid("Failed to base64url decode the iv");
1508
+ }
1509
+ let tag2;
1510
+ try {
1511
+ tag2 = decode(joseHeader.tag);
1512
+ } catch {
1513
+ throw new JWEInvalid("Failed to base64url decode the tag");
1514
+ }
1515
+ return unwrap3(alg, key, encryptedKey, iv, tag2);
1516
+ }
1517
+ default: {
1518
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
1519
+ }
1520
+ }
1521
+ }
1522
+ var init_decrypt_key_management = __esm({
1523
+ "../../../node_modules/jose/dist/webapi/lib/decrypt_key_management.js"() {
1524
+ init_aeskw();
1525
+ init_ecdhes();
1526
+ init_pbes2kw();
1527
+ init_rsaes();
1528
+ init_base64url();
1529
+ init_errors();
1530
+ init_cek();
1531
+ init_import();
1532
+ init_is_object();
1533
+ init_aesgcmkw();
1534
+ init_is_key_like();
1535
+ }
1536
+ });
1537
+
1538
+ // ../../../node_modules/jose/dist/webapi/lib/validate_crit.js
1539
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
1540
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
1541
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
1542
+ }
1543
+ if (!protectedHeader || protectedHeader.crit === void 0) {
1544
+ return /* @__PURE__ */ new Set();
1545
+ }
1546
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
1547
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
1548
+ }
1549
+ let recognized;
1550
+ if (recognizedOption !== void 0) {
1551
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
1552
+ } else {
1553
+ recognized = recognizedDefault;
1554
+ }
1555
+ for (const parameter of protectedHeader.crit) {
1556
+ if (!recognized.has(parameter)) {
1557
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
1558
+ }
1559
+ if (joseHeader[parameter] === void 0) {
1560
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
1561
+ }
1562
+ if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
1563
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
1564
+ }
1565
+ }
1566
+ return new Set(protectedHeader.crit);
1567
+ }
1568
+ var init_validate_crit = __esm({
1569
+ "../../../node_modules/jose/dist/webapi/lib/validate_crit.js"() {
1570
+ init_errors();
1571
+ }
1572
+ });
1573
+
1574
+ // ../../../node_modules/jose/dist/webapi/lib/validate_algorithms.js
1575
+ function validateAlgorithms(option, algorithms) {
1576
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
1577
+ throw new TypeError(`"${option}" option must be an array of strings`);
1578
+ }
1579
+ if (!algorithms) {
1580
+ return void 0;
1581
+ }
1582
+ return new Set(algorithms);
1583
+ }
1584
+ var init_validate_algorithms = __esm({
1585
+ "../../../node_modules/jose/dist/webapi/lib/validate_algorithms.js"() {
1586
+ }
1587
+ });
1588
+
1589
+ // ../../../node_modules/jose/dist/webapi/lib/is_jwk.js
1590
+ var isJWK, isPrivateJWK, isPublicJWK, isSecretJWK;
1591
+ var init_is_jwk = __esm({
1592
+ "../../../node_modules/jose/dist/webapi/lib/is_jwk.js"() {
1593
+ init_is_object();
1594
+ isJWK = (key) => isObject(key) && typeof key.kty === "string";
1595
+ isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
1596
+ isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
1597
+ isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
1598
+ }
1599
+ });
1600
+
1601
+ // ../../../node_modules/jose/dist/webapi/lib/normalize_key.js
1602
+ async function normalizeKey(key, alg) {
1603
+ if (key instanceof Uint8Array) {
1604
+ return key;
1605
+ }
1606
+ if (isCryptoKey(key)) {
1607
+ return key;
1608
+ }
1609
+ if (isKeyObject(key)) {
1610
+ if (key.type === "secret") {
1611
+ return key.export();
1612
+ }
1613
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
1614
+ try {
1615
+ return handleKeyObject(key, alg);
1616
+ } catch (err) {
1617
+ if (err instanceof TypeError) {
1618
+ throw err;
1619
+ }
1620
+ }
1621
+ }
1622
+ let jwk = key.export({ format: "jwk" });
1623
+ return handleJWK(key, jwk, alg);
1624
+ }
1625
+ if (isJWK(key)) {
1626
+ if (key.k) {
1627
+ return decode(key.k);
1628
+ }
1629
+ return handleJWK(key, key, alg, true);
1630
+ }
1631
+ throw new Error("unreachable");
1632
+ }
1633
+ var cache, handleJWK, handleKeyObject;
1634
+ var init_normalize_key = __esm({
1635
+ "../../../node_modules/jose/dist/webapi/lib/normalize_key.js"() {
1636
+ init_is_jwk();
1637
+ init_base64url();
1638
+ init_jwk_to_key();
1639
+ init_is_key_like();
1640
+ handleJWK = async (key, jwk, alg, freeze = false) => {
1641
+ cache ||= /* @__PURE__ */ new WeakMap();
1642
+ let cached = cache.get(key);
1643
+ if (cached?.[alg]) {
1644
+ return cached[alg];
1645
+ }
1646
+ const cryptoKey = await jwkToKey({ ...jwk, alg });
1647
+ if (freeze)
1648
+ Object.freeze(key);
1649
+ if (!cached) {
1650
+ cache.set(key, { [alg]: cryptoKey });
1651
+ } else {
1652
+ cached[alg] = cryptoKey;
1653
+ }
1654
+ return cryptoKey;
1655
+ };
1656
+ handleKeyObject = (keyObject, alg) => {
1657
+ cache ||= /* @__PURE__ */ new WeakMap();
1658
+ let cached = cache.get(keyObject);
1659
+ if (cached?.[alg]) {
1660
+ return cached[alg];
1661
+ }
1662
+ const isPublic = keyObject.type === "public";
1663
+ const extractable = isPublic ? true : false;
1664
+ let cryptoKey;
1665
+ if (keyObject.asymmetricKeyType === "x25519") {
1666
+ switch (alg) {
1667
+ case "ECDH-ES":
1668
+ case "ECDH-ES+A128KW":
1669
+ case "ECDH-ES+A192KW":
1670
+ case "ECDH-ES+A256KW":
1671
+ break;
1672
+ default:
1673
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1674
+ }
1675
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
1676
+ }
1677
+ if (keyObject.asymmetricKeyType === "ed25519") {
1678
+ if (alg !== "EdDSA" && alg !== "Ed25519") {
1679
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1680
+ }
1681
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
1682
+ isPublic ? "verify" : "sign"
1683
+ ]);
1684
+ }
1685
+ switch (keyObject.asymmetricKeyType) {
1686
+ case "ml-dsa-44":
1687
+ case "ml-dsa-65":
1688
+ case "ml-dsa-87": {
1689
+ if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
1690
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1691
+ }
1692
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
1693
+ isPublic ? "verify" : "sign"
1694
+ ]);
1695
+ }
1696
+ }
1697
+ if (keyObject.asymmetricKeyType === "rsa") {
1698
+ let hash;
1699
+ switch (alg) {
1700
+ case "RSA-OAEP":
1701
+ hash = "SHA-1";
1702
+ break;
1703
+ case "RS256":
1704
+ case "PS256":
1705
+ case "RSA-OAEP-256":
1706
+ hash = "SHA-256";
1707
+ break;
1708
+ case "RS384":
1709
+ case "PS384":
1710
+ case "RSA-OAEP-384":
1711
+ hash = "SHA-384";
1712
+ break;
1713
+ case "RS512":
1714
+ case "PS512":
1715
+ case "RSA-OAEP-512":
1716
+ hash = "SHA-512";
1717
+ break;
1718
+ default:
1719
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1720
+ }
1721
+ if (alg.startsWith("RSA-OAEP")) {
1722
+ return keyObject.toCryptoKey({
1723
+ name: "RSA-OAEP",
1724
+ hash
1725
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
1726
+ }
1727
+ cryptoKey = keyObject.toCryptoKey({
1728
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
1729
+ hash
1730
+ }, extractable, [isPublic ? "verify" : "sign"]);
1731
+ }
1732
+ if (keyObject.asymmetricKeyType === "ec") {
1733
+ const nist = /* @__PURE__ */ new Map([
1734
+ ["prime256v1", "P-256"],
1735
+ ["secp384r1", "P-384"],
1736
+ ["secp521r1", "P-521"]
1737
+ ]);
1738
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
1739
+ if (!namedCurve) {
1740
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1741
+ }
1742
+ if (alg === "ES256" && namedCurve === "P-256") {
1743
+ cryptoKey = keyObject.toCryptoKey({
1744
+ name: "ECDSA",
1745
+ namedCurve
1746
+ }, extractable, [isPublic ? "verify" : "sign"]);
1747
+ }
1748
+ if (alg === "ES384" && namedCurve === "P-384") {
1749
+ cryptoKey = keyObject.toCryptoKey({
1750
+ name: "ECDSA",
1751
+ namedCurve
1752
+ }, extractable, [isPublic ? "verify" : "sign"]);
1753
+ }
1754
+ if (alg === "ES512" && namedCurve === "P-521") {
1755
+ cryptoKey = keyObject.toCryptoKey({
1756
+ name: "ECDSA",
1757
+ namedCurve
1758
+ }, extractable, [isPublic ? "verify" : "sign"]);
1759
+ }
1760
+ if (alg.startsWith("ECDH-ES")) {
1761
+ cryptoKey = keyObject.toCryptoKey({
1762
+ name: "ECDH",
1763
+ namedCurve
1764
+ }, extractable, isPublic ? [] : ["deriveBits"]);
1765
+ }
1766
+ }
1767
+ if (!cryptoKey) {
1768
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1769
+ }
1770
+ if (!cached) {
1771
+ cache.set(keyObject, { [alg]: cryptoKey });
1772
+ } else {
1773
+ cached[alg] = cryptoKey;
1774
+ }
1775
+ return cryptoKey;
1776
+ };
1777
+ }
1778
+ });
1779
+
1780
+ // ../../../node_modules/jose/dist/webapi/lib/check_key_type.js
1781
+ function checkKeyType(alg, key, usage) {
1782
+ switch (alg.substring(0, 2)) {
1783
+ case "A1":
1784
+ case "A2":
1785
+ case "di":
1786
+ case "HS":
1787
+ case "PB":
1788
+ symmetricTypeCheck(alg, key, usage);
1789
+ break;
1790
+ default:
1791
+ asymmetricTypeCheck(alg, key, usage);
1792
+ }
1793
+ }
1794
+ var tag, jwkMatchesOp, symmetricTypeCheck, asymmetricTypeCheck;
1795
+ var init_check_key_type = __esm({
1796
+ "../../../node_modules/jose/dist/webapi/lib/check_key_type.js"() {
1797
+ init_invalid_key_input();
1798
+ init_is_key_like();
1799
+ init_is_jwk();
1800
+ tag = (key) => key?.[Symbol.toStringTag];
1801
+ jwkMatchesOp = (alg, key, usage) => {
1802
+ if (key.use !== void 0) {
1803
+ let expected;
1804
+ switch (usage) {
1805
+ case "sign":
1806
+ case "verify":
1807
+ expected = "sig";
1808
+ break;
1809
+ case "encrypt":
1810
+ case "decrypt":
1811
+ expected = "enc";
1812
+ break;
1813
+ }
1814
+ if (key.use !== expected) {
1815
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
1816
+ }
1817
+ }
1818
+ if (key.alg !== void 0 && key.alg !== alg) {
1819
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
1820
+ }
1821
+ if (Array.isArray(key.key_ops)) {
1822
+ let expectedKeyOp;
1823
+ switch (true) {
1824
+ case (usage === "sign" || usage === "verify"):
1825
+ case alg === "dir":
1826
+ case alg.includes("CBC-HS"):
1827
+ expectedKeyOp = usage;
1828
+ break;
1829
+ case alg.startsWith("PBES2"):
1830
+ expectedKeyOp = "deriveBits";
1831
+ break;
1832
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
1833
+ if (!alg.includes("GCM") && alg.endsWith("KW")) {
1834
+ expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
1835
+ } else {
1836
+ expectedKeyOp = usage;
1837
+ }
1838
+ break;
1839
+ case (usage === "encrypt" && alg.startsWith("RSA")):
1840
+ expectedKeyOp = "wrapKey";
1841
+ break;
1842
+ case usage === "decrypt":
1843
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
1844
+ break;
1845
+ }
1846
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
1847
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
1848
+ }
1849
+ }
1850
+ return true;
1851
+ };
1852
+ symmetricTypeCheck = (alg, key, usage) => {
1853
+ if (key instanceof Uint8Array)
1854
+ return;
1855
+ if (isJWK(key)) {
1856
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
1857
+ return;
1858
+ throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
1859
+ }
1860
+ if (!isKeyLike(key)) {
1861
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
1862
+ }
1863
+ if (key.type !== "secret") {
1864
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
1865
+ }
1866
+ };
1867
+ asymmetricTypeCheck = (alg, key, usage) => {
1868
+ if (isJWK(key)) {
1869
+ switch (usage) {
1870
+ case "decrypt":
1871
+ case "sign":
1872
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
1873
+ return;
1874
+ throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
1875
+ case "encrypt":
1876
+ case "verify":
1877
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
1878
+ return;
1879
+ throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
1880
+ }
1881
+ }
1882
+ if (!isKeyLike(key)) {
1883
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
1884
+ }
1885
+ if (key.type === "secret") {
1886
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
1887
+ }
1888
+ if (key.type === "public") {
1889
+ switch (usage) {
1890
+ case "sign":
1891
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
1892
+ case "decrypt":
1893
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
1894
+ }
1895
+ }
1896
+ if (key.type === "private") {
1897
+ switch (usage) {
1898
+ case "verify":
1899
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
1900
+ case "encrypt":
1901
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
1902
+ }
1903
+ }
1904
+ };
1905
+ }
1906
+ });
1907
+
1908
+ // ../../../node_modules/jose/dist/webapi/jwe/flattened/decrypt.js
1909
+ async function flattenedDecrypt(jwe, key, options) {
1910
+ if (!isObject(jwe)) {
1911
+ throw new JWEInvalid("Flattened JWE must be an object");
1912
+ }
1913
+ if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) {
1914
+ throw new JWEInvalid("JOSE Header missing");
1915
+ }
1916
+ if (jwe.iv !== void 0 && typeof jwe.iv !== "string") {
1917
+ throw new JWEInvalid("JWE Initialization Vector incorrect type");
1918
+ }
1919
+ if (typeof jwe.ciphertext !== "string") {
1920
+ throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
1921
+ }
1922
+ if (jwe.tag !== void 0 && typeof jwe.tag !== "string") {
1923
+ throw new JWEInvalid("JWE Authentication Tag incorrect type");
1924
+ }
1925
+ if (jwe.protected !== void 0 && typeof jwe.protected !== "string") {
1926
+ throw new JWEInvalid("JWE Protected Header incorrect type");
1927
+ }
1928
+ if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") {
1929
+ throw new JWEInvalid("JWE Encrypted Key incorrect type");
1930
+ }
1931
+ if (jwe.aad !== void 0 && typeof jwe.aad !== "string") {
1932
+ throw new JWEInvalid("JWE AAD incorrect type");
1933
+ }
1934
+ if (jwe.header !== void 0 && !isObject(jwe.header)) {
1935
+ throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
1936
+ }
1937
+ if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) {
1938
+ throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
1939
+ }
1940
+ let parsedProt;
1941
+ if (jwe.protected) {
1942
+ try {
1943
+ const protectedHeader2 = decode(jwe.protected);
1944
+ parsedProt = JSON.parse(decoder.decode(protectedHeader2));
1945
+ } catch {
1946
+ throw new JWEInvalid("JWE Protected Header is invalid");
1947
+ }
1948
+ }
1949
+ if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
1950
+ throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
1951
+ }
1952
+ const joseHeader = {
1953
+ ...parsedProt,
1954
+ ...jwe.header,
1955
+ ...jwe.unprotected
1956
+ };
1957
+ validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
1958
+ if (joseHeader.zip !== void 0) {
1959
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
1960
+ }
1961
+ const { alg, enc } = joseHeader;
1962
+ if (typeof alg !== "string" || !alg) {
1963
+ throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
1964
+ }
1965
+ if (typeof enc !== "string" || !enc) {
1966
+ throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
1967
+ }
1968
+ const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms);
1969
+ const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
1970
+ if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) {
1971
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
1972
+ }
1973
+ if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
1974
+ throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
1975
+ }
1976
+ let encryptedKey;
1977
+ if (jwe.encrypted_key !== void 0) {
1978
+ try {
1979
+ encryptedKey = decode(jwe.encrypted_key);
1980
+ } catch {
1981
+ throw new JWEInvalid("Failed to base64url decode the encrypted_key");
1982
+ }
1983
+ }
1984
+ let resolvedKey = false;
1985
+ if (typeof key === "function") {
1986
+ key = await key(parsedProt, jwe);
1987
+ resolvedKey = true;
1988
+ }
1989
+ checkKeyType(alg === "dir" ? enc : alg, key, "decrypt");
1990
+ const k = await normalizeKey(key, alg);
1991
+ let cek;
1992
+ try {
1993
+ cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);
1994
+ } catch (err) {
1995
+ if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
1996
+ throw err;
1997
+ }
1998
+ cek = generateCek(enc);
1999
+ }
2000
+ let iv;
2001
+ let tag2;
2002
+ if (jwe.iv !== void 0) {
2003
+ try {
2004
+ iv = decode(jwe.iv);
2005
+ } catch {
2006
+ throw new JWEInvalid("Failed to base64url decode the iv");
2007
+ }
2008
+ }
2009
+ if (jwe.tag !== void 0) {
2010
+ try {
2011
+ tag2 = decode(jwe.tag);
2012
+ } catch {
2013
+ throw new JWEInvalid("Failed to base64url decode the tag");
2014
+ }
2015
+ }
2016
+ const protectedHeader = jwe.protected !== void 0 ? encode(jwe.protected) : new Uint8Array();
2017
+ let additionalData;
2018
+ if (jwe.aad !== void 0) {
2019
+ additionalData = concat(protectedHeader, encode("."), encode(jwe.aad));
2020
+ } else {
2021
+ additionalData = protectedHeader;
2022
+ }
2023
+ let ciphertext;
2024
+ try {
2025
+ ciphertext = decode(jwe.ciphertext);
2026
+ } catch {
2027
+ throw new JWEInvalid("Failed to base64url decode the ciphertext");
2028
+ }
2029
+ const plaintext = await decrypt(enc, cek, ciphertext, iv, tag2, additionalData);
2030
+ const result = { plaintext };
2031
+ if (jwe.protected !== void 0) {
2032
+ result.protectedHeader = parsedProt;
2033
+ }
2034
+ if (jwe.aad !== void 0) {
2035
+ try {
2036
+ result.additionalAuthenticatedData = decode(jwe.aad);
2037
+ } catch {
2038
+ throw new JWEInvalid("Failed to base64url decode the aad");
2039
+ }
2040
+ }
2041
+ if (jwe.unprotected !== void 0) {
2042
+ result.sharedUnprotectedHeader = jwe.unprotected;
2043
+ }
2044
+ if (jwe.header !== void 0) {
2045
+ result.unprotectedHeader = jwe.header;
2046
+ }
2047
+ if (resolvedKey) {
2048
+ return { ...result, key: k };
2049
+ }
2050
+ return result;
2051
+ }
2052
+ var init_decrypt2 = __esm({
2053
+ "../../../node_modules/jose/dist/webapi/jwe/flattened/decrypt.js"() {
2054
+ init_base64url();
2055
+ init_decrypt();
2056
+ init_errors();
2057
+ init_is_disjoint();
2058
+ init_is_object();
2059
+ init_decrypt_key_management();
2060
+ init_buffer_utils();
2061
+ init_cek();
2062
+ init_validate_crit();
2063
+ init_validate_algorithms();
2064
+ init_normalize_key();
2065
+ init_check_key_type();
2066
+ }
2067
+ });
2068
+
2069
+ // ../../../node_modules/jose/dist/webapi/jwe/compact/decrypt.js
2070
+ async function compactDecrypt(jwe, key, options) {
2071
+ if (jwe instanceof Uint8Array) {
2072
+ jwe = decoder.decode(jwe);
2073
+ }
2074
+ if (typeof jwe !== "string") {
2075
+ throw new JWEInvalid("Compact JWE must be a string or Uint8Array");
2076
+ }
2077
+ const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split(".");
2078
+ if (length !== 5) {
2079
+ throw new JWEInvalid("Invalid Compact JWE");
2080
+ }
2081
+ const decrypted = await flattenedDecrypt({
2082
+ ciphertext,
2083
+ iv: iv || void 0,
2084
+ protected: protectedHeader,
2085
+ tag: tag2 || void 0,
2086
+ encrypted_key: encryptedKey || void 0
2087
+ }, key, options);
2088
+ const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
2089
+ if (typeof key === "function") {
2090
+ return { ...result, key: decrypted.key };
2091
+ }
2092
+ return result;
2093
+ }
2094
+ var init_decrypt3 = __esm({
2095
+ "../../../node_modules/jose/dist/webapi/jwe/compact/decrypt.js"() {
2096
+ init_decrypt2();
2097
+ init_errors();
2098
+ init_buffer_utils();
2099
+ }
2100
+ });
2101
+
2102
+ // ../../../node_modules/jose/dist/webapi/jwe/general/decrypt.js
2103
+ async function generalDecrypt(jwe, key, options) {
2104
+ if (!isObject(jwe)) {
2105
+ throw new JWEInvalid("General JWE must be an object");
2106
+ }
2107
+ if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) {
2108
+ throw new JWEInvalid("JWE Recipients missing or incorrect type");
2109
+ }
2110
+ if (!jwe.recipients.length) {
2111
+ throw new JWEInvalid("JWE Recipients has no members");
2112
+ }
2113
+ for (const recipient of jwe.recipients) {
2114
+ try {
2115
+ return await flattenedDecrypt({
2116
+ aad: jwe.aad,
2117
+ ciphertext: jwe.ciphertext,
2118
+ encrypted_key: recipient.encrypted_key,
2119
+ header: recipient.header,
2120
+ iv: jwe.iv,
2121
+ protected: jwe.protected,
2122
+ tag: jwe.tag,
2123
+ unprotected: jwe.unprotected
2124
+ }, key, options);
2125
+ } catch {
2126
+ }
2127
+ }
2128
+ throw new JWEDecryptionFailed();
2129
+ }
2130
+ var init_decrypt4 = __esm({
2131
+ "../../../node_modules/jose/dist/webapi/jwe/general/decrypt.js"() {
2132
+ init_decrypt2();
2133
+ init_errors();
2134
+ init_is_object();
2135
+ }
2136
+ });
2137
+
2138
+ // ../../../node_modules/jose/dist/webapi/lib/private_symbols.js
2139
+ var unprotected;
2140
+ var init_private_symbols = __esm({
2141
+ "../../../node_modules/jose/dist/webapi/lib/private_symbols.js"() {
2142
+ unprotected = /* @__PURE__ */ Symbol();
2143
+ }
2144
+ });
2145
+
2146
+ // ../../../node_modules/jose/dist/webapi/lib/key_to_jwk.js
2147
+ async function keyToJWK(key) {
2148
+ if (isKeyObject(key)) {
2149
+ if (key.type === "secret") {
2150
+ key = key.export();
2151
+ } else {
2152
+ return key.export({ format: "jwk" });
2153
+ }
2154
+ }
2155
+ if (key instanceof Uint8Array) {
2156
+ return {
2157
+ kty: "oct",
2158
+ k: encode2(key)
2159
+ };
2160
+ }
2161
+ if (!isCryptoKey(key)) {
2162
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
2163
+ }
2164
+ if (!key.extractable) {
2165
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
2166
+ }
2167
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
2168
+ if (jwk.kty === "AKP") {
2169
+ jwk.alg = alg;
2170
+ }
2171
+ return jwk;
2172
+ }
2173
+ var init_key_to_jwk = __esm({
2174
+ "../../../node_modules/jose/dist/webapi/lib/key_to_jwk.js"() {
2175
+ init_invalid_key_input();
2176
+ init_base64url();
2177
+ init_is_key_like();
2178
+ }
2179
+ });
2180
+
2181
+ // ../../../node_modules/jose/dist/webapi/key/export.js
2182
+ async function exportSPKI(key) {
2183
+ return toSPKI(key);
2184
+ }
2185
+ async function exportPKCS8(key) {
2186
+ return toPKCS8(key);
2187
+ }
2188
+ async function exportJWK(key) {
2189
+ return keyToJWK(key);
2190
+ }
2191
+ var init_export = __esm({
2192
+ "../../../node_modules/jose/dist/webapi/key/export.js"() {
2193
+ init_asn1();
2194
+ init_key_to_jwk();
2195
+ }
2196
+ });
2197
+
2198
+ // ../../../node_modules/jose/dist/webapi/lib/encrypt_key_management.js
2199
+ async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
2200
+ let encryptedKey;
2201
+ let parameters;
2202
+ let cek;
2203
+ switch (alg) {
2204
+ case "dir": {
2205
+ cek = key;
2206
+ break;
2207
+ }
2208
+ case "ECDH-ES":
2209
+ case "ECDH-ES+A128KW":
2210
+ case "ECDH-ES+A192KW":
2211
+ case "ECDH-ES+A256KW": {
2212
+ assertCryptoKey(key);
2213
+ if (!allowed(key)) {
2214
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
2215
+ }
2216
+ const { apu, apv } = providedParameters;
2217
+ let ephemeralKey;
2218
+ if (providedParameters.epk) {
2219
+ ephemeralKey = await normalizeKey(providedParameters.epk, alg);
2220
+ } else {
2221
+ ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
2222
+ }
2223
+ const { x, y, crv, kty } = await exportJWK(ephemeralKey);
2224
+ const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
2225
+ parameters = { epk: { x, crv, kty } };
2226
+ if (kty === "EC")
2227
+ parameters.epk.y = y;
2228
+ if (apu)
2229
+ parameters.apu = encode2(apu);
2230
+ if (apv)
2231
+ parameters.apv = encode2(apv);
2232
+ if (alg === "ECDH-ES") {
2233
+ cek = sharedSecret;
2234
+ break;
2235
+ }
2236
+ cek = providedCek || generateCek(enc);
2237
+ const kwAlg = alg.slice(-6);
2238
+ encryptedKey = await wrap(kwAlg, sharedSecret, cek);
2239
+ break;
2240
+ }
2241
+ case "RSA-OAEP":
2242
+ case "RSA-OAEP-256":
2243
+ case "RSA-OAEP-384":
2244
+ case "RSA-OAEP-512": {
2245
+ cek = providedCek || generateCek(enc);
2246
+ assertCryptoKey(key);
2247
+ encryptedKey = await encrypt(alg, key, cek);
2248
+ break;
2249
+ }
2250
+ case "PBES2-HS256+A128KW":
2251
+ case "PBES2-HS384+A192KW":
2252
+ case "PBES2-HS512+A256KW": {
2253
+ cek = providedCek || generateCek(enc);
2254
+ const { p2c, p2s } = providedParameters;
2255
+ ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s));
2256
+ break;
2257
+ }
2258
+ case "A128KW":
2259
+ case "A192KW":
2260
+ case "A256KW": {
2261
+ cek = providedCek || generateCek(enc);
2262
+ encryptedKey = await wrap(alg, key, cek);
2263
+ break;
2264
+ }
2265
+ case "A128GCMKW":
2266
+ case "A192GCMKW":
2267
+ case "A256GCMKW": {
2268
+ cek = providedCek || generateCek(enc);
2269
+ const { iv } = providedParameters;
2270
+ ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv));
2271
+ break;
2272
+ }
2273
+ default: {
2274
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
2275
+ }
2276
+ }
2277
+ return { cek, encryptedKey, parameters };
2278
+ }
2279
+ var init_encrypt_key_management = __esm({
2280
+ "../../../node_modules/jose/dist/webapi/lib/encrypt_key_management.js"() {
2281
+ init_aeskw();
2282
+ init_ecdhes();
2283
+ init_pbes2kw();
2284
+ init_rsaes();
2285
+ init_base64url();
2286
+ init_normalize_key();
2287
+ init_cek();
2288
+ init_errors();
2289
+ init_export();
2290
+ init_aesgcmkw();
2291
+ init_is_key_like();
2292
+ }
2293
+ });
2294
+
2295
+ // ../../../node_modules/jose/dist/webapi/jwe/flattened/encrypt.js
2296
+ var FlattenedEncrypt;
2297
+ var init_encrypt2 = __esm({
2298
+ "../../../node_modules/jose/dist/webapi/jwe/flattened/encrypt.js"() {
2299
+ init_base64url();
2300
+ init_private_symbols();
2301
+ init_encrypt();
2302
+ init_encrypt_key_management();
2303
+ init_errors();
2304
+ init_is_disjoint();
2305
+ init_buffer_utils();
2306
+ init_validate_crit();
2307
+ init_normalize_key();
2308
+ init_check_key_type();
2309
+ FlattenedEncrypt = class {
2310
+ #plaintext;
2311
+ #protectedHeader;
2312
+ #sharedUnprotectedHeader;
2313
+ #unprotectedHeader;
2314
+ #aad;
2315
+ #cek;
2316
+ #iv;
2317
+ #keyManagementParameters;
2318
+ constructor(plaintext) {
2319
+ if (!(plaintext instanceof Uint8Array)) {
2320
+ throw new TypeError("plaintext must be an instance of Uint8Array");
2321
+ }
2322
+ this.#plaintext = plaintext;
2323
+ }
2324
+ setKeyManagementParameters(parameters) {
2325
+ if (this.#keyManagementParameters) {
2326
+ throw new TypeError("setKeyManagementParameters can only be called once");
2327
+ }
2328
+ this.#keyManagementParameters = parameters;
2329
+ return this;
2330
+ }
2331
+ setProtectedHeader(protectedHeader) {
2332
+ if (this.#protectedHeader) {
2333
+ throw new TypeError("setProtectedHeader can only be called once");
2334
+ }
2335
+ this.#protectedHeader = protectedHeader;
2336
+ return this;
2337
+ }
2338
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
2339
+ if (this.#sharedUnprotectedHeader) {
2340
+ throw new TypeError("setSharedUnprotectedHeader can only be called once");
2341
+ }
2342
+ this.#sharedUnprotectedHeader = sharedUnprotectedHeader;
2343
+ return this;
2344
+ }
2345
+ setUnprotectedHeader(unprotectedHeader) {
2346
+ if (this.#unprotectedHeader) {
2347
+ throw new TypeError("setUnprotectedHeader can only be called once");
2348
+ }
2349
+ this.#unprotectedHeader = unprotectedHeader;
2350
+ return this;
2351
+ }
2352
+ setAdditionalAuthenticatedData(aad) {
2353
+ this.#aad = aad;
2354
+ return this;
2355
+ }
2356
+ setContentEncryptionKey(cek) {
2357
+ if (this.#cek) {
2358
+ throw new TypeError("setContentEncryptionKey can only be called once");
2359
+ }
2360
+ this.#cek = cek;
2361
+ return this;
2362
+ }
2363
+ setInitializationVector(iv) {
2364
+ if (this.#iv) {
2365
+ throw new TypeError("setInitializationVector can only be called once");
2366
+ }
2367
+ this.#iv = iv;
2368
+ return this;
2369
+ }
2370
+ async encrypt(key, options) {
2371
+ if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) {
2372
+ throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
2373
+ }
2374
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {
2375
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
2376
+ }
2377
+ const joseHeader = {
2378
+ ...this.#protectedHeader,
2379
+ ...this.#unprotectedHeader,
2380
+ ...this.#sharedUnprotectedHeader
2381
+ };
2382
+ validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader);
2383
+ if (joseHeader.zip !== void 0) {
2384
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
2385
+ }
2386
+ const { alg, enc } = joseHeader;
2387
+ if (typeof alg !== "string" || !alg) {
2388
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
2389
+ }
2390
+ if (typeof enc !== "string" || !enc) {
2391
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
2392
+ }
2393
+ let encryptedKey;
2394
+ if (this.#cek && (alg === "dir" || alg === "ECDH-ES")) {
2395
+ throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
2396
+ }
2397
+ checkKeyType(alg === "dir" ? enc : alg, key, "encrypt");
2398
+ let cek;
2399
+ {
2400
+ let parameters;
2401
+ const k = await normalizeKey(key, alg);
2402
+ ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters));
2403
+ if (parameters) {
2404
+ if (options && unprotected in options) {
2405
+ if (!this.#unprotectedHeader) {
2406
+ this.setUnprotectedHeader(parameters);
2407
+ } else {
2408
+ this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters };
2409
+ }
2410
+ } else if (!this.#protectedHeader) {
2411
+ this.setProtectedHeader(parameters);
2412
+ } else {
2413
+ this.#protectedHeader = { ...this.#protectedHeader, ...parameters };
2414
+ }
2415
+ }
2416
+ }
2417
+ let additionalData;
2418
+ let protectedHeaderS;
2419
+ let protectedHeaderB;
2420
+ let aadMember;
2421
+ if (this.#protectedHeader) {
2422
+ protectedHeaderS = encode2(JSON.stringify(this.#protectedHeader));
2423
+ protectedHeaderB = encode(protectedHeaderS);
2424
+ } else {
2425
+ protectedHeaderS = "";
2426
+ protectedHeaderB = new Uint8Array();
2427
+ }
2428
+ if (this.#aad) {
2429
+ aadMember = encode2(this.#aad);
2430
+ const aadMemberBytes = encode(aadMember);
2431
+ additionalData = concat(protectedHeaderB, encode("."), aadMemberBytes);
2432
+ } else {
2433
+ additionalData = protectedHeaderB;
2434
+ }
2435
+ const { ciphertext, tag: tag2, iv } = await encrypt2(enc, this.#plaintext, cek, this.#iv, additionalData);
2436
+ const jwe = {
2437
+ ciphertext: encode2(ciphertext)
2438
+ };
2439
+ if (iv) {
2440
+ jwe.iv = encode2(iv);
2441
+ }
2442
+ if (tag2) {
2443
+ jwe.tag = encode2(tag2);
2444
+ }
2445
+ if (encryptedKey) {
2446
+ jwe.encrypted_key = encode2(encryptedKey);
2447
+ }
2448
+ if (aadMember) {
2449
+ jwe.aad = aadMember;
2450
+ }
2451
+ if (this.#protectedHeader) {
2452
+ jwe.protected = protectedHeaderS;
2453
+ }
2454
+ if (this.#sharedUnprotectedHeader) {
2455
+ jwe.unprotected = this.#sharedUnprotectedHeader;
2456
+ }
2457
+ if (this.#unprotectedHeader) {
2458
+ jwe.header = this.#unprotectedHeader;
2459
+ }
2460
+ return jwe;
2461
+ }
2462
+ };
2463
+ }
2464
+ });
2465
+
2466
+ // ../../../node_modules/jose/dist/webapi/jwe/general/encrypt.js
2467
+ var IndividualRecipient, GeneralEncrypt;
2468
+ var init_encrypt3 = __esm({
2469
+ "../../../node_modules/jose/dist/webapi/jwe/general/encrypt.js"() {
2470
+ init_encrypt2();
2471
+ init_private_symbols();
2472
+ init_errors();
2473
+ init_cek();
2474
+ init_is_disjoint();
2475
+ init_encrypt_key_management();
2476
+ init_base64url();
2477
+ init_validate_crit();
2478
+ init_normalize_key();
2479
+ init_check_key_type();
2480
+ IndividualRecipient = class {
2481
+ #parent;
2482
+ unprotectedHeader;
2483
+ keyManagementParameters;
2484
+ key;
2485
+ options;
2486
+ constructor(enc, key, options) {
2487
+ this.#parent = enc;
2488
+ this.key = key;
2489
+ this.options = options;
2490
+ }
2491
+ setUnprotectedHeader(unprotectedHeader) {
2492
+ if (this.unprotectedHeader) {
2493
+ throw new TypeError("setUnprotectedHeader can only be called once");
2494
+ }
2495
+ this.unprotectedHeader = unprotectedHeader;
2496
+ return this;
2497
+ }
2498
+ setKeyManagementParameters(parameters) {
2499
+ if (this.keyManagementParameters) {
2500
+ throw new TypeError("setKeyManagementParameters can only be called once");
2501
+ }
2502
+ this.keyManagementParameters = parameters;
2503
+ return this;
2504
+ }
2505
+ addRecipient(...args) {
2506
+ return this.#parent.addRecipient(...args);
2507
+ }
2508
+ encrypt(...args) {
2509
+ return this.#parent.encrypt(...args);
2510
+ }
2511
+ done() {
2512
+ return this.#parent;
2513
+ }
2514
+ };
2515
+ GeneralEncrypt = class {
2516
+ #plaintext;
2517
+ #recipients = [];
2518
+ #protectedHeader;
2519
+ #unprotectedHeader;
2520
+ #aad;
2521
+ constructor(plaintext) {
2522
+ this.#plaintext = plaintext;
2523
+ }
2524
+ addRecipient(key, options) {
2525
+ const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
2526
+ this.#recipients.push(recipient);
2527
+ return recipient;
2528
+ }
2529
+ setProtectedHeader(protectedHeader) {
2530
+ if (this.#protectedHeader) {
2531
+ throw new TypeError("setProtectedHeader can only be called once");
2532
+ }
2533
+ this.#protectedHeader = protectedHeader;
2534
+ return this;
2535
+ }
2536
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
2537
+ if (this.#unprotectedHeader) {
2538
+ throw new TypeError("setSharedUnprotectedHeader can only be called once");
2539
+ }
2540
+ this.#unprotectedHeader = sharedUnprotectedHeader;
2541
+ return this;
2542
+ }
2543
+ setAdditionalAuthenticatedData(aad) {
2544
+ this.#aad = aad;
2545
+ return this;
2546
+ }
2547
+ async encrypt() {
2548
+ if (!this.#recipients.length) {
2549
+ throw new JWEInvalid("at least one recipient must be added");
2550
+ }
2551
+ if (this.#recipients.length === 1) {
2552
+ const [recipient] = this.#recipients;
2553
+ const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options });
2554
+ const jwe2 = {
2555
+ ciphertext: flattened.ciphertext,
2556
+ iv: flattened.iv,
2557
+ recipients: [{}],
2558
+ tag: flattened.tag
2559
+ };
2560
+ if (flattened.aad)
2561
+ jwe2.aad = flattened.aad;
2562
+ if (flattened.protected)
2563
+ jwe2.protected = flattened.protected;
2564
+ if (flattened.unprotected)
2565
+ jwe2.unprotected = flattened.unprotected;
2566
+ if (flattened.encrypted_key)
2567
+ jwe2.recipients[0].encrypted_key = flattened.encrypted_key;
2568
+ if (flattened.header)
2569
+ jwe2.recipients[0].header = flattened.header;
2570
+ return jwe2;
2571
+ }
2572
+ let enc;
2573
+ for (let i = 0; i < this.#recipients.length; i++) {
2574
+ const recipient = this.#recipients[i];
2575
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, recipient.unprotectedHeader)) {
2576
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
2577
+ }
2578
+ const joseHeader = {
2579
+ ...this.#protectedHeader,
2580
+ ...this.#unprotectedHeader,
2581
+ ...recipient.unprotectedHeader
2582
+ };
2583
+ const { alg } = joseHeader;
2584
+ if (typeof alg !== "string" || !alg) {
2585
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
2586
+ }
2587
+ if (alg === "dir" || alg === "ECDH-ES") {
2588
+ throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
2589
+ }
2590
+ if (typeof joseHeader.enc !== "string" || !joseHeader.enc) {
2591
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
2592
+ }
2593
+ if (!enc) {
2594
+ enc = joseHeader.enc;
2595
+ } else if (enc !== joseHeader.enc) {
2596
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
2597
+ }
2598
+ validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this.#protectedHeader, joseHeader);
2599
+ if (joseHeader.zip !== void 0) {
2600
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
2601
+ }
2602
+ }
2603
+ const cek = generateCek(enc);
2604
+ const jwe = {
2605
+ ciphertext: "",
2606
+ recipients: []
2607
+ };
2608
+ for (let i = 0; i < this.#recipients.length; i++) {
2609
+ const recipient = this.#recipients[i];
2610
+ const target = {};
2611
+ jwe.recipients.push(target);
2612
+ if (i === 0) {
2613
+ 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, {
2614
+ ...recipient.options,
2615
+ [unprotected]: true
2616
+ });
2617
+ jwe.ciphertext = flattened.ciphertext;
2618
+ jwe.iv = flattened.iv;
2619
+ jwe.tag = flattened.tag;
2620
+ if (flattened.aad)
2621
+ jwe.aad = flattened.aad;
2622
+ if (flattened.protected)
2623
+ jwe.protected = flattened.protected;
2624
+ if (flattened.unprotected)
2625
+ jwe.unprotected = flattened.unprotected;
2626
+ target.encrypted_key = flattened.encrypted_key;
2627
+ if (flattened.header)
2628
+ target.header = flattened.header;
2629
+ continue;
2630
+ }
2631
+ const alg = recipient.unprotectedHeader?.alg || this.#protectedHeader?.alg || this.#unprotectedHeader?.alg;
2632
+ checkKeyType(alg === "dir" ? enc : alg, recipient.key, "encrypt");
2633
+ const k = await normalizeKey(recipient.key, alg);
2634
+ const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters);
2635
+ target.encrypted_key = encode2(encryptedKey);
2636
+ if (recipient.unprotectedHeader || parameters)
2637
+ target.header = { ...recipient.unprotectedHeader, ...parameters };
2638
+ }
2639
+ return jwe;
2640
+ }
2641
+ };
2642
+ }
2643
+ });
2644
+
2645
+ // ../../../node_modules/jose/dist/webapi/lib/subtle_dsa.js
2646
+ function subtleAlgorithm2(alg, algorithm) {
2647
+ const hash = `SHA-${alg.slice(-3)}`;
2648
+ switch (alg) {
2649
+ case "HS256":
2650
+ case "HS384":
2651
+ case "HS512":
2652
+ return { hash, name: "HMAC" };
2653
+ case "PS256":
2654
+ case "PS384":
2655
+ case "PS512":
2656
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
2657
+ case "RS256":
2658
+ case "RS384":
2659
+ case "RS512":
2660
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
2661
+ case "ES256":
2662
+ case "ES384":
2663
+ case "ES512":
2664
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
2665
+ case "Ed25519":
2666
+ case "EdDSA":
2667
+ return { name: "Ed25519" };
2668
+ case "ML-DSA-44":
2669
+ case "ML-DSA-65":
2670
+ case "ML-DSA-87":
2671
+ return { name: alg };
2672
+ default:
2673
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
2674
+ }
2675
+ }
2676
+ var init_subtle_dsa = __esm({
2677
+ "../../../node_modules/jose/dist/webapi/lib/subtle_dsa.js"() {
2678
+ init_errors();
2679
+ }
2680
+ });
2681
+
2682
+ // ../../../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
2683
+ async function getSigKey(alg, key, usage) {
2684
+ if (key instanceof Uint8Array) {
2685
+ if (!alg.startsWith("HS")) {
2686
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
2687
+ }
2688
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
2689
+ }
2690
+ checkSigCryptoKey(key, alg, usage);
2691
+ return key;
2692
+ }
2693
+ var init_get_sign_verify_key = __esm({
2694
+ "../../../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js"() {
2695
+ init_crypto_key();
2696
+ init_invalid_key_input();
2697
+ }
2698
+ });
2699
+
2700
+ // ../../../node_modules/jose/dist/webapi/lib/verify.js
2701
+ async function verify(alg, key, signature, data) {
2702
+ const cryptoKey = await getSigKey(alg, key, "verify");
2703
+ checkKeyLength(alg, cryptoKey);
2704
+ const algorithm = subtleAlgorithm2(alg, cryptoKey.algorithm);
2705
+ try {
2706
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
2707
+ } catch {
2708
+ return false;
2709
+ }
2710
+ }
2711
+ var init_verify = __esm({
2712
+ "../../../node_modules/jose/dist/webapi/lib/verify.js"() {
2713
+ init_subtle_dsa();
2714
+ init_check_key_length();
2715
+ init_get_sign_verify_key();
2716
+ }
2717
+ });
2718
+
2719
+ // ../../../node_modules/jose/dist/webapi/jws/flattened/verify.js
2720
+ async function flattenedVerify(jws, key, options) {
2721
+ if (!isObject(jws)) {
2722
+ throw new JWSInvalid("Flattened JWS must be an object");
2723
+ }
2724
+ if (jws.protected === void 0 && jws.header === void 0) {
2725
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
2726
+ }
2727
+ if (jws.protected !== void 0 && typeof jws.protected !== "string") {
2728
+ throw new JWSInvalid("JWS Protected Header incorrect type");
2729
+ }
2730
+ if (jws.payload === void 0) {
2731
+ throw new JWSInvalid("JWS Payload missing");
2732
+ }
2733
+ if (typeof jws.signature !== "string") {
2734
+ throw new JWSInvalid("JWS Signature missing or incorrect type");
2735
+ }
2736
+ if (jws.header !== void 0 && !isObject(jws.header)) {
2737
+ throw new JWSInvalid("JWS Unprotected Header incorrect type");
2738
+ }
2739
+ let parsedProt = {};
2740
+ if (jws.protected) {
2741
+ try {
2742
+ const protectedHeader = decode(jws.protected);
2743
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
2744
+ } catch {
2745
+ throw new JWSInvalid("JWS Protected Header is invalid");
2746
+ }
2747
+ }
2748
+ if (!isDisjoint(parsedProt, jws.header)) {
2749
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
2750
+ }
2751
+ const joseHeader = {
2752
+ ...parsedProt,
2753
+ ...jws.header
2754
+ };
2755
+ const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
2756
+ let b64 = true;
2757
+ if (extensions.has("b64")) {
2758
+ b64 = parsedProt.b64;
2759
+ if (typeof b64 !== "boolean") {
2760
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
2761
+ }
2762
+ }
2763
+ const { alg } = joseHeader;
2764
+ if (typeof alg !== "string" || !alg) {
2765
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
2766
+ }
2767
+ const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
2768
+ if (algorithms && !algorithms.has(alg)) {
2769
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
2770
+ }
2771
+ if (b64) {
2772
+ if (typeof jws.payload !== "string") {
2773
+ throw new JWSInvalid("JWS Payload must be a string");
2774
+ }
2775
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
2776
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
2777
+ }
2778
+ let resolvedKey = false;
2779
+ if (typeof key === "function") {
2780
+ key = await key(parsedProt, jws);
2781
+ resolvedKey = true;
2782
+ }
2783
+ checkKeyType(alg, key, "verify");
2784
+ const data = concat(jws.protected !== void 0 ? encode(jws.protected) : new Uint8Array(), encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
2785
+ let signature;
2786
+ try {
2787
+ signature = decode(jws.signature);
2788
+ } catch {
2789
+ throw new JWSInvalid("Failed to base64url decode the signature");
2790
+ }
2791
+ const k = await normalizeKey(key, alg);
2792
+ const verified = await verify(alg, k, signature, data);
2793
+ if (!verified) {
2794
+ throw new JWSSignatureVerificationFailed();
2795
+ }
2796
+ let payload;
2797
+ if (b64) {
2798
+ try {
2799
+ payload = decode(jws.payload);
2800
+ } catch {
2801
+ throw new JWSInvalid("Failed to base64url decode the payload");
2802
+ }
2803
+ } else if (typeof jws.payload === "string") {
2804
+ payload = encoder.encode(jws.payload);
2805
+ } else {
2806
+ payload = jws.payload;
2807
+ }
2808
+ const result = { payload };
2809
+ if (jws.protected !== void 0) {
2810
+ result.protectedHeader = parsedProt;
2811
+ }
2812
+ if (jws.header !== void 0) {
2813
+ result.unprotectedHeader = jws.header;
2814
+ }
2815
+ if (resolvedKey) {
2816
+ return { ...result, key: k };
2817
+ }
2818
+ return result;
2819
+ }
2820
+ var init_verify2 = __esm({
2821
+ "../../../node_modules/jose/dist/webapi/jws/flattened/verify.js"() {
2822
+ init_base64url();
2823
+ init_verify();
2824
+ init_errors();
2825
+ init_buffer_utils();
2826
+ init_is_disjoint();
2827
+ init_is_object();
2828
+ init_check_key_type();
2829
+ init_validate_crit();
2830
+ init_validate_algorithms();
2831
+ init_normalize_key();
2832
+ }
2833
+ });
2834
+
2835
+ // ../../../node_modules/jose/dist/webapi/jws/compact/verify.js
2836
+ async function compactVerify(jws, key, options) {
2837
+ if (jws instanceof Uint8Array) {
2838
+ jws = decoder.decode(jws);
2839
+ }
2840
+ if (typeof jws !== "string") {
2841
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
2842
+ }
2843
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
2844
+ if (length !== 3) {
2845
+ throw new JWSInvalid("Invalid Compact JWS");
2846
+ }
2847
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
2848
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
2849
+ if (typeof key === "function") {
2850
+ return { ...result, key: verified.key };
2851
+ }
2852
+ return result;
2853
+ }
2854
+ var init_verify3 = __esm({
2855
+ "../../../node_modules/jose/dist/webapi/jws/compact/verify.js"() {
2856
+ init_verify2();
2857
+ init_errors();
2858
+ init_buffer_utils();
2859
+ }
2860
+ });
2861
+
2862
+ // ../../../node_modules/jose/dist/webapi/jws/general/verify.js
2863
+ async function generalVerify(jws, key, options) {
2864
+ if (!isObject(jws)) {
2865
+ throw new JWSInvalid("General JWS must be an object");
2866
+ }
2867
+ if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) {
2868
+ throw new JWSInvalid("JWS Signatures missing or incorrect type");
2869
+ }
2870
+ for (const signature of jws.signatures) {
2871
+ try {
2872
+ return await flattenedVerify({
2873
+ header: signature.header,
2874
+ payload: jws.payload,
2875
+ protected: signature.protected,
2876
+ signature: signature.signature
2877
+ }, key, options);
2878
+ } catch {
2879
+ }
2880
+ }
2881
+ throw new JWSSignatureVerificationFailed();
2882
+ }
2883
+ var init_verify4 = __esm({
2884
+ "../../../node_modules/jose/dist/webapi/jws/general/verify.js"() {
2885
+ init_verify2();
2886
+ init_errors();
2887
+ init_is_object();
2888
+ }
2889
+ });
2890
+
2891
+ // ../../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js
2892
+ function secs(str) {
2893
+ const matched = REGEX.exec(str);
2894
+ if (!matched || matched[4] && matched[1]) {
2895
+ throw new TypeError("Invalid time period format");
2896
+ }
2897
+ const value = parseFloat(matched[2]);
2898
+ const unit = matched[3].toLowerCase();
2899
+ let numericDate;
2900
+ switch (unit) {
2901
+ case "sec":
2902
+ case "secs":
2903
+ case "second":
2904
+ case "seconds":
2905
+ case "s":
2906
+ numericDate = Math.round(value);
2907
+ break;
2908
+ case "minute":
2909
+ case "minutes":
2910
+ case "min":
2911
+ case "mins":
2912
+ case "m":
2913
+ numericDate = Math.round(value * minute);
2914
+ break;
2915
+ case "hour":
2916
+ case "hours":
2917
+ case "hr":
2918
+ case "hrs":
2919
+ case "h":
2920
+ numericDate = Math.round(value * hour);
2921
+ break;
2922
+ case "day":
2923
+ case "days":
2924
+ case "d":
2925
+ numericDate = Math.round(value * day);
2926
+ break;
2927
+ case "week":
2928
+ case "weeks":
2929
+ case "w":
2930
+ numericDate = Math.round(value * week);
2931
+ break;
2932
+ default:
2933
+ numericDate = Math.round(value * year);
2934
+ break;
2935
+ }
2936
+ if (matched[1] === "-" || matched[4] === "ago") {
2937
+ return -numericDate;
2938
+ }
2939
+ return numericDate;
2940
+ }
2941
+ function validateInput(label, input) {
2942
+ if (!Number.isFinite(input)) {
2943
+ throw new TypeError(`Invalid ${label} input`);
2944
+ }
2945
+ return input;
2946
+ }
2947
+ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
2948
+ let payload;
2949
+ try {
2950
+ payload = JSON.parse(decoder.decode(encodedPayload));
2951
+ } catch {
2952
+ }
2953
+ if (!isObject(payload)) {
2954
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
2955
+ }
2956
+ const { typ } = options;
2957
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
2958
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
2959
+ }
2960
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
2961
+ const presenceCheck = [...requiredClaims];
2962
+ if (maxTokenAge !== void 0)
2963
+ presenceCheck.push("iat");
2964
+ if (audience !== void 0)
2965
+ presenceCheck.push("aud");
2966
+ if (subject !== void 0)
2967
+ presenceCheck.push("sub");
2968
+ if (issuer !== void 0)
2969
+ presenceCheck.push("iss");
2970
+ for (const claim of new Set(presenceCheck.reverse())) {
2971
+ if (!(claim in payload)) {
2972
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
2973
+ }
2974
+ }
2975
+ if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
2976
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
2977
+ }
2978
+ if (subject && payload.sub !== subject) {
2979
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
2980
+ }
2981
+ if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
2982
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
2983
+ }
2984
+ let tolerance;
2985
+ switch (typeof options.clockTolerance) {
2986
+ case "string":
2987
+ tolerance = secs(options.clockTolerance);
2988
+ break;
2989
+ case "number":
2990
+ tolerance = options.clockTolerance;
2991
+ break;
2992
+ case "undefined":
2993
+ tolerance = 0;
2994
+ break;
2995
+ default:
2996
+ throw new TypeError("Invalid clockTolerance option type");
2997
+ }
2998
+ const { currentDate } = options;
2999
+ const now = epoch(currentDate || /* @__PURE__ */ new Date());
3000
+ if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
3001
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
3002
+ }
3003
+ if (payload.nbf !== void 0) {
3004
+ if (typeof payload.nbf !== "number") {
3005
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
3006
+ }
3007
+ if (payload.nbf > now + tolerance) {
3008
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
3009
+ }
3010
+ }
3011
+ if (payload.exp !== void 0) {
3012
+ if (typeof payload.exp !== "number") {
3013
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
3014
+ }
3015
+ if (payload.exp <= now - tolerance) {
3016
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
3017
+ }
3018
+ }
3019
+ if (maxTokenAge) {
3020
+ const age = now - payload.iat;
3021
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
3022
+ if (age - tolerance > max) {
3023
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
3024
+ }
3025
+ if (age < 0 - tolerance) {
3026
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
3027
+ }
3028
+ }
3029
+ return payload;
3030
+ }
3031
+ var epoch, minute, hour, day, week, year, REGEX, normalizeTyp, checkAudiencePresence, JWTClaimsBuilder;
3032
+ var init_jwt_claims_set = __esm({
3033
+ "../../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js"() {
3034
+ init_errors();
3035
+ init_buffer_utils();
3036
+ init_is_object();
3037
+ epoch = (date) => Math.floor(date.getTime() / 1e3);
3038
+ minute = 60;
3039
+ hour = minute * 60;
3040
+ day = hour * 24;
3041
+ week = day * 7;
3042
+ year = day * 365.25;
3043
+ REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
3044
+ normalizeTyp = (value) => {
3045
+ if (value.includes("/")) {
3046
+ return value.toLowerCase();
3047
+ }
3048
+ return `application/${value.toLowerCase()}`;
3049
+ };
3050
+ checkAudiencePresence = (audPayload, audOption) => {
3051
+ if (typeof audPayload === "string") {
3052
+ return audOption.includes(audPayload);
3053
+ }
3054
+ if (Array.isArray(audPayload)) {
3055
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
3056
+ }
3057
+ return false;
3058
+ };
3059
+ JWTClaimsBuilder = class {
3060
+ #payload;
3061
+ constructor(payload) {
3062
+ if (!isObject(payload)) {
3063
+ throw new TypeError("JWT Claims Set MUST be an object");
3064
+ }
3065
+ this.#payload = structuredClone(payload);
3066
+ }
3067
+ data() {
3068
+ return encoder.encode(JSON.stringify(this.#payload));
3069
+ }
3070
+ get iss() {
3071
+ return this.#payload.iss;
3072
+ }
3073
+ set iss(value) {
3074
+ this.#payload.iss = value;
3075
+ }
3076
+ get sub() {
3077
+ return this.#payload.sub;
3078
+ }
3079
+ set sub(value) {
3080
+ this.#payload.sub = value;
3081
+ }
3082
+ get aud() {
3083
+ return this.#payload.aud;
3084
+ }
3085
+ set aud(value) {
3086
+ this.#payload.aud = value;
3087
+ }
3088
+ set jti(value) {
3089
+ this.#payload.jti = value;
3090
+ }
3091
+ set nbf(value) {
3092
+ if (typeof value === "number") {
3093
+ this.#payload.nbf = validateInput("setNotBefore", value);
3094
+ } else if (value instanceof Date) {
3095
+ this.#payload.nbf = validateInput("setNotBefore", epoch(value));
3096
+ } else {
3097
+ this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
3098
+ }
3099
+ }
3100
+ set exp(value) {
3101
+ if (typeof value === "number") {
3102
+ this.#payload.exp = validateInput("setExpirationTime", value);
3103
+ } else if (value instanceof Date) {
3104
+ this.#payload.exp = validateInput("setExpirationTime", epoch(value));
3105
+ } else {
3106
+ this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
3107
+ }
3108
+ }
3109
+ set iat(value) {
3110
+ if (value === void 0) {
3111
+ this.#payload.iat = epoch(/* @__PURE__ */ new Date());
3112
+ } else if (value instanceof Date) {
3113
+ this.#payload.iat = validateInput("setIssuedAt", epoch(value));
3114
+ } else if (typeof value === "string") {
3115
+ this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
3116
+ } else {
3117
+ this.#payload.iat = validateInput("setIssuedAt", value);
3118
+ }
3119
+ }
3120
+ };
3121
+ }
3122
+ });
3123
+
3124
+ // ../../../node_modules/jose/dist/webapi/jwt/verify.js
3125
+ async function jwtVerify(jwt, key, options) {
3126
+ const verified = await compactVerify(jwt, key, options);
3127
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
3128
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3129
+ }
3130
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
3131
+ const result = { payload, protectedHeader: verified.protectedHeader };
3132
+ if (typeof key === "function") {
3133
+ return { ...result, key: verified.key };
3134
+ }
3135
+ return result;
3136
+ }
3137
+ var init_verify5 = __esm({
3138
+ "../../../node_modules/jose/dist/webapi/jwt/verify.js"() {
3139
+ init_verify3();
3140
+ init_jwt_claims_set();
3141
+ init_errors();
3142
+ }
3143
+ });
3144
+
3145
+ // ../../../node_modules/jose/dist/webapi/jwt/decrypt.js
3146
+ async function jwtDecrypt(jwt, key, options) {
3147
+ const decrypted = await compactDecrypt(jwt, key, options);
3148
+ const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options);
3149
+ const { protectedHeader } = decrypted;
3150
+ if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) {
3151
+ throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch");
3152
+ }
3153
+ if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) {
3154
+ throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch");
3155
+ }
3156
+ if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
3157
+ throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch");
3158
+ }
3159
+ const result = { payload, protectedHeader };
3160
+ if (typeof key === "function") {
3161
+ return { ...result, key: decrypted.key };
3162
+ }
3163
+ return result;
3164
+ }
3165
+ var init_decrypt5 = __esm({
3166
+ "../../../node_modules/jose/dist/webapi/jwt/decrypt.js"() {
3167
+ init_decrypt3();
3168
+ init_jwt_claims_set();
3169
+ init_errors();
3170
+ }
3171
+ });
3172
+
3173
+ // ../../../node_modules/jose/dist/webapi/jwe/compact/encrypt.js
3174
+ var CompactEncrypt;
3175
+ var init_encrypt4 = __esm({
3176
+ "../../../node_modules/jose/dist/webapi/jwe/compact/encrypt.js"() {
3177
+ init_encrypt2();
3178
+ CompactEncrypt = class {
3179
+ #flattened;
3180
+ constructor(plaintext) {
3181
+ this.#flattened = new FlattenedEncrypt(plaintext);
3182
+ }
3183
+ setContentEncryptionKey(cek) {
3184
+ this.#flattened.setContentEncryptionKey(cek);
3185
+ return this;
3186
+ }
3187
+ setInitializationVector(iv) {
3188
+ this.#flattened.setInitializationVector(iv);
3189
+ return this;
3190
+ }
3191
+ setProtectedHeader(protectedHeader) {
3192
+ this.#flattened.setProtectedHeader(protectedHeader);
3193
+ return this;
3194
+ }
3195
+ setKeyManagementParameters(parameters) {
3196
+ this.#flattened.setKeyManagementParameters(parameters);
3197
+ return this;
3198
+ }
3199
+ async encrypt(key, options) {
3200
+ const jwe = await this.#flattened.encrypt(key, options);
3201
+ return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join(".");
3202
+ }
3203
+ };
3204
+ }
3205
+ });
3206
+
3207
+ // ../../../node_modules/jose/dist/webapi/lib/sign.js
3208
+ async function sign(alg, key, data) {
3209
+ const cryptoKey = await getSigKey(alg, key, "sign");
3210
+ checkKeyLength(alg, cryptoKey);
3211
+ const signature = await crypto.subtle.sign(subtleAlgorithm2(alg, cryptoKey.algorithm), cryptoKey, data);
3212
+ return new Uint8Array(signature);
3213
+ }
3214
+ var init_sign = __esm({
3215
+ "../../../node_modules/jose/dist/webapi/lib/sign.js"() {
3216
+ init_subtle_dsa();
3217
+ init_check_key_length();
3218
+ init_get_sign_verify_key();
3219
+ }
3220
+ });
3221
+
3222
+ // ../../../node_modules/jose/dist/webapi/jws/flattened/sign.js
3223
+ var FlattenedSign;
3224
+ var init_sign2 = __esm({
3225
+ "../../../node_modules/jose/dist/webapi/jws/flattened/sign.js"() {
3226
+ init_base64url();
3227
+ init_sign();
3228
+ init_is_disjoint();
3229
+ init_errors();
3230
+ init_buffer_utils();
3231
+ init_check_key_type();
3232
+ init_validate_crit();
3233
+ init_normalize_key();
3234
+ FlattenedSign = class {
3235
+ #payload;
3236
+ #protectedHeader;
3237
+ #unprotectedHeader;
3238
+ constructor(payload) {
3239
+ if (!(payload instanceof Uint8Array)) {
3240
+ throw new TypeError("payload must be an instance of Uint8Array");
3241
+ }
3242
+ this.#payload = payload;
3243
+ }
3244
+ setProtectedHeader(protectedHeader) {
3245
+ if (this.#protectedHeader) {
3246
+ throw new TypeError("setProtectedHeader can only be called once");
3247
+ }
3248
+ this.#protectedHeader = protectedHeader;
3249
+ return this;
3250
+ }
3251
+ setUnprotectedHeader(unprotectedHeader) {
3252
+ if (this.#unprotectedHeader) {
3253
+ throw new TypeError("setUnprotectedHeader can only be called once");
3254
+ }
3255
+ this.#unprotectedHeader = unprotectedHeader;
3256
+ return this;
3257
+ }
3258
+ async sign(key, options) {
3259
+ if (!this.#protectedHeader && !this.#unprotectedHeader) {
3260
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
3261
+ }
3262
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {
3263
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
3264
+ }
3265
+ const joseHeader = {
3266
+ ...this.#protectedHeader,
3267
+ ...this.#unprotectedHeader
3268
+ };
3269
+ const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
3270
+ let b64 = true;
3271
+ if (extensions.has("b64")) {
3272
+ b64 = this.#protectedHeader.b64;
3273
+ if (typeof b64 !== "boolean") {
3274
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
3275
+ }
3276
+ }
3277
+ const { alg } = joseHeader;
3278
+ if (typeof alg !== "string" || !alg) {
3279
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
3280
+ }
3281
+ checkKeyType(alg, key, "sign");
3282
+ let payloadS;
3283
+ let payloadB;
3284
+ if (b64) {
3285
+ payloadS = encode2(this.#payload);
3286
+ payloadB = encode(payloadS);
3287
+ } else {
3288
+ payloadB = this.#payload;
3289
+ payloadS = "";
3290
+ }
3291
+ let protectedHeaderString;
3292
+ let protectedHeaderBytes;
3293
+ if (this.#protectedHeader) {
3294
+ protectedHeaderString = encode2(JSON.stringify(this.#protectedHeader));
3295
+ protectedHeaderBytes = encode(protectedHeaderString);
3296
+ } else {
3297
+ protectedHeaderString = "";
3298
+ protectedHeaderBytes = new Uint8Array();
3299
+ }
3300
+ const data = concat(protectedHeaderBytes, encode("."), payloadB);
3301
+ const k = await normalizeKey(key, alg);
3302
+ const signature = await sign(alg, k, data);
3303
+ const jws = {
3304
+ signature: encode2(signature),
3305
+ payload: payloadS
3306
+ };
3307
+ if (this.#unprotectedHeader) {
3308
+ jws.header = this.#unprotectedHeader;
3309
+ }
3310
+ if (this.#protectedHeader) {
3311
+ jws.protected = protectedHeaderString;
3312
+ }
3313
+ return jws;
3314
+ }
3315
+ };
3316
+ }
3317
+ });
3318
+
3319
+ // ../../../node_modules/jose/dist/webapi/jws/compact/sign.js
3320
+ var CompactSign;
3321
+ var init_sign3 = __esm({
3322
+ "../../../node_modules/jose/dist/webapi/jws/compact/sign.js"() {
3323
+ init_sign2();
3324
+ CompactSign = class {
3325
+ #flattened;
3326
+ constructor(payload) {
3327
+ this.#flattened = new FlattenedSign(payload);
3328
+ }
3329
+ setProtectedHeader(protectedHeader) {
3330
+ this.#flattened.setProtectedHeader(protectedHeader);
3331
+ return this;
3332
+ }
3333
+ async sign(key, options) {
3334
+ const jws = await this.#flattened.sign(key, options);
3335
+ if (jws.payload === void 0) {
3336
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
3337
+ }
3338
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
3339
+ }
3340
+ };
3341
+ }
3342
+ });
3343
+
3344
+ // ../../../node_modules/jose/dist/webapi/jws/general/sign.js
3345
+ var IndividualSignature, GeneralSign;
3346
+ var init_sign4 = __esm({
3347
+ "../../../node_modules/jose/dist/webapi/jws/general/sign.js"() {
3348
+ init_sign2();
3349
+ init_errors();
3350
+ IndividualSignature = class {
3351
+ #parent;
3352
+ protectedHeader;
3353
+ unprotectedHeader;
3354
+ options;
3355
+ key;
3356
+ constructor(sig, key, options) {
3357
+ this.#parent = sig;
3358
+ this.key = key;
3359
+ this.options = options;
3360
+ }
3361
+ setProtectedHeader(protectedHeader) {
3362
+ if (this.protectedHeader) {
3363
+ throw new TypeError("setProtectedHeader can only be called once");
3364
+ }
3365
+ this.protectedHeader = protectedHeader;
3366
+ return this;
3367
+ }
3368
+ setUnprotectedHeader(unprotectedHeader) {
3369
+ if (this.unprotectedHeader) {
3370
+ throw new TypeError("setUnprotectedHeader can only be called once");
3371
+ }
3372
+ this.unprotectedHeader = unprotectedHeader;
3373
+ return this;
3374
+ }
3375
+ addSignature(...args) {
3376
+ return this.#parent.addSignature(...args);
3377
+ }
3378
+ sign(...args) {
3379
+ return this.#parent.sign(...args);
3380
+ }
3381
+ done() {
3382
+ return this.#parent;
3383
+ }
3384
+ };
3385
+ GeneralSign = class {
3386
+ #payload;
3387
+ #signatures = [];
3388
+ constructor(payload) {
3389
+ this.#payload = payload;
3390
+ }
3391
+ addSignature(key, options) {
3392
+ const signature = new IndividualSignature(this, key, options);
3393
+ this.#signatures.push(signature);
3394
+ return signature;
3395
+ }
3396
+ async sign() {
3397
+ if (!this.#signatures.length) {
3398
+ throw new JWSInvalid("at least one signature must be added");
3399
+ }
3400
+ const jws = {
3401
+ signatures: [],
3402
+ payload: ""
3403
+ };
3404
+ for (let i = 0; i < this.#signatures.length; i++) {
3405
+ const signature = this.#signatures[i];
3406
+ const flattened = new FlattenedSign(this.#payload);
3407
+ flattened.setProtectedHeader(signature.protectedHeader);
3408
+ flattened.setUnprotectedHeader(signature.unprotectedHeader);
3409
+ const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
3410
+ if (i === 0) {
3411
+ jws.payload = payload;
3412
+ } else if (jws.payload !== payload) {
3413
+ throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");
3414
+ }
3415
+ jws.signatures.push(rest);
3416
+ }
3417
+ return jws;
3418
+ }
3419
+ };
3420
+ }
3421
+ });
3422
+
3423
+ // ../../../node_modules/jose/dist/webapi/jwt/sign.js
3424
+ var SignJWT;
3425
+ var init_sign5 = __esm({
3426
+ "../../../node_modules/jose/dist/webapi/jwt/sign.js"() {
3427
+ init_sign3();
3428
+ init_errors();
3429
+ init_jwt_claims_set();
3430
+ SignJWT = class {
3431
+ #protectedHeader;
3432
+ #jwt;
3433
+ constructor(payload = {}) {
3434
+ this.#jwt = new JWTClaimsBuilder(payload);
3435
+ }
3436
+ setIssuer(issuer) {
3437
+ this.#jwt.iss = issuer;
3438
+ return this;
3439
+ }
3440
+ setSubject(subject) {
3441
+ this.#jwt.sub = subject;
3442
+ return this;
3443
+ }
3444
+ setAudience(audience) {
3445
+ this.#jwt.aud = audience;
3446
+ return this;
3447
+ }
3448
+ setJti(jwtId) {
3449
+ this.#jwt.jti = jwtId;
3450
+ return this;
3451
+ }
3452
+ setNotBefore(input) {
3453
+ this.#jwt.nbf = input;
3454
+ return this;
3455
+ }
3456
+ setExpirationTime(input) {
3457
+ this.#jwt.exp = input;
3458
+ return this;
3459
+ }
3460
+ setIssuedAt(input) {
3461
+ this.#jwt.iat = input;
3462
+ return this;
3463
+ }
3464
+ setProtectedHeader(protectedHeader) {
3465
+ this.#protectedHeader = protectedHeader;
3466
+ return this;
3467
+ }
3468
+ async sign(key, options) {
3469
+ const sig = new CompactSign(this.#jwt.data());
3470
+ sig.setProtectedHeader(this.#protectedHeader);
3471
+ if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) {
3472
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3473
+ }
3474
+ return sig.sign(key, options);
3475
+ }
3476
+ };
3477
+ }
3478
+ });
3479
+
3480
+ // ../../../node_modules/jose/dist/webapi/jwt/encrypt.js
3481
+ var EncryptJWT;
3482
+ var init_encrypt5 = __esm({
3483
+ "../../../node_modules/jose/dist/webapi/jwt/encrypt.js"() {
3484
+ init_encrypt4();
3485
+ init_jwt_claims_set();
3486
+ EncryptJWT = class {
3487
+ #cek;
3488
+ #iv;
3489
+ #keyManagementParameters;
3490
+ #protectedHeader;
3491
+ #replicateIssuerAsHeader;
3492
+ #replicateSubjectAsHeader;
3493
+ #replicateAudienceAsHeader;
3494
+ #jwt;
3495
+ constructor(payload = {}) {
3496
+ this.#jwt = new JWTClaimsBuilder(payload);
3497
+ }
3498
+ setIssuer(issuer) {
3499
+ this.#jwt.iss = issuer;
3500
+ return this;
3501
+ }
3502
+ setSubject(subject) {
3503
+ this.#jwt.sub = subject;
3504
+ return this;
3505
+ }
3506
+ setAudience(audience) {
3507
+ this.#jwt.aud = audience;
3508
+ return this;
3509
+ }
3510
+ setJti(jwtId) {
3511
+ this.#jwt.jti = jwtId;
3512
+ return this;
3513
+ }
3514
+ setNotBefore(input) {
3515
+ this.#jwt.nbf = input;
3516
+ return this;
3517
+ }
3518
+ setExpirationTime(input) {
3519
+ this.#jwt.exp = input;
3520
+ return this;
3521
+ }
3522
+ setIssuedAt(input) {
3523
+ this.#jwt.iat = input;
3524
+ return this;
3525
+ }
3526
+ setProtectedHeader(protectedHeader) {
3527
+ if (this.#protectedHeader) {
3528
+ throw new TypeError("setProtectedHeader can only be called once");
3529
+ }
3530
+ this.#protectedHeader = protectedHeader;
3531
+ return this;
3532
+ }
3533
+ setKeyManagementParameters(parameters) {
3534
+ if (this.#keyManagementParameters) {
3535
+ throw new TypeError("setKeyManagementParameters can only be called once");
3536
+ }
3537
+ this.#keyManagementParameters = parameters;
3538
+ return this;
3539
+ }
3540
+ setContentEncryptionKey(cek) {
3541
+ if (this.#cek) {
3542
+ throw new TypeError("setContentEncryptionKey can only be called once");
3543
+ }
3544
+ this.#cek = cek;
3545
+ return this;
3546
+ }
3547
+ setInitializationVector(iv) {
3548
+ if (this.#iv) {
3549
+ throw new TypeError("setInitializationVector can only be called once");
3550
+ }
3551
+ this.#iv = iv;
3552
+ return this;
3553
+ }
3554
+ replicateIssuerAsHeader() {
3555
+ this.#replicateIssuerAsHeader = true;
3556
+ return this;
3557
+ }
3558
+ replicateSubjectAsHeader() {
3559
+ this.#replicateSubjectAsHeader = true;
3560
+ return this;
3561
+ }
3562
+ replicateAudienceAsHeader() {
3563
+ this.#replicateAudienceAsHeader = true;
3564
+ return this;
3565
+ }
3566
+ async encrypt(key, options) {
3567
+ const enc = new CompactEncrypt(this.#jwt.data());
3568
+ if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) {
3569
+ this.#protectedHeader = {
3570
+ ...this.#protectedHeader,
3571
+ iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : void 0,
3572
+ sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : void 0,
3573
+ aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : void 0
3574
+ };
3575
+ }
3576
+ enc.setProtectedHeader(this.#protectedHeader);
3577
+ if (this.#iv) {
3578
+ enc.setInitializationVector(this.#iv);
3579
+ }
3580
+ if (this.#cek) {
3581
+ enc.setContentEncryptionKey(this.#cek);
3582
+ }
3583
+ if (this.#keyManagementParameters) {
3584
+ enc.setKeyManagementParameters(this.#keyManagementParameters);
3585
+ }
3586
+ return enc.encrypt(key, options);
3587
+ }
3588
+ };
3589
+ }
3590
+ });
3591
+
3592
+ // ../../../node_modules/jose/dist/webapi/jwk/thumbprint.js
3593
+ async function calculateJwkThumbprint(key, digestAlgorithm) {
3594
+ let jwk;
3595
+ if (isJWK(key)) {
3596
+ jwk = key;
3597
+ } else if (isKeyLike(key)) {
3598
+ jwk = await exportJWK(key);
3599
+ } else {
3600
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
3601
+ }
3602
+ digestAlgorithm ??= "sha256";
3603
+ if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") {
3604
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
3605
+ }
3606
+ let components;
3607
+ switch (jwk.kty) {
3608
+ case "AKP":
3609
+ check(jwk.alg, '"alg" (Algorithm) Parameter');
3610
+ check(jwk.pub, '"pub" (Public key) Parameter');
3611
+ components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
3612
+ break;
3613
+ case "EC":
3614
+ check(jwk.crv, '"crv" (Curve) Parameter');
3615
+ check(jwk.x, '"x" (X Coordinate) Parameter');
3616
+ check(jwk.y, '"y" (Y Coordinate) Parameter');
3617
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
3618
+ break;
3619
+ case "OKP":
3620
+ check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
3621
+ check(jwk.x, '"x" (Public Key) Parameter');
3622
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
3623
+ break;
3624
+ case "RSA":
3625
+ check(jwk.e, '"e" (Exponent) Parameter');
3626
+ check(jwk.n, '"n" (Modulus) Parameter');
3627
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
3628
+ break;
3629
+ case "oct":
3630
+ check(jwk.k, '"k" (Key Value) Parameter');
3631
+ components = { k: jwk.k, kty: jwk.kty };
3632
+ break;
3633
+ default:
3634
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
3635
+ }
3636
+ const data = encode(JSON.stringify(components));
3637
+ return encode2(await digest(digestAlgorithm, data));
3638
+ }
3639
+ async function calculateJwkThumbprintUri(key, digestAlgorithm) {
3640
+ digestAlgorithm ??= "sha256";
3641
+ const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);
3642
+ return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
3643
+ }
3644
+ var check;
3645
+ var init_thumbprint = __esm({
3646
+ "../../../node_modules/jose/dist/webapi/jwk/thumbprint.js"() {
3647
+ init_digest();
3648
+ init_base64url();
3649
+ init_errors();
3650
+ init_buffer_utils();
3651
+ init_is_key_like();
3652
+ init_is_jwk();
3653
+ init_export();
3654
+ init_invalid_key_input();
3655
+ check = (value, description) => {
3656
+ if (typeof value !== "string" || !value) {
3657
+ throw new JWKInvalid(`${description} missing or invalid`);
3658
+ }
3659
+ };
3660
+ }
3661
+ });
3662
+
3663
+ // ../../../node_modules/jose/dist/webapi/jwk/embedded.js
3664
+ async function EmbeddedJWK(protectedHeader, token) {
3665
+ const joseHeader = {
3666
+ ...protectedHeader,
3667
+ ...token?.header
3668
+ };
3669
+ if (!isObject(joseHeader.jwk)) {
3670
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
3671
+ }
3672
+ const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
3673
+ if (key instanceof Uint8Array || key.type !== "public") {
3674
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
3675
+ }
3676
+ return key;
3677
+ }
3678
+ var init_embedded = __esm({
3679
+ "../../../node_modules/jose/dist/webapi/jwk/embedded.js"() {
3680
+ init_import();
3681
+ init_is_object();
3682
+ init_errors();
3683
+ }
3684
+ });
3685
+
3686
+ // ../../../node_modules/jose/dist/webapi/jwks/local.js
3687
+ function getKtyFromAlg(alg) {
3688
+ switch (typeof alg === "string" && alg.slice(0, 2)) {
3689
+ case "RS":
3690
+ case "PS":
3691
+ return "RSA";
3692
+ case "ES":
3693
+ return "EC";
3694
+ case "Ed":
3695
+ return "OKP";
3696
+ case "ML":
3697
+ return "AKP";
3698
+ default:
3699
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
3700
+ }
3701
+ }
3702
+ function isJWKSLike(jwks) {
3703
+ return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
3704
+ }
3705
+ function isJWKLike(key) {
3706
+ return isObject(key);
3707
+ }
3708
+ async function importWithAlgCache(cache2, jwk, alg) {
3709
+ const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk);
3710
+ if (cached[alg] === void 0) {
3711
+ const key = await importJWK({ ...jwk, ext: true }, alg);
3712
+ if (key instanceof Uint8Array || key.type !== "public") {
3713
+ throw new JWKSInvalid("JSON Web Key Set members must be public keys");
3714
+ }
3715
+ cached[alg] = key;
3716
+ }
3717
+ return cached[alg];
3718
+ }
3719
+ function createLocalJWKSet(jwks) {
3720
+ const set = new LocalJWKSet(jwks);
3721
+ const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
3722
+ Object.defineProperties(localJWKSet, {
3723
+ jwks: {
3724
+ value: () => structuredClone(set.jwks()),
3725
+ enumerable: false,
3726
+ configurable: false,
3727
+ writable: false
3728
+ }
3729
+ });
3730
+ return localJWKSet;
3731
+ }
3732
+ var LocalJWKSet;
3733
+ var init_local = __esm({
3734
+ "../../../node_modules/jose/dist/webapi/jwks/local.js"() {
3735
+ init_import();
3736
+ init_errors();
3737
+ init_is_object();
3738
+ LocalJWKSet = class {
3739
+ #jwks;
3740
+ #cached = /* @__PURE__ */ new WeakMap();
3741
+ constructor(jwks) {
3742
+ if (!isJWKSLike(jwks)) {
3743
+ throw new JWKSInvalid("JSON Web Key Set malformed");
3744
+ }
3745
+ this.#jwks = structuredClone(jwks);
3746
+ }
3747
+ jwks() {
3748
+ return this.#jwks;
3749
+ }
3750
+ async getKey(protectedHeader, token) {
3751
+ const { alg, kid } = { ...protectedHeader, ...token?.header };
3752
+ const kty = getKtyFromAlg(alg);
3753
+ const candidates = this.#jwks.keys.filter((jwk2) => {
3754
+ let candidate = kty === jwk2.kty;
3755
+ if (candidate && typeof kid === "string") {
3756
+ candidate = kid === jwk2.kid;
3757
+ }
3758
+ if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) {
3759
+ candidate = alg === jwk2.alg;
3760
+ }
3761
+ if (candidate && typeof jwk2.use === "string") {
3762
+ candidate = jwk2.use === "sig";
3763
+ }
3764
+ if (candidate && Array.isArray(jwk2.key_ops)) {
3765
+ candidate = jwk2.key_ops.includes("verify");
3766
+ }
3767
+ if (candidate) {
3768
+ switch (alg) {
3769
+ case "ES256":
3770
+ candidate = jwk2.crv === "P-256";
3771
+ break;
3772
+ case "ES384":
3773
+ candidate = jwk2.crv === "P-384";
3774
+ break;
3775
+ case "ES512":
3776
+ candidate = jwk2.crv === "P-521";
3777
+ break;
3778
+ case "Ed25519":
3779
+ case "EdDSA":
3780
+ candidate = jwk2.crv === "Ed25519";
3781
+ break;
3782
+ }
3783
+ }
3784
+ return candidate;
3785
+ });
3786
+ const { 0: jwk, length } = candidates;
3787
+ if (length === 0) {
3788
+ throw new JWKSNoMatchingKey();
3789
+ }
3790
+ if (length !== 1) {
3791
+ const error = new JWKSMultipleMatchingKeys();
3792
+ const _cached = this.#cached;
3793
+ error[Symbol.asyncIterator] = async function* () {
3794
+ for (const jwk2 of candidates) {
3795
+ try {
3796
+ yield await importWithAlgCache(_cached, jwk2, alg);
3797
+ } catch {
3798
+ }
3799
+ }
3800
+ };
3801
+ throw error;
3802
+ }
3803
+ return importWithAlgCache(this.#cached, jwk, alg);
3804
+ }
3805
+ };
3806
+ }
3807
+ });
3808
+
3809
+ // ../../../node_modules/jose/dist/webapi/jwks/remote.js
3810
+ function isCloudflareWorkers() {
3811
+ return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
3812
+ }
3813
+ async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
3814
+ const response = await fetchImpl(url, {
3815
+ method: "GET",
3816
+ signal,
3817
+ redirect: "manual",
3818
+ headers
3819
+ }).catch((err) => {
3820
+ if (err.name === "TimeoutError") {
3821
+ throw new JWKSTimeout();
3822
+ }
3823
+ throw err;
3824
+ });
3825
+ if (response.status !== 200) {
3826
+ throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
3827
+ }
3828
+ try {
3829
+ return await response.json();
3830
+ } catch {
3831
+ throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
3832
+ }
3833
+ }
3834
+ function isFreshJwksCache(input, cacheMaxAge) {
3835
+ if (typeof input !== "object" || input === null) {
3836
+ return false;
3837
+ }
3838
+ if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) {
3839
+ return false;
3840
+ }
3841
+ if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) {
3842
+ return false;
3843
+ }
3844
+ return true;
3845
+ }
3846
+ function createRemoteJWKSet(url, options) {
3847
+ const set = new RemoteJWKSet(url, options);
3848
+ const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
3849
+ Object.defineProperties(remoteJWKSet, {
3850
+ coolingDown: {
3851
+ get: () => set.coolingDown(),
3852
+ enumerable: true,
3853
+ configurable: false
3854
+ },
3855
+ fresh: {
3856
+ get: () => set.fresh(),
3857
+ enumerable: true,
3858
+ configurable: false
3859
+ },
3860
+ reload: {
3861
+ value: () => set.reload(),
3862
+ enumerable: true,
3863
+ configurable: false,
3864
+ writable: false
3865
+ },
3866
+ reloading: {
3867
+ get: () => set.pendingFetch(),
3868
+ enumerable: true,
3869
+ configurable: false
3870
+ },
3871
+ jwks: {
3872
+ value: () => set.jwks(),
3873
+ enumerable: true,
3874
+ configurable: false,
3875
+ writable: false
3876
+ }
3877
+ });
3878
+ return remoteJWKSet;
3879
+ }
3880
+ var USER_AGENT, customFetch, jwksCache, RemoteJWKSet;
3881
+ var init_remote = __esm({
3882
+ "../../../node_modules/jose/dist/webapi/jwks/remote.js"() {
3883
+ init_errors();
3884
+ init_local();
3885
+ init_is_object();
3886
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
3887
+ const NAME = "jose";
3888
+ const VERSION = "v6.1.3";
3889
+ USER_AGENT = `${NAME}/${VERSION}`;
3890
+ }
3891
+ customFetch = /* @__PURE__ */ Symbol();
3892
+ jwksCache = /* @__PURE__ */ Symbol();
3893
+ RemoteJWKSet = class {
3894
+ #url;
3895
+ #timeoutDuration;
3896
+ #cooldownDuration;
3897
+ #cacheMaxAge;
3898
+ #jwksTimestamp;
3899
+ #pendingFetch;
3900
+ #headers;
3901
+ #customFetch;
3902
+ #local;
3903
+ #cache;
3904
+ constructor(url, options) {
3905
+ if (!(url instanceof URL)) {
3906
+ throw new TypeError("url must be an instance of URL");
3907
+ }
3908
+ this.#url = new URL(url.href);
3909
+ this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
3910
+ this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
3911
+ this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
3912
+ this.#headers = new Headers(options?.headers);
3913
+ if (USER_AGENT && !this.#headers.has("User-Agent")) {
3914
+ this.#headers.set("User-Agent", USER_AGENT);
3915
+ }
3916
+ if (!this.#headers.has("accept")) {
3917
+ this.#headers.set("accept", "application/json");
3918
+ this.#headers.append("accept", "application/jwk-set+json");
3919
+ }
3920
+ this.#customFetch = options?.[customFetch];
3921
+ if (options?.[jwksCache] !== void 0) {
3922
+ this.#cache = options?.[jwksCache];
3923
+ if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
3924
+ this.#jwksTimestamp = this.#cache.uat;
3925
+ this.#local = createLocalJWKSet(this.#cache.jwks);
3926
+ }
3927
+ }
3928
+ }
3929
+ pendingFetch() {
3930
+ return !!this.#pendingFetch;
3931
+ }
3932
+ coolingDown() {
3933
+ return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false;
3934
+ }
3935
+ fresh() {
3936
+ return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false;
3937
+ }
3938
+ jwks() {
3939
+ return this.#local?.jwks();
3940
+ }
3941
+ async getKey(protectedHeader, token) {
3942
+ if (!this.#local || !this.fresh()) {
3943
+ await this.reload();
3944
+ }
3945
+ try {
3946
+ return await this.#local(protectedHeader, token);
3947
+ } catch (err) {
3948
+ if (err instanceof JWKSNoMatchingKey) {
3949
+ if (this.coolingDown() === false) {
3950
+ await this.reload();
3951
+ return this.#local(protectedHeader, token);
3952
+ }
3953
+ }
3954
+ throw err;
3955
+ }
3956
+ }
3957
+ async reload() {
3958
+ if (this.#pendingFetch && isCloudflareWorkers()) {
3959
+ this.#pendingFetch = void 0;
3960
+ }
3961
+ this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => {
3962
+ this.#local = createLocalJWKSet(json);
3963
+ if (this.#cache) {
3964
+ this.#cache.uat = Date.now();
3965
+ this.#cache.jwks = json;
3966
+ }
3967
+ this.#jwksTimestamp = Date.now();
3968
+ this.#pendingFetch = void 0;
3969
+ }).catch((err) => {
3970
+ this.#pendingFetch = void 0;
3971
+ throw err;
3972
+ });
3973
+ await this.#pendingFetch;
3974
+ }
3975
+ };
3976
+ }
3977
+ });
3978
+
3979
+ // ../../../node_modules/jose/dist/webapi/jwt/unsecured.js
3980
+ var UnsecuredJWT;
3981
+ var init_unsecured = __esm({
3982
+ "../../../node_modules/jose/dist/webapi/jwt/unsecured.js"() {
3983
+ init_base64url();
3984
+ init_buffer_utils();
3985
+ init_errors();
3986
+ init_jwt_claims_set();
3987
+ UnsecuredJWT = class {
3988
+ #jwt;
3989
+ constructor(payload = {}) {
3990
+ this.#jwt = new JWTClaimsBuilder(payload);
3991
+ }
3992
+ encode() {
3993
+ const header = encode2(JSON.stringify({ alg: "none" }));
3994
+ const payload = encode2(this.#jwt.data());
3995
+ return `${header}.${payload}.`;
3996
+ }
3997
+ setIssuer(issuer) {
3998
+ this.#jwt.iss = issuer;
3999
+ return this;
4000
+ }
4001
+ setSubject(subject) {
4002
+ this.#jwt.sub = subject;
4003
+ return this;
4004
+ }
4005
+ setAudience(audience) {
4006
+ this.#jwt.aud = audience;
4007
+ return this;
4008
+ }
4009
+ setJti(jwtId) {
4010
+ this.#jwt.jti = jwtId;
4011
+ return this;
4012
+ }
4013
+ setNotBefore(input) {
4014
+ this.#jwt.nbf = input;
4015
+ return this;
4016
+ }
4017
+ setExpirationTime(input) {
4018
+ this.#jwt.exp = input;
4019
+ return this;
4020
+ }
4021
+ setIssuedAt(input) {
4022
+ this.#jwt.iat = input;
4023
+ return this;
4024
+ }
4025
+ static decode(jwt, options) {
4026
+ if (typeof jwt !== "string") {
4027
+ throw new JWTInvalid("Unsecured JWT must be a string");
4028
+ }
4029
+ const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split(".");
4030
+ if (length !== 3 || signature !== "") {
4031
+ throw new JWTInvalid("Invalid Unsecured JWT");
4032
+ }
4033
+ let header;
4034
+ try {
4035
+ header = JSON.parse(decoder.decode(decode(encodedHeader)));
4036
+ if (header.alg !== "none")
4037
+ throw new Error();
4038
+ } catch {
4039
+ throw new JWTInvalid("Invalid Unsecured JWT");
4040
+ }
4041
+ const payload = validateClaimsSet(header, decode(encodedPayload), options);
4042
+ return { payload, header };
4043
+ }
4044
+ };
4045
+ }
4046
+ });
4047
+
4048
+ // ../../../node_modules/jose/dist/webapi/util/decode_protected_header.js
4049
+ function decodeProtectedHeader(token) {
4050
+ let protectedB64u;
4051
+ if (typeof token === "string") {
4052
+ const parts = token.split(".");
4053
+ if (parts.length === 3 || parts.length === 5) {
4054
+ [protectedB64u] = parts;
4055
+ }
4056
+ } else if (typeof token === "object" && token) {
4057
+ if ("protected" in token) {
4058
+ protectedB64u = token.protected;
4059
+ } else {
4060
+ throw new TypeError("Token does not contain a Protected Header");
4061
+ }
4062
+ }
4063
+ try {
4064
+ if (typeof protectedB64u !== "string" || !protectedB64u) {
4065
+ throw new Error();
4066
+ }
4067
+ const result = JSON.parse(decoder.decode(decode(protectedB64u)));
4068
+ if (!isObject(result)) {
4069
+ throw new Error();
4070
+ }
4071
+ return result;
4072
+ } catch {
4073
+ throw new TypeError("Invalid Token or Protected Header formatting");
4074
+ }
4075
+ }
4076
+ var init_decode_protected_header = __esm({
4077
+ "../../../node_modules/jose/dist/webapi/util/decode_protected_header.js"() {
4078
+ init_base64url();
4079
+ init_buffer_utils();
4080
+ init_is_object();
4081
+ }
4082
+ });
4083
+
4084
+ // ../../../node_modules/jose/dist/webapi/util/decode_jwt.js
4085
+ function decodeJwt(jwt) {
4086
+ if (typeof jwt !== "string")
4087
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
4088
+ const { 1: payload, length } = jwt.split(".");
4089
+ if (length === 5)
4090
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
4091
+ if (length !== 3)
4092
+ throw new JWTInvalid("Invalid JWT");
4093
+ if (!payload)
4094
+ throw new JWTInvalid("JWTs must contain a payload");
4095
+ let decoded;
4096
+ try {
4097
+ decoded = decode(payload);
4098
+ } catch {
4099
+ throw new JWTInvalid("Failed to base64url decode the payload");
4100
+ }
4101
+ let result;
4102
+ try {
4103
+ result = JSON.parse(decoder.decode(decoded));
4104
+ } catch {
4105
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
4106
+ }
4107
+ if (!isObject(result))
4108
+ throw new JWTInvalid("Invalid JWT Claims Set");
4109
+ return result;
4110
+ }
4111
+ var init_decode_jwt = __esm({
4112
+ "../../../node_modules/jose/dist/webapi/util/decode_jwt.js"() {
4113
+ init_base64url();
4114
+ init_buffer_utils();
4115
+ init_is_object();
4116
+ init_errors();
4117
+ }
4118
+ });
4119
+
4120
+ // ../../../node_modules/jose/dist/webapi/key/generate_key_pair.js
4121
+ function getModulusLengthOption(options) {
4122
+ const modulusLength = options?.modulusLength ?? 2048;
4123
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
4124
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
4125
+ }
4126
+ return modulusLength;
4127
+ }
4128
+ async function generateKeyPair(alg, options) {
4129
+ let algorithm;
4130
+ let keyUsages;
4131
+ switch (alg) {
4132
+ case "PS256":
4133
+ case "PS384":
4134
+ case "PS512":
4135
+ algorithm = {
4136
+ name: "RSA-PSS",
4137
+ hash: `SHA-${alg.slice(-3)}`,
4138
+ publicExponent: Uint8Array.of(1, 0, 1),
4139
+ modulusLength: getModulusLengthOption(options)
4140
+ };
4141
+ keyUsages = ["sign", "verify"];
4142
+ break;
4143
+ case "RS256":
4144
+ case "RS384":
4145
+ case "RS512":
4146
+ algorithm = {
4147
+ name: "RSASSA-PKCS1-v1_5",
4148
+ hash: `SHA-${alg.slice(-3)}`,
4149
+ publicExponent: Uint8Array.of(1, 0, 1),
4150
+ modulusLength: getModulusLengthOption(options)
4151
+ };
4152
+ keyUsages = ["sign", "verify"];
4153
+ break;
4154
+ case "RSA-OAEP":
4155
+ case "RSA-OAEP-256":
4156
+ case "RSA-OAEP-384":
4157
+ case "RSA-OAEP-512":
4158
+ algorithm = {
4159
+ name: "RSA-OAEP",
4160
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
4161
+ publicExponent: Uint8Array.of(1, 0, 1),
4162
+ modulusLength: getModulusLengthOption(options)
4163
+ };
4164
+ keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"];
4165
+ break;
4166
+ case "ES256":
4167
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
4168
+ keyUsages = ["sign", "verify"];
4169
+ break;
4170
+ case "ES384":
4171
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
4172
+ keyUsages = ["sign", "verify"];
4173
+ break;
4174
+ case "ES512":
4175
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
4176
+ keyUsages = ["sign", "verify"];
4177
+ break;
4178
+ case "Ed25519":
4179
+ case "EdDSA": {
4180
+ keyUsages = ["sign", "verify"];
4181
+ algorithm = { name: "Ed25519" };
4182
+ break;
4183
+ }
4184
+ case "ML-DSA-44":
4185
+ case "ML-DSA-65":
4186
+ case "ML-DSA-87": {
4187
+ keyUsages = ["sign", "verify"];
4188
+ algorithm = { name: alg };
4189
+ break;
4190
+ }
4191
+ case "ECDH-ES":
4192
+ case "ECDH-ES+A128KW":
4193
+ case "ECDH-ES+A192KW":
4194
+ case "ECDH-ES+A256KW": {
4195
+ keyUsages = ["deriveBits"];
4196
+ const crv = options?.crv ?? "P-256";
4197
+ switch (crv) {
4198
+ case "P-256":
4199
+ case "P-384":
4200
+ case "P-521": {
4201
+ algorithm = { name: "ECDH", namedCurve: crv };
4202
+ break;
4203
+ }
4204
+ case "X25519":
4205
+ algorithm = { name: "X25519" };
4206
+ break;
4207
+ default:
4208
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
4209
+ }
4210
+ break;
4211
+ }
4212
+ default:
4213
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
4214
+ }
4215
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
4216
+ }
4217
+ var init_generate_key_pair = __esm({
4218
+ "../../../node_modules/jose/dist/webapi/key/generate_key_pair.js"() {
4219
+ init_errors();
4220
+ }
4221
+ });
4222
+
4223
+ // ../../../node_modules/jose/dist/webapi/key/generate_secret.js
4224
+ async function generateSecret(alg, options) {
4225
+ let length;
4226
+ let algorithm;
4227
+ let keyUsages;
4228
+ switch (alg) {
4229
+ case "HS256":
4230
+ case "HS384":
4231
+ case "HS512":
4232
+ length = parseInt(alg.slice(-3), 10);
4233
+ algorithm = { name: "HMAC", hash: `SHA-${length}`, length };
4234
+ keyUsages = ["sign", "verify"];
4235
+ break;
4236
+ case "A128CBC-HS256":
4237
+ case "A192CBC-HS384":
4238
+ case "A256CBC-HS512":
4239
+ length = parseInt(alg.slice(-3), 10);
4240
+ return crypto.getRandomValues(new Uint8Array(length >> 3));
4241
+ case "A128KW":
4242
+ case "A192KW":
4243
+ case "A256KW":
4244
+ length = parseInt(alg.slice(1, 4), 10);
4245
+ algorithm = { name: "AES-KW", length };
4246
+ keyUsages = ["wrapKey", "unwrapKey"];
4247
+ break;
4248
+ case "A128GCMKW":
4249
+ case "A192GCMKW":
4250
+ case "A256GCMKW":
4251
+ case "A128GCM":
4252
+ case "A192GCM":
4253
+ case "A256GCM":
4254
+ length = parseInt(alg.slice(1, 4), 10);
4255
+ algorithm = { name: "AES-GCM", length };
4256
+ keyUsages = ["encrypt", "decrypt"];
4257
+ break;
4258
+ default:
4259
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
4260
+ }
4261
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
4262
+ }
4263
+ var init_generate_secret = __esm({
4264
+ "../../../node_modules/jose/dist/webapi/key/generate_secret.js"() {
4265
+ init_errors();
4266
+ }
4267
+ });
4268
+
4269
+ // ../../../node_modules/jose/dist/webapi/index.js
4270
+ var webapi_exports = {};
4271
+ __export(webapi_exports, {
4272
+ CompactEncrypt: () => CompactEncrypt,
4273
+ CompactSign: () => CompactSign,
4274
+ EmbeddedJWK: () => EmbeddedJWK,
4275
+ EncryptJWT: () => EncryptJWT,
4276
+ FlattenedEncrypt: () => FlattenedEncrypt,
4277
+ FlattenedSign: () => FlattenedSign,
4278
+ GeneralEncrypt: () => GeneralEncrypt,
4279
+ GeneralSign: () => GeneralSign,
4280
+ SignJWT: () => SignJWT,
4281
+ UnsecuredJWT: () => UnsecuredJWT,
4282
+ base64url: () => base64url_exports,
4283
+ calculateJwkThumbprint: () => calculateJwkThumbprint,
4284
+ calculateJwkThumbprintUri: () => calculateJwkThumbprintUri,
4285
+ compactDecrypt: () => compactDecrypt,
4286
+ compactVerify: () => compactVerify,
4287
+ createLocalJWKSet: () => createLocalJWKSet,
4288
+ createRemoteJWKSet: () => createRemoteJWKSet,
4289
+ cryptoRuntime: () => cryptoRuntime,
4290
+ customFetch: () => customFetch,
4291
+ decodeJwt: () => decodeJwt,
4292
+ decodeProtectedHeader: () => decodeProtectedHeader,
4293
+ errors: () => errors_exports,
4294
+ exportJWK: () => exportJWK,
4295
+ exportPKCS8: () => exportPKCS8,
4296
+ exportSPKI: () => exportSPKI,
4297
+ flattenedDecrypt: () => flattenedDecrypt,
4298
+ flattenedVerify: () => flattenedVerify,
4299
+ generalDecrypt: () => generalDecrypt,
4300
+ generalVerify: () => generalVerify,
4301
+ generateKeyPair: () => generateKeyPair,
4302
+ generateSecret: () => generateSecret,
4303
+ importJWK: () => importJWK,
4304
+ importPKCS8: () => importPKCS8,
4305
+ importSPKI: () => importSPKI,
4306
+ importX509: () => importX509,
4307
+ jwksCache: () => jwksCache,
4308
+ jwtDecrypt: () => jwtDecrypt,
4309
+ jwtVerify: () => jwtVerify
4310
+ });
4311
+ var cryptoRuntime;
4312
+ var init_webapi = __esm({
4313
+ "../../../node_modules/jose/dist/webapi/index.js"() {
4314
+ init_decrypt3();
4315
+ init_decrypt2();
4316
+ init_decrypt4();
4317
+ init_encrypt3();
4318
+ init_verify3();
4319
+ init_verify2();
4320
+ init_verify4();
4321
+ init_verify5();
4322
+ init_decrypt5();
4323
+ init_encrypt4();
4324
+ init_encrypt2();
4325
+ init_sign3();
4326
+ init_sign2();
4327
+ init_sign4();
4328
+ init_sign5();
4329
+ init_encrypt5();
4330
+ init_thumbprint();
4331
+ init_embedded();
4332
+ init_local();
4333
+ init_remote();
4334
+ init_unsecured();
4335
+ init_export();
4336
+ init_import();
4337
+ init_decode_protected_header();
4338
+ init_decode_jwt();
4339
+ init_errors();
4340
+ init_generate_key_pair();
4341
+ init_generate_secret();
4342
+ init_base64url();
4343
+ cryptoRuntime = "WebCryptoAPI";
4344
+ }
4345
+ });
4346
+
4
4347
  // src/types/index.ts
5
4348
  var EVENT_TYPES = {
6
4349
  // Trajectory events
@@ -584,8 +4927,8 @@ function createErrorResponse(id, error) {
584
4927
  var MAPRequestError = class _MAPRequestError extends Error {
585
4928
  code;
586
4929
  data;
587
- constructor(code, message, data) {
588
- super(message);
4930
+ constructor(code, message2, data) {
4931
+ super(message2);
589
4932
  this.name = "MAPRequestError";
590
4933
  this.code = code;
591
4934
  this.data = data;
@@ -3142,7 +7485,7 @@ var MessageRouterImpl = class {
3142
7485
  throw new Error(`Target agent not found: ${params.to}`);
3143
7486
  }
3144
7487
  }
3145
- const message = {
7488
+ const message2 = {
3146
7489
  id: ulid(),
3147
7490
  from: params.from,
3148
7491
  to: params.to,
@@ -3155,17 +7498,17 @@ var MessageRouterImpl = class {
3155
7498
  };
3156
7499
  this.eventBus.emit({
3157
7500
  type: "message.sent",
3158
- data: { message },
7501
+ data: { message: message2 },
3159
7502
  source: { agentId: params.from }
3160
7503
  });
3161
- this.deliverToAgent(params.to, message);
3162
- return message;
7504
+ this.deliverToAgent(params.to, message2);
7505
+ return message2;
3163
7506
  }
3164
7507
  /**
3165
7508
  * Broadcast message to all agents in a scope.
3166
7509
  */
3167
7510
  sendToScope(params) {
3168
- const message = {
7511
+ const message2 = {
3169
7512
  id: ulid(),
3170
7513
  from: params.from,
3171
7514
  to: params.scopeId,
@@ -3175,7 +7518,7 @@ var MessageRouterImpl = class {
3175
7518
  };
3176
7519
  this.eventBus.emit({
3177
7520
  type: "message.sent",
3178
- data: { message, scopeId: params.scopeId },
7521
+ data: { message: message2, scopeId: params.scopeId },
3179
7522
  source: { agentId: params.from, scopeId: params.scopeId }
3180
7523
  });
3181
7524
  const members = this.scopes.getMembers(params.scopeId, {
@@ -3185,9 +7528,9 @@ var MessageRouterImpl = class {
3185
7528
  if (params.excludeSender && agentId === params.from) {
3186
7529
  continue;
3187
7530
  }
3188
- this.deliverToAgent(agentId, message);
7531
+ this.deliverToAgent(agentId, message2);
3189
7532
  }
3190
- return message;
7533
+ return message2;
3191
7534
  }
3192
7535
  /**
3193
7536
  * Set the delivery handler callback.
@@ -3237,32 +7580,32 @@ var MessageRouterImpl = class {
3237
7580
  /**
3238
7581
  * Deliver a message to an agent, queuing if offline.
3239
7582
  */
3240
- deliverToAgent(agentId, message) {
7583
+ deliverToAgent(agentId, message2) {
3241
7584
  const agent = this.agents.get(agentId);
3242
7585
  const isOnline = agent && agent.state !== "stopped";
3243
7586
  if (isOnline && this.deliveryHandler) {
3244
- this.deliveryHandler(agentId, message);
7587
+ this.deliveryHandler(agentId, message2);
3245
7588
  this.eventBus.emit({
3246
7589
  type: "message.delivered",
3247
- data: { message, agentId }
7590
+ data: { message: message2, agentId }
3248
7591
  });
3249
7592
  } else if (this.queueOptions.enabled) {
3250
- this.queueMessage(agentId, message);
7593
+ this.queueMessage(agentId, message2);
3251
7594
  }
3252
7595
  }
3253
7596
  /**
3254
7597
  * Queue a message for later delivery.
3255
7598
  * @returns true if message was queued, false if dropped
3256
7599
  */
3257
- queueMessage(agentId, message) {
7600
+ queueMessage(agentId, message2) {
3258
7601
  if (this.queueStore.getTotalSize() >= this.queueOptions.maxTotal) {
3259
7602
  this.queueStore.expireOld();
3260
7603
  if (this.queueStore.getTotalSize() >= this.queueOptions.maxTotal) {
3261
7604
  this.eventBus.emit({
3262
7605
  type: "message.dropped",
3263
7606
  data: {
3264
- messageId: message.id,
3265
- from: message.from,
7607
+ messageId: message2.id,
7608
+ from: message2.from,
3266
7609
  to: agentId,
3267
7610
  reason: "queue_full",
3268
7611
  queueSize: this.queueStore.getTotalSize(),
@@ -3276,8 +7619,8 @@ var MessageRouterImpl = class {
3276
7619
  this.eventBus.emit({
3277
7620
  type: "message.dropped",
3278
7621
  data: {
3279
- messageId: message.id,
3280
- from: message.from,
7622
+ messageId: message2.id,
7623
+ from: message2.from,
3281
7624
  to: agentId,
3282
7625
  reason: "agent_queue_full",
3283
7626
  agentQueueSize: this.queueStore.getQueueSize(agentId),
@@ -3286,10 +7629,10 @@ var MessageRouterImpl = class {
3286
7629
  });
3287
7630
  return false;
3288
7631
  }
3289
- const ttlMs = message.ttlMs ?? this.queueOptions.defaultTtlMs;
7632
+ const ttlMs = message2.ttlMs ?? this.queueOptions.defaultTtlMs;
3290
7633
  const now = Date.now();
3291
7634
  const queuedMessage = {
3292
- message,
7635
+ message: message2,
3293
7636
  targetAgentId: agentId,
3294
7637
  queuedAt: now,
3295
7638
  expiresAt: now + ttlMs,
@@ -3298,7 +7641,7 @@ var MessageRouterImpl = class {
3298
7641
  this.queueStore.enqueue(queuedMessage);
3299
7642
  this.eventBus.emit({
3300
7643
  type: "message.queued",
3301
- data: { messageId: message.id, agentId, expiresAt: queuedMessage.expiresAt }
7644
+ data: { messageId: message2.id, agentId, expiresAt: queuedMessage.expiresAt }
3302
7645
  });
3303
7646
  return true;
3304
7647
  }
@@ -3402,94 +7745,113 @@ function toScope(scopeId) {
3402
7745
  }
3403
7746
 
3404
7747
  // src/server/messages/handlers.ts
7748
+ function resolveRouteTarget(to) {
7749
+ if (typeof to === "string") {
7750
+ return { type: "string", value: to };
7751
+ }
7752
+ if (Array.isArray(to)) {
7753
+ return to.map((item) => resolveRouteTarget(item));
7754
+ }
7755
+ if (to && typeof to === "object") {
7756
+ const obj = to;
7757
+ if (typeof obj.agent === "string" && !obj.system) {
7758
+ return { type: "agent", id: obj.agent };
7759
+ }
7760
+ if (Array.isArray(obj.agents)) {
7761
+ return { type: "agents", ids: obj.agents };
7762
+ }
7763
+ if (typeof obj.scope === "string") {
7764
+ return { type: "scope", id: obj.scope };
7765
+ }
7766
+ if (obj.broadcast === true) {
7767
+ return { type: "broadcast" };
7768
+ }
7769
+ if (typeof obj.role === "string") {
7770
+ if (typeof obj.within === "string") {
7771
+ return { type: "scope", id: obj.within };
7772
+ }
7773
+ return { type: "broadcast" };
7774
+ }
7775
+ if (obj.system === true) {
7776
+ return { type: "broadcast" };
7777
+ }
7778
+ if (typeof obj.system === "string" && typeof obj.agent === "string") {
7779
+ return { type: "agent", id: obj.agent };
7780
+ }
7781
+ if (typeof obj.participant === "string") {
7782
+ return { type: "agent", id: obj.participant };
7783
+ }
7784
+ if (obj.participants === "all" || obj.participants === "agents") {
7785
+ return { type: "broadcast" };
7786
+ }
7787
+ if (obj.parent || obj.children || obj.ancestors || obj.descendants || obj.siblings) {
7788
+ return { type: "broadcast" };
7789
+ }
7790
+ }
7791
+ return { type: "string", value: String(to) };
7792
+ }
3405
7793
  function createMessageHandlers(options) {
3406
7794
  const { messages, scopes, agents, turns } = options;
7795
+ function sendToAgent(from, to, params) {
7796
+ return messages.sendToAgent({
7797
+ from,
7798
+ to,
7799
+ payload: params.payload,
7800
+ replyTo: params.replyTo,
7801
+ priority: params.priority,
7802
+ ttlMs: params.ttlMs,
7803
+ messageType: params.messageType
7804
+ });
7805
+ }
7806
+ function sendToScope(from, scopeId, params) {
7807
+ return messages.sendToScope({
7808
+ from,
7809
+ scopeId,
7810
+ payload: params.payload,
7811
+ excludeSender: true,
7812
+ messageType: params.messageType
7813
+ });
7814
+ }
7815
+ function resolveStringAddress(from, to, params) {
7816
+ if (isAddress(to)) {
7817
+ if (isScopeAddress(to)) {
7818
+ const message3 = sendToScope(from, extractId(to), params);
7819
+ return { messageId: message3.id };
7820
+ } else {
7821
+ const message3 = sendToAgent(from, extractId(to), params);
7822
+ return { messageId: message3.id };
7823
+ }
7824
+ }
7825
+ const scope = scopes.get(to);
7826
+ const agent = agents?.get(to);
7827
+ if (scope && agent) {
7828
+ throw new Error(
7829
+ `Ambiguous address "${to}" matches both an agent and a scope. Use "agent:${to}" or "scope:${to}" to disambiguate.`
7830
+ );
7831
+ }
7832
+ if (scope) {
7833
+ const message3 = sendToScope(from, to, params);
7834
+ return { messageId: message3.id };
7835
+ }
7836
+ const message2 = sendToAgent(from, to, params);
7837
+ return { messageId: message2.id };
7838
+ }
3407
7839
  return {
3408
7840
  "map/send": async (params, ctx) => {
3409
- const { to, payload, replyTo, priority, ttlMs, messageType, meta } = params;
7841
+ const sendParams = params;
7842
+ const { to: rawTo, meta } = sendParams;
3410
7843
  const from = ctx.session.agentIds[0] ?? ctx.session.id;
7844
+ const target = resolveRouteTarget(rawTo);
3411
7845
  let result;
3412
- if (Array.isArray(to)) {
7846
+ if (Array.isArray(target)) {
3413
7847
  const results = [];
3414
- for (const recipient of to) {
3415
- if (isScopeAddress(recipient)) {
3416
- const scopeId = extractId(recipient);
3417
- const message = messages.sendToScope({
3418
- from,
3419
- scopeId,
3420
- payload,
3421
- excludeSender: true,
3422
- messageType
3423
- });
3424
- results.push(message.id);
3425
- } else {
3426
- const agentId = isAgentAddress(recipient) ? extractId(recipient) : recipient;
3427
- const message = messages.sendToAgent({
3428
- from,
3429
- to: agentId,
3430
- payload,
3431
- replyTo,
3432
- priority,
3433
- ttlMs,
3434
- messageType
3435
- });
3436
- results.push(message.id);
3437
- }
7848
+ for (const t of target) {
7849
+ const { messageId } = routeSingle(from, t, sendParams);
7850
+ results.push(messageId);
3438
7851
  }
3439
7852
  result = { messageId: results[0], delivered: results };
3440
- } else if (isAddress(to)) {
3441
- if (isScopeAddress(to)) {
3442
- const scopeId = extractId(to);
3443
- const message = messages.sendToScope({
3444
- from,
3445
- scopeId,
3446
- payload,
3447
- excludeSender: true,
3448
- messageType
3449
- });
3450
- result = { messageId: message.id };
3451
- } else {
3452
- const agentId = extractId(to);
3453
- const message = messages.sendToAgent({
3454
- from,
3455
- to: agentId,
3456
- payload,
3457
- replyTo,
3458
- priority,
3459
- ttlMs,
3460
- messageType
3461
- });
3462
- result = { messageId: message.id };
3463
- }
3464
7853
  } else {
3465
- const scope = scopes.get(to);
3466
- const agent = agents?.get(to);
3467
- if (scope && agent) {
3468
- throw new Error(
3469
- `Ambiguous address "${to}" matches both an agent and a scope. Use "agent:${to}" or "scope:${to}" to disambiguate.`
3470
- );
3471
- }
3472
- if (scope) {
3473
- const message = messages.sendToScope({
3474
- from,
3475
- scopeId: to,
3476
- payload,
3477
- excludeSender: true,
3478
- messageType
3479
- });
3480
- result = { messageId: message.id };
3481
- } else {
3482
- const message = messages.sendToAgent({
3483
- from,
3484
- to,
3485
- payload,
3486
- replyTo,
3487
- priority,
3488
- ttlMs,
3489
- messageType
3490
- });
3491
- result = { messageId: message.id };
3492
- }
7854
+ result = routeSingle(from, target, sendParams);
3493
7855
  }
3494
7856
  if (turns && meta?.mail?.conversationId) {
3495
7857
  try {
@@ -3497,7 +7859,7 @@ function createMessageHandlers(options) {
3497
7859
  conversationId: meta.mail.conversationId,
3498
7860
  participant: from,
3499
7861
  contentType: "data",
3500
- content: payload,
7862
+ content: sendParams.payload,
3501
7863
  messageId: result.messageId,
3502
7864
  threadId: meta.mail.threadId,
3503
7865
  inReplyTo: meta.mail.inReplyTo,
@@ -3511,7 +7873,7 @@ function createMessageHandlers(options) {
3511
7873
  "map/send/scope": async (params, ctx) => {
3512
7874
  const { scopeId, payload, excludeSender, includeDescendants, messageType } = params;
3513
7875
  const from = ctx.session.agentIds[0] ?? ctx.session.id;
3514
- const message = messages.sendToScope({
7876
+ const message2 = messages.sendToScope({
3515
7877
  from,
3516
7878
  scopeId,
3517
7879
  payload,
@@ -3519,9 +7881,41 @@ function createMessageHandlers(options) {
3519
7881
  includeDescendants,
3520
7882
  messageType
3521
7883
  });
3522
- return { messageId: message.id };
7884
+ return { messageId: message2.id };
3523
7885
  }
3524
7886
  };
7887
+ function routeSingle(from, target, params) {
7888
+ switch (target.type) {
7889
+ case "agent": {
7890
+ const message2 = sendToAgent(from, target.id, params);
7891
+ return { messageId: message2.id };
7892
+ }
7893
+ case "agents": {
7894
+ const results = [];
7895
+ for (const agentId of target.ids) {
7896
+ const message2 = sendToAgent(from, agentId, params);
7897
+ results.push(message2.id);
7898
+ }
7899
+ return { messageId: results[0] };
7900
+ }
7901
+ case "scope": {
7902
+ const message2 = sendToScope(from, target.id, params);
7903
+ return { messageId: message2.id };
7904
+ }
7905
+ case "broadcast": {
7906
+ const message2 = messages.sendToAgent({
7907
+ from,
7908
+ to: "*",
7909
+ payload: params.payload,
7910
+ messageType: params.messageType
7911
+ });
7912
+ return { messageId: message2.id };
7913
+ }
7914
+ case "string": {
7915
+ return resolveStringAddress(from, target.value, params);
7916
+ }
7917
+ }
7918
+ }
3525
7919
  }
3526
7920
 
3527
7921
  // src/server/mail/stores/in-memory-conversation.ts
@@ -5056,13 +9450,13 @@ var RouterConnectionImpl = class {
5056
9450
  /**
5057
9451
  * Handle an incoming message.
5058
9452
  */
5059
- async handleMessage(message) {
5060
- if (this.isRequest(message)) {
5061
- await this.handleRequest(message);
5062
- } else if (this.isNotification(message)) {
9453
+ async handleMessage(message2) {
9454
+ if (this.isRequest(message2)) {
9455
+ await this.handleRequest(message2);
9456
+ } else if (this.isNotification(message2)) {
5063
9457
  if (this._notificationHandler) {
5064
9458
  try {
5065
- const msg = message;
9459
+ const msg = message2;
5066
9460
  this._notificationHandler(msg.method, msg.params);
5067
9461
  } catch {
5068
9462
  }
@@ -5072,14 +9466,14 @@ var RouterConnectionImpl = class {
5072
9466
  /**
5073
9467
  * Check if a message is a notification (method but no id).
5074
9468
  */
5075
- isNotification(message) {
5076
- return typeof message === "object" && message !== null && "jsonrpc" in message && message.jsonrpc === "2.0" && "method" in message && !("id" in message);
9469
+ isNotification(message2) {
9470
+ return typeof message2 === "object" && message2 !== null && "jsonrpc" in message2 && message2.jsonrpc === "2.0" && "method" in message2 && !("id" in message2);
5077
9471
  }
5078
9472
  /**
5079
9473
  * Check if a message is a request.
5080
9474
  */
5081
- isRequest(message) {
5082
- return typeof message === "object" && message !== null && "jsonrpc" in message && message.jsonrpc === "2.0" && "id" in message && "method" in message;
9475
+ isRequest(message2) {
9476
+ return typeof message2 === "object" && message2 !== null && "jsonrpc" in message2 && message2.jsonrpc === "2.0" && "id" in message2 && "method" in message2;
5083
9477
  }
5084
9478
  /**
5085
9479
  * Handle a JSON-RPC request.
@@ -5155,10 +9549,10 @@ var RouterConnectionImpl = class {
5155
9549
  /**
5156
9550
  * Send a message to the stream.
5157
9551
  */
5158
- async sendMessage(message) {
9552
+ async sendMessage(message2) {
5159
9553
  const writer = this.stream.writable.getWriter();
5160
9554
  try {
5161
- await writer.write(message);
9555
+ await writer.write(message2);
5162
9556
  } finally {
5163
9557
  writer.releaseLock();
5164
9558
  }
@@ -5789,8 +10183,8 @@ function createCredentialHandlers(options) {
5789
10183
  throw new Error("Missing required parameter: resource");
5790
10184
  }
5791
10185
  const token = getTokenFromSession(ctx);
5792
- const check = broker.checkPermission(token, scope, resource);
5793
- if (!check.valid) {
10186
+ const check2 = broker.checkPermission(token, scope, resource);
10187
+ if (!check2.valid) {
5794
10188
  if (eventBus) {
5795
10189
  eventBus.emit({
5796
10190
  type: "credential.denied",
@@ -5801,12 +10195,12 @@ function createCredentialHandlers(options) {
5801
10195
  },
5802
10196
  scope,
5803
10197
  resource,
5804
- reason: check.error
10198
+ reason: check2.error
5805
10199
  },
5806
10200
  source: { agentId: token.agentId }
5807
10201
  });
5808
10202
  }
5809
- throw new Error(check.error ?? "Permission denied");
10203
+ throw new Error(check2.error ?? "Permission denied");
5810
10204
  }
5811
10205
  const credential = await broker.getCredential(token, scope, resource);
5812
10206
  if (eventBus) {
@@ -6158,8 +10552,8 @@ var AUTH_ERRORS = {
6158
10552
  var AuthenticationError = class extends Error {
6159
10553
  code;
6160
10554
  authErrorCode;
6161
- constructor(message, authErrorCode = "auth_required") {
6162
- super(message);
10555
+ constructor(message2, authErrorCode = "auth_required") {
10556
+ super(message2);
6163
10557
  this.name = "AuthenticationError";
6164
10558
  this.code = AUTH_ERRORS.UNAUTHORIZED;
6165
10559
  this.authErrorCode = authErrorCode;
@@ -6292,7 +10686,7 @@ var joseModule = null;
6292
10686
  async function getJose() {
6293
10687
  if (!joseModule) {
6294
10688
  try {
6295
- joseModule = await import('jose');
10689
+ joseModule = await Promise.resolve().then(() => (init_webapi(), webapi_exports));
6296
10690
  } catch {
6297
10691
  throw new Error(
6298
10692
  'JWTAuthenticator requires the "jose" package. Install it with: npm install jose'
@@ -8016,8 +12410,8 @@ var PERMISSION_ERRORS = {
8016
12410
  FORBIDDEN: -32e3};
8017
12411
  var PermissionDeniedError = class extends Error {
8018
12412
  code;
8019
- constructor(message) {
8020
- super(message);
12413
+ constructor(message2) {
12414
+ super(message2);
8021
12415
  this.name = "PermissionDeniedError";
8022
12416
  this.code = PERMISSION_ERRORS.FORBIDDEN;
8023
12417
  }
@@ -9096,10 +13490,10 @@ var FederatedMessageRouter = class {
9096
13490
  this.gateway = options.gateway;
9097
13491
  this.agents = options.agents;
9098
13492
  this.gateway.onPeerMessage(this.handlePeerMessage.bind(this));
9099
- this.local.onDeliver((message) => {
13493
+ this.local.onDeliver((message2) => {
9100
13494
  for (const handler of this.deliveryHandlers) {
9101
13495
  try {
9102
- handler(message);
13496
+ handler(message2);
9103
13497
  } catch (error) {
9104
13498
  console.error("FederatedMessageRouter delivery handler error:", error);
9105
13499
  }
@@ -9183,7 +13577,7 @@ var FederatedMessageRouter = class {
9183
13577
  if (!parsed) {
9184
13578
  throw new Error(`Invalid remote agent ID: ${params.to}`);
9185
13579
  }
9186
- const message = {
13580
+ const message2 = {
9187
13581
  id: this.generateMessageId(),
9188
13582
  from: params.from,
9189
13583
  to: params.to,
@@ -9195,7 +13589,7 @@ var FederatedMessageRouter = class {
9195
13589
  const envelope = this.gateway.createEnvelope(parsed.systemId, {
9196
13590
  type: "message",
9197
13591
  message: {
9198
- ...message,
13592
+ ...message2,
9199
13593
  // Translate the target to original ID for the remote system
9200
13594
  to: parsed.originalId
9201
13595
  }
@@ -9203,7 +13597,7 @@ var FederatedMessageRouter = class {
9203
13597
  this.gateway.routeToPeer(parsed.systemId, envelope).catch((err) => {
9204
13598
  console.error(`Failed to route message to ${parsed.systemId}:`, err);
9205
13599
  });
9206
- return message;
13600
+ return message2;
9207
13601
  }
9208
13602
  /**
9209
13603
  * Handle incoming peer messages.
@@ -9213,19 +13607,19 @@ var FederatedMessageRouter = class {
9213
13607
  if (payload.type !== "message" || !payload.message) {
9214
13608
  return;
9215
13609
  }
9216
- const message = payload.message;
9217
- const localAgent = this.agents.get(message.to);
13610
+ const message2 = payload.message;
13611
+ const localAgent = this.agents.get(message2.to);
9218
13612
  if (!localAgent) {
9219
- console.warn(`Received federated message for unknown agent: ${message.to}`);
13613
+ console.warn(`Received federated message for unknown agent: ${message2.to}`);
9220
13614
  return;
9221
13615
  }
9222
13616
  const federatedMessage = {
9223
- ...message,
9224
- from: formatFederatedId(from, "agent", message.from),
13617
+ ...message2,
13618
+ from: formatFederatedId(from, "agent", message2.from),
9225
13619
  metadata: {
9226
- ...message.metadata ?? {},
13620
+ ...message2.metadata ?? {},
9227
13621
  _federatedFrom: from,
9228
- _originalFrom: message.from
13622
+ _originalFrom: message2.from
9229
13623
  }
9230
13624
  };
9231
13625
  for (const handler of this.deliveryHandlers) {
@@ -9247,15 +13641,15 @@ var FederatedMessageRouter = class {
9247
13641
  // src/server/federation/handlers.ts
9248
13642
  var FederationError = class extends Error {
9249
13643
  code;
9250
- constructor(message, code = -32e3) {
9251
- super(message);
13644
+ constructor(message2, code = -32e3) {
13645
+ super(message2);
9252
13646
  this.name = "FederationError";
9253
13647
  this.code = code;
9254
13648
  }
9255
13649
  };
9256
13650
  var FederationPermissionError = class extends FederationError {
9257
- constructor(message = "Federation operations require gateway role") {
9258
- super(message, -32003);
13651
+ constructor(message2 = "Federation operations require gateway role") {
13652
+ super(message2, -32003);
9259
13653
  this.name = "FederationPermissionError";
9260
13654
  }
9261
13655
  };