moltspay 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -9,4636 +9,36 @@ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
9
  var __esm = (fn, res) => function __init() {
10
10
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
11
  };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
-
33
- // node_modules/tsup/assets/cjs_shims.js
34
- var init_cjs_shims = __esm({
35
- "node_modules/tsup/assets/cjs_shims.js"() {
36
- "use strict";
37
- }
38
- });
39
-
40
- // node_modules/jose/dist/webapi/lib/buffer_utils.js
41
- function concat(...buffers) {
42
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
43
- const buf = new Uint8Array(size);
44
- let i = 0;
45
- for (const buffer of buffers) {
46
- buf.set(buffer, i);
47
- i += buffer.length;
48
- }
49
- return buf;
50
- }
51
- function writeUInt32BE(buf, value, offset) {
52
- if (value < 0 || value >= MAX_INT32) {
53
- throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
54
- }
55
- buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);
56
- }
57
- function uint64be(value) {
58
- const high = Math.floor(value / MAX_INT32);
59
- const low = value % MAX_INT32;
60
- const buf = new Uint8Array(8);
61
- writeUInt32BE(buf, high, 0);
62
- writeUInt32BE(buf, low, 4);
63
- return buf;
64
- }
65
- function uint32be(value) {
66
- const buf = new Uint8Array(4);
67
- writeUInt32BE(buf, value);
68
- return buf;
69
- }
70
- function encode(string) {
71
- const bytes = new Uint8Array(string.length);
72
- for (let i = 0; i < string.length; i++) {
73
- const code = string.charCodeAt(i);
74
- if (code > 127) {
75
- throw new TypeError("non-ASCII string encountered in encode()");
76
- }
77
- bytes[i] = code;
78
- }
79
- return bytes;
80
- }
81
- var encoder, decoder, MAX_INT32;
82
- var init_buffer_utils = __esm({
83
- "node_modules/jose/dist/webapi/lib/buffer_utils.js"() {
84
- "use strict";
85
- init_cjs_shims();
86
- encoder = new TextEncoder();
87
- decoder = new TextDecoder();
88
- MAX_INT32 = 2 ** 32;
89
- }
90
- });
91
-
92
- // node_modules/jose/dist/webapi/lib/base64.js
93
- function encodeBase64(input) {
94
- if (Uint8Array.prototype.toBase64) {
95
- return input.toBase64();
96
- }
97
- const CHUNK_SIZE = 32768;
98
- const arr = [];
99
- for (let i = 0; i < input.length; i += CHUNK_SIZE) {
100
- arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
101
- }
102
- return btoa(arr.join(""));
103
- }
104
- function decodeBase64(encoded) {
105
- if (Uint8Array.fromBase64) {
106
- return Uint8Array.fromBase64(encoded);
107
- }
108
- const binary = atob(encoded);
109
- const bytes = new Uint8Array(binary.length);
110
- for (let i = 0; i < binary.length; i++) {
111
- bytes[i] = binary.charCodeAt(i);
112
- }
113
- return bytes;
114
- }
115
- var init_base64 = __esm({
116
- "node_modules/jose/dist/webapi/lib/base64.js"() {
117
- "use strict";
118
- init_cjs_shims();
119
- }
120
- });
121
-
122
- // node_modules/jose/dist/webapi/util/base64url.js
123
- var base64url_exports = {};
124
- __export(base64url_exports, {
125
- decode: () => decode,
126
- encode: () => encode2
127
- });
128
- function decode(input) {
129
- if (Uint8Array.fromBase64) {
130
- return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
131
- alphabet: "base64url"
132
- });
133
- }
134
- let encoded = input;
135
- if (encoded instanceof Uint8Array) {
136
- encoded = decoder.decode(encoded);
137
- }
138
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
139
- try {
140
- return decodeBase64(encoded);
141
- } catch {
142
- throw new TypeError("The input to be decoded is not correctly encoded.");
143
- }
144
- }
145
- function encode2(input) {
146
- let unencoded = input;
147
- if (typeof unencoded === "string") {
148
- unencoded = encoder.encode(unencoded);
149
- }
150
- if (Uint8Array.prototype.toBase64) {
151
- return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
152
- }
153
- return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
154
- }
155
- var init_base64url = __esm({
156
- "node_modules/jose/dist/webapi/util/base64url.js"() {
157
- "use strict";
158
- init_cjs_shims();
159
- init_buffer_utils();
160
- init_base64();
161
- }
162
- });
163
-
164
- // node_modules/jose/dist/webapi/util/errors.js
165
- var errors_exports = {};
166
- __export(errors_exports, {
167
- JOSEAlgNotAllowed: () => JOSEAlgNotAllowed,
168
- JOSEError: () => JOSEError,
169
- JOSENotSupported: () => JOSENotSupported,
170
- JWEDecryptionFailed: () => JWEDecryptionFailed,
171
- JWEInvalid: () => JWEInvalid,
172
- JWKInvalid: () => JWKInvalid,
173
- JWKSInvalid: () => JWKSInvalid,
174
- JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
175
- JWKSNoMatchingKey: () => JWKSNoMatchingKey,
176
- JWKSTimeout: () => JWKSTimeout,
177
- JWSInvalid: () => JWSInvalid,
178
- JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
179
- JWTClaimValidationFailed: () => JWTClaimValidationFailed,
180
- JWTExpired: () => JWTExpired,
181
- JWTInvalid: () => JWTInvalid
182
- });
183
- var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed;
184
- var init_errors = __esm({
185
- "node_modules/jose/dist/webapi/util/errors.js"() {
186
- "use strict";
187
- init_cjs_shims();
188
- JOSEError = class extends Error {
189
- static code = "ERR_JOSE_GENERIC";
190
- code = "ERR_JOSE_GENERIC";
191
- constructor(message2, options) {
192
- super(message2, options);
193
- this.name = this.constructor.name;
194
- Error.captureStackTrace?.(this, this.constructor);
195
- }
196
- };
197
- JWTClaimValidationFailed = class extends JOSEError {
198
- static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
199
- code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
200
- claim;
201
- reason;
202
- payload;
203
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
204
- super(message2, { cause: { claim, reason, payload } });
205
- this.claim = claim;
206
- this.reason = reason;
207
- this.payload = payload;
208
- }
209
- };
210
- JWTExpired = class extends JOSEError {
211
- static code = "ERR_JWT_EXPIRED";
212
- code = "ERR_JWT_EXPIRED";
213
- claim;
214
- reason;
215
- payload;
216
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
217
- super(message2, { cause: { claim, reason, payload } });
218
- this.claim = claim;
219
- this.reason = reason;
220
- this.payload = payload;
221
- }
222
- };
223
- JOSEAlgNotAllowed = class extends JOSEError {
224
- static code = "ERR_JOSE_ALG_NOT_ALLOWED";
225
- code = "ERR_JOSE_ALG_NOT_ALLOWED";
226
- };
227
- JOSENotSupported = class extends JOSEError {
228
- static code = "ERR_JOSE_NOT_SUPPORTED";
229
- code = "ERR_JOSE_NOT_SUPPORTED";
230
- };
231
- JWEDecryptionFailed = class extends JOSEError {
232
- static code = "ERR_JWE_DECRYPTION_FAILED";
233
- code = "ERR_JWE_DECRYPTION_FAILED";
234
- constructor(message2 = "decryption operation failed", options) {
235
- super(message2, options);
236
- }
237
- };
238
- JWEInvalid = class extends JOSEError {
239
- static code = "ERR_JWE_INVALID";
240
- code = "ERR_JWE_INVALID";
241
- };
242
- JWSInvalid = class extends JOSEError {
243
- static code = "ERR_JWS_INVALID";
244
- code = "ERR_JWS_INVALID";
245
- };
246
- JWTInvalid = class extends JOSEError {
247
- static code = "ERR_JWT_INVALID";
248
- code = "ERR_JWT_INVALID";
249
- };
250
- JWKInvalid = class extends JOSEError {
251
- static code = "ERR_JWK_INVALID";
252
- code = "ERR_JWK_INVALID";
253
- };
254
- JWKSInvalid = class extends JOSEError {
255
- static code = "ERR_JWKS_INVALID";
256
- code = "ERR_JWKS_INVALID";
257
- };
258
- JWKSNoMatchingKey = class extends JOSEError {
259
- static code = "ERR_JWKS_NO_MATCHING_KEY";
260
- code = "ERR_JWKS_NO_MATCHING_KEY";
261
- constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
262
- super(message2, options);
263
- }
264
- };
265
- JWKSMultipleMatchingKeys = class extends JOSEError {
266
- [Symbol.asyncIterator];
267
- static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
268
- code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
269
- constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
270
- super(message2, options);
271
- }
272
- };
273
- JWKSTimeout = class extends JOSEError {
274
- static code = "ERR_JWKS_TIMEOUT";
275
- code = "ERR_JWKS_TIMEOUT";
276
- constructor(message2 = "request timed out", options) {
277
- super(message2, options);
278
- }
279
- };
280
- JWSSignatureVerificationFailed = class extends JOSEError {
281
- static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
282
- code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
283
- constructor(message2 = "signature verification failed", options) {
284
- super(message2, options);
285
- }
286
- };
287
- }
288
- });
289
-
290
- // node_modules/jose/dist/webapi/lib/iv.js
291
- function bitLength(alg) {
292
- switch (alg) {
293
- case "A128GCM":
294
- case "A128GCMKW":
295
- case "A192GCM":
296
- case "A192GCMKW":
297
- case "A256GCM":
298
- case "A256GCMKW":
299
- return 96;
300
- case "A128CBC-HS256":
301
- case "A192CBC-HS384":
302
- case "A256CBC-HS512":
303
- return 128;
304
- default:
305
- throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
306
- }
307
- }
308
- var generateIv;
309
- var init_iv = __esm({
310
- "node_modules/jose/dist/webapi/lib/iv.js"() {
311
- "use strict";
312
- init_cjs_shims();
313
- init_errors();
314
- generateIv = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
315
- }
316
- });
317
-
318
- // node_modules/jose/dist/webapi/lib/check_iv_length.js
319
- function checkIvLength(enc, iv) {
320
- if (iv.length << 3 !== bitLength(enc)) {
321
- throw new JWEInvalid("Invalid Initialization Vector length");
322
- }
323
- }
324
- var init_check_iv_length = __esm({
325
- "node_modules/jose/dist/webapi/lib/check_iv_length.js"() {
326
- "use strict";
327
- init_cjs_shims();
328
- init_errors();
329
- init_iv();
330
- }
331
- });
332
-
333
- // node_modules/jose/dist/webapi/lib/check_cek_length.js
334
- function checkCekLength(cek, expected) {
335
- const actual = cek.byteLength << 3;
336
- if (actual !== expected) {
337
- throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
338
- }
339
- }
340
- var init_check_cek_length = __esm({
341
- "node_modules/jose/dist/webapi/lib/check_cek_length.js"() {
342
- "use strict";
343
- init_cjs_shims();
344
- init_errors();
345
- }
346
- });
347
-
348
- // node_modules/jose/dist/webapi/lib/crypto_key.js
349
- function getHashLength(hash) {
350
- return parseInt(hash.name.slice(4), 10);
351
- }
352
- function getNamedCurve(alg) {
353
- switch (alg) {
354
- case "ES256":
355
- return "P-256";
356
- case "ES384":
357
- return "P-384";
358
- case "ES512":
359
- return "P-521";
360
- default:
361
- throw new Error("unreachable");
362
- }
363
- }
364
- function checkUsage(key, usage) {
365
- if (usage && !key.usages.includes(usage)) {
366
- throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
367
- }
368
- }
369
- function checkSigCryptoKey(key, alg, usage) {
370
- switch (alg) {
371
- case "HS256":
372
- case "HS384":
373
- case "HS512": {
374
- if (!isAlgorithm(key.algorithm, "HMAC"))
375
- throw unusable("HMAC");
376
- const expected = parseInt(alg.slice(2), 10);
377
- const actual = getHashLength(key.algorithm.hash);
378
- if (actual !== expected)
379
- throw unusable(`SHA-${expected}`, "algorithm.hash");
380
- break;
381
- }
382
- case "RS256":
383
- case "RS384":
384
- case "RS512": {
385
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
386
- throw unusable("RSASSA-PKCS1-v1_5");
387
- const expected = parseInt(alg.slice(2), 10);
388
- const actual = getHashLength(key.algorithm.hash);
389
- if (actual !== expected)
390
- throw unusable(`SHA-${expected}`, "algorithm.hash");
391
- break;
392
- }
393
- case "PS256":
394
- case "PS384":
395
- case "PS512": {
396
- if (!isAlgorithm(key.algorithm, "RSA-PSS"))
397
- throw unusable("RSA-PSS");
398
- const expected = parseInt(alg.slice(2), 10);
399
- const actual = getHashLength(key.algorithm.hash);
400
- if (actual !== expected)
401
- throw unusable(`SHA-${expected}`, "algorithm.hash");
402
- break;
403
- }
404
- case "Ed25519":
405
- case "EdDSA": {
406
- if (!isAlgorithm(key.algorithm, "Ed25519"))
407
- throw unusable("Ed25519");
408
- break;
409
- }
410
- case "ML-DSA-44":
411
- case "ML-DSA-65":
412
- case "ML-DSA-87": {
413
- if (!isAlgorithm(key.algorithm, alg))
414
- throw unusable(alg);
415
- break;
416
- }
417
- case "ES256":
418
- case "ES384":
419
- case "ES512": {
420
- if (!isAlgorithm(key.algorithm, "ECDSA"))
421
- throw unusable("ECDSA");
422
- const expected = getNamedCurve(alg);
423
- const actual = key.algorithm.namedCurve;
424
- if (actual !== expected)
425
- throw unusable(expected, "algorithm.namedCurve");
426
- break;
427
- }
428
- default:
429
- throw new TypeError("CryptoKey does not support this operation");
430
- }
431
- checkUsage(key, usage);
432
- }
433
- function checkEncCryptoKey(key, alg, usage) {
434
- switch (alg) {
435
- case "A128GCM":
436
- case "A192GCM":
437
- case "A256GCM": {
438
- if (!isAlgorithm(key.algorithm, "AES-GCM"))
439
- throw unusable("AES-GCM");
440
- const expected = parseInt(alg.slice(1, 4), 10);
441
- const actual = key.algorithm.length;
442
- if (actual !== expected)
443
- throw unusable(expected, "algorithm.length");
444
- break;
445
- }
446
- case "A128KW":
447
- case "A192KW":
448
- case "A256KW": {
449
- if (!isAlgorithm(key.algorithm, "AES-KW"))
450
- throw unusable("AES-KW");
451
- const expected = parseInt(alg.slice(1, 4), 10);
452
- const actual = key.algorithm.length;
453
- if (actual !== expected)
454
- throw unusable(expected, "algorithm.length");
455
- break;
456
- }
457
- case "ECDH": {
458
- switch (key.algorithm.name) {
459
- case "ECDH":
460
- case "X25519":
461
- break;
462
- default:
463
- throw unusable("ECDH or X25519");
464
- }
465
- break;
466
- }
467
- case "PBES2-HS256+A128KW":
468
- case "PBES2-HS384+A192KW":
469
- case "PBES2-HS512+A256KW":
470
- if (!isAlgorithm(key.algorithm, "PBKDF2"))
471
- throw unusable("PBKDF2");
472
- break;
473
- case "RSA-OAEP":
474
- case "RSA-OAEP-256":
475
- case "RSA-OAEP-384":
476
- case "RSA-OAEP-512": {
477
- if (!isAlgorithm(key.algorithm, "RSA-OAEP"))
478
- throw unusable("RSA-OAEP");
479
- const expected = parseInt(alg.slice(9), 10) || 1;
480
- const actual = getHashLength(key.algorithm.hash);
481
- if (actual !== expected)
482
- throw unusable(`SHA-${expected}`, "algorithm.hash");
483
- break;
484
- }
485
- default:
486
- throw new TypeError("CryptoKey does not support this operation");
487
- }
488
- checkUsage(key, usage);
489
- }
490
- var unusable, isAlgorithm;
491
- var init_crypto_key = __esm({
492
- "node_modules/jose/dist/webapi/lib/crypto_key.js"() {
493
- "use strict";
494
- init_cjs_shims();
495
- unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
496
- isAlgorithm = (algorithm, name) => algorithm.name === name;
497
- }
498
- });
499
-
500
- // node_modules/jose/dist/webapi/lib/invalid_key_input.js
501
- function message(msg, actual, ...types) {
502
- types = types.filter(Boolean);
503
- if (types.length > 2) {
504
- const last = types.pop();
505
- msg += `one of type ${types.join(", ")}, or ${last}.`;
506
- } else if (types.length === 2) {
507
- msg += `one of type ${types[0]} or ${types[1]}.`;
508
- } else {
509
- msg += `of type ${types[0]}.`;
510
- }
511
- if (actual == null) {
512
- msg += ` Received ${actual}`;
513
- } else if (typeof actual === "function" && actual.name) {
514
- msg += ` Received function ${actual.name}`;
515
- } else if (typeof actual === "object" && actual != null) {
516
- if (actual.constructor?.name) {
517
- msg += ` Received an instance of ${actual.constructor.name}`;
518
- }
519
- }
520
- return msg;
521
- }
522
- var invalidKeyInput, withAlg;
523
- var init_invalid_key_input = __esm({
524
- "node_modules/jose/dist/webapi/lib/invalid_key_input.js"() {
525
- "use strict";
526
- init_cjs_shims();
527
- invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
528
- withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
529
- }
530
- });
531
-
532
- // node_modules/jose/dist/webapi/lib/is_key_like.js
533
- function assertCryptoKey(key) {
534
- if (!isCryptoKey(key)) {
535
- throw new Error("CryptoKey instance expected");
536
- }
537
- }
538
- var isCryptoKey, isKeyObject, isKeyLike;
539
- var init_is_key_like = __esm({
540
- "node_modules/jose/dist/webapi/lib/is_key_like.js"() {
541
- "use strict";
542
- init_cjs_shims();
543
- isCryptoKey = (key) => {
544
- if (key?.[Symbol.toStringTag] === "CryptoKey")
545
- return true;
546
- try {
547
- return key instanceof CryptoKey;
548
- } catch {
549
- return false;
550
- }
551
- };
552
- isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
553
- isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
554
- }
555
- });
556
-
557
- // node_modules/jose/dist/webapi/lib/decrypt.js
558
- async function timingSafeEqual(a, b) {
559
- if (!(a instanceof Uint8Array)) {
560
- throw new TypeError("First argument must be a buffer");
561
- }
562
- if (!(b instanceof Uint8Array)) {
563
- throw new TypeError("Second argument must be a buffer");
564
- }
565
- const algorithm = { name: "HMAC", hash: "SHA-256" };
566
- const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]);
567
- const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
568
- const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
569
- let out = 0;
570
- let i = -1;
571
- while (++i < 32) {
572
- out |= aHmac[i] ^ bHmac[i];
573
- }
574
- return out === 0;
575
- }
576
- async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
577
- if (!(cek instanceof Uint8Array)) {
578
- throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
579
- }
580
- const keySize = parseInt(enc.slice(1, 4), 10);
581
- const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]);
582
- const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
583
- hash: `SHA-${keySize << 1}`,
584
- name: "HMAC"
585
- }, false, ["sign"]);
586
- const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
587
- const expectedTag = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
588
- let macCheckPassed;
589
- try {
590
- macCheckPassed = await timingSafeEqual(tag2, expectedTag);
591
- } catch {
592
- }
593
- if (!macCheckPassed) {
594
- throw new JWEDecryptionFailed();
595
- }
596
- let plaintext;
597
- try {
598
- plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext));
599
- } catch {
600
- }
601
- if (!plaintext) {
602
- throw new JWEDecryptionFailed();
603
- }
604
- return plaintext;
605
- }
606
- async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
607
- let encKey;
608
- if (cek instanceof Uint8Array) {
609
- encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
610
- } else {
611
- checkEncCryptoKey(cek, enc, "decrypt");
612
- encKey = cek;
613
- }
614
- try {
615
- return new Uint8Array(await crypto.subtle.decrypt({
616
- additionalData: aad,
617
- iv,
618
- name: "AES-GCM",
619
- tagLength: 128
620
- }, encKey, concat(ciphertext, tag2)));
621
- } catch {
622
- throw new JWEDecryptionFailed();
623
- }
624
- }
625
- async function decrypt(enc, cek, ciphertext, iv, tag2, aad) {
626
- if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
627
- throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
628
- }
629
- if (!iv) {
630
- throw new JWEInvalid("JWE Initialization Vector missing");
631
- }
632
- if (!tag2) {
633
- throw new JWEInvalid("JWE Authentication Tag missing");
634
- }
635
- checkIvLength(enc, iv);
636
- switch (enc) {
637
- case "A128CBC-HS256":
638
- case "A192CBC-HS384":
639
- case "A256CBC-HS512":
640
- if (cek instanceof Uint8Array)
641
- checkCekLength(cek, parseInt(enc.slice(-3), 10));
642
- return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad);
643
- case "A128GCM":
644
- case "A192GCM":
645
- case "A256GCM":
646
- if (cek instanceof Uint8Array)
647
- checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
648
- return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad);
649
- default:
650
- throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
651
- }
652
- }
653
- var init_decrypt = __esm({
654
- "node_modules/jose/dist/webapi/lib/decrypt.js"() {
655
- "use strict";
656
- init_cjs_shims();
657
- init_buffer_utils();
658
- init_check_iv_length();
659
- init_check_cek_length();
660
- init_errors();
661
- init_crypto_key();
662
- init_invalid_key_input();
663
- init_is_key_like();
664
- }
665
- });
666
-
667
- // node_modules/jose/dist/webapi/lib/is_disjoint.js
668
- function isDisjoint(...headers) {
669
- const sources = headers.filter(Boolean);
670
- if (sources.length === 0 || sources.length === 1) {
671
- return true;
672
- }
673
- let acc;
674
- for (const header of sources) {
675
- const parameters = Object.keys(header);
676
- if (!acc || acc.size === 0) {
677
- acc = new Set(parameters);
678
- continue;
679
- }
680
- for (const parameter of parameters) {
681
- if (acc.has(parameter)) {
682
- return false;
683
- }
684
- acc.add(parameter);
685
- }
686
- }
687
- return true;
688
- }
689
- var init_is_disjoint = __esm({
690
- "node_modules/jose/dist/webapi/lib/is_disjoint.js"() {
691
- "use strict";
692
- init_cjs_shims();
693
- }
694
- });
695
-
696
- // node_modules/jose/dist/webapi/lib/is_object.js
697
- function isObject(input) {
698
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
699
- return false;
700
- }
701
- if (Object.getPrototypeOf(input) === null) {
702
- return true;
703
- }
704
- let proto = input;
705
- while (Object.getPrototypeOf(proto) !== null) {
706
- proto = Object.getPrototypeOf(proto);
707
- }
708
- return Object.getPrototypeOf(input) === proto;
709
- }
710
- var isObjectLike;
711
- var init_is_object = __esm({
712
- "node_modules/jose/dist/webapi/lib/is_object.js"() {
713
- "use strict";
714
- init_cjs_shims();
715
- isObjectLike = (value) => typeof value === "object" && value !== null;
716
- }
717
- });
718
-
719
- // node_modules/jose/dist/webapi/lib/aeskw.js
720
- function checkKeySize(key, alg) {
721
- if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
722
- throw new TypeError(`Invalid key size for alg: ${alg}`);
723
- }
724
- }
725
- function getCryptoKey(key, alg, usage) {
726
- if (key instanceof Uint8Array) {
727
- return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]);
728
- }
729
- checkEncCryptoKey(key, alg, usage);
730
- return key;
731
- }
732
- async function wrap(alg, key, cek) {
733
- const cryptoKey = await getCryptoKey(key, alg, "wrapKey");
734
- checkKeySize(cryptoKey, alg);
735
- const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
736
- return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
737
- }
738
- async function unwrap(alg, key, encryptedKey) {
739
- const cryptoKey = await getCryptoKey(key, alg, "unwrapKey");
740
- checkKeySize(cryptoKey, alg);
741
- const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
742
- return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
743
- }
744
- var init_aeskw = __esm({
745
- "node_modules/jose/dist/webapi/lib/aeskw.js"() {
746
- "use strict";
747
- init_cjs_shims();
748
- init_crypto_key();
749
- }
750
- });
751
-
752
- // node_modules/jose/dist/webapi/lib/digest.js
753
- async function digest(algorithm, data) {
754
- const subtleDigest = `SHA-${algorithm.slice(-3)}`;
755
- return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
756
- }
757
- var init_digest = __esm({
758
- "node_modules/jose/dist/webapi/lib/digest.js"() {
759
- "use strict";
760
- init_cjs_shims();
761
- }
762
- });
763
-
764
- // node_modules/jose/dist/webapi/lib/ecdhes.js
765
- function lengthAndInput(input) {
766
- return concat(uint32be(input.length), input);
767
- }
768
- async function concatKdf(Z, L, OtherInfo) {
769
- const dkLen = L >> 3;
770
- const hashLen = 32;
771
- const reps = Math.ceil(dkLen / hashLen);
772
- const dk = new Uint8Array(reps * hashLen);
773
- for (let i = 1; i <= reps; i++) {
774
- const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);
775
- hashInput.set(uint32be(i), 0);
776
- hashInput.set(Z, 4);
777
- hashInput.set(OtherInfo, 4 + Z.length);
778
- const hashResult = await digest("sha256", hashInput);
779
- dk.set(hashResult, (i - 1) * hashLen);
780
- }
781
- return dk.slice(0, dkLen);
782
- }
783
- async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {
784
- checkEncCryptoKey(publicKey, "ECDH");
785
- checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
786
- const algorithmID = lengthAndInput(encode(algorithm));
787
- const partyUInfo = lengthAndInput(apu);
788
- const partyVInfo = lengthAndInput(apv);
789
- const suppPubInfo = uint32be(keyLength);
790
- const suppPrivInfo = new Uint8Array();
791
- const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
792
- const Z = new Uint8Array(await crypto.subtle.deriveBits({
793
- name: publicKey.algorithm.name,
794
- public: publicKey
795
- }, privateKey, getEcdhBitLength(publicKey)));
796
- return concatKdf(Z, keyLength, otherInfo);
797
- }
798
- function getEcdhBitLength(publicKey) {
799
- if (publicKey.algorithm.name === "X25519") {
800
- return 256;
801
- }
802
- return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
803
- }
804
- function allowed(key) {
805
- switch (key.algorithm.namedCurve) {
806
- case "P-256":
807
- case "P-384":
808
- case "P-521":
809
- return true;
810
- default:
811
- return key.algorithm.name === "X25519";
812
- }
813
- }
814
- var init_ecdhes = __esm({
815
- "node_modules/jose/dist/webapi/lib/ecdhes.js"() {
816
- "use strict";
817
- init_cjs_shims();
818
- init_buffer_utils();
819
- init_crypto_key();
820
- init_digest();
821
- }
822
- });
823
-
824
- // node_modules/jose/dist/webapi/lib/pbes2kw.js
825
- function getCryptoKey2(key, alg) {
826
- if (key instanceof Uint8Array) {
827
- return crypto.subtle.importKey("raw", key, "PBKDF2", false, [
828
- "deriveBits"
829
- ]);
830
- }
831
- checkEncCryptoKey(key, alg, "deriveBits");
832
- return key;
833
- }
834
- async function deriveKey2(p2s, alg, p2c, key) {
835
- if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
836
- throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
837
- }
838
- const salt = concatSalt(alg, p2s);
839
- const keylen = parseInt(alg.slice(13, 16), 10);
840
- const subtleAlg = {
841
- hash: `SHA-${alg.slice(8, 11)}`,
842
- iterations: p2c,
843
- name: "PBKDF2",
844
- salt
845
- };
846
- const cryptoKey = await getCryptoKey2(key, alg);
847
- return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
848
- }
849
- async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
850
- const derived = await deriveKey2(p2s, alg, p2c, key);
851
- const encryptedKey = await wrap(alg.slice(-6), derived, cek);
852
- return { encryptedKey, p2c, p2s: encode2(p2s) };
853
- }
854
- async function unwrap2(alg, key, encryptedKey, p2c, p2s) {
855
- const derived = await deriveKey2(p2s, alg, p2c, key);
856
- return unwrap(alg.slice(-6), derived, encryptedKey);
857
- }
858
- var concatSalt;
859
- var init_pbes2kw = __esm({
860
- "node_modules/jose/dist/webapi/lib/pbes2kw.js"() {
861
- "use strict";
862
- init_cjs_shims();
863
- init_base64url();
864
- init_aeskw();
865
- init_crypto_key();
866
- init_buffer_utils();
867
- init_errors();
868
- concatSalt = (alg, p2sInput) => concat(encode(alg), Uint8Array.of(0), p2sInput);
869
- }
870
- });
871
-
872
- // node_modules/jose/dist/webapi/lib/check_key_length.js
873
- function checkKeyLength(alg, key) {
874
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
875
- const { modulusLength } = key.algorithm;
876
- if (typeof modulusLength !== "number" || modulusLength < 2048) {
877
- throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
878
- }
879
- }
880
- }
881
- var init_check_key_length = __esm({
882
- "node_modules/jose/dist/webapi/lib/check_key_length.js"() {
883
- "use strict";
884
- init_cjs_shims();
885
- }
886
- });
887
-
888
- // node_modules/jose/dist/webapi/lib/rsaes.js
889
- async function encrypt(alg, key, cek) {
890
- checkEncCryptoKey(key, alg, "encrypt");
891
- checkKeyLength(alg, key);
892
- return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
893
- }
894
- async function decrypt2(alg, key, encryptedKey) {
895
- checkEncCryptoKey(key, alg, "decrypt");
896
- checkKeyLength(alg, key);
897
- return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
898
- }
899
- var subtleAlgorithm;
900
- var init_rsaes = __esm({
901
- "node_modules/jose/dist/webapi/lib/rsaes.js"() {
902
- "use strict";
903
- init_cjs_shims();
904
- init_crypto_key();
905
- init_check_key_length();
906
- init_errors();
907
- subtleAlgorithm = (alg) => {
908
- switch (alg) {
909
- case "RSA-OAEP":
910
- case "RSA-OAEP-256":
911
- case "RSA-OAEP-384":
912
- case "RSA-OAEP-512":
913
- return "RSA-OAEP";
914
- default:
915
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
916
- }
917
- };
918
- }
919
- });
920
-
921
- // node_modules/jose/dist/webapi/lib/cek.js
922
- function cekLength(alg) {
923
- switch (alg) {
924
- case "A128GCM":
925
- return 128;
926
- case "A192GCM":
927
- return 192;
928
- case "A256GCM":
929
- case "A128CBC-HS256":
930
- return 256;
931
- case "A192CBC-HS384":
932
- return 384;
933
- case "A256CBC-HS512":
934
- return 512;
935
- default:
936
- throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
937
- }
938
- }
939
- var generateCek;
940
- var init_cek = __esm({
941
- "node_modules/jose/dist/webapi/lib/cek.js"() {
942
- "use strict";
943
- init_cjs_shims();
944
- init_errors();
945
- generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3));
946
- }
947
- });
948
-
949
- // node_modules/jose/dist/webapi/lib/asn1.js
950
- function parsePKCS8Header(state) {
951
- expectTag(state, 48, "Invalid PKCS#8 structure");
952
- parseLength(state);
953
- expectTag(state, 2, "Expected version field");
954
- const verLen = parseLength(state);
955
- state.pos += verLen;
956
- expectTag(state, 48, "Expected algorithm identifier");
957
- const algIdLen = parseLength(state);
958
- const algIdStart = state.pos;
959
- return { algIdStart, algIdLength: algIdLen };
960
- }
961
- function parseSPKIHeader(state) {
962
- expectTag(state, 48, "Invalid SPKI structure");
963
- parseLength(state);
964
- expectTag(state, 48, "Expected algorithm identifier");
965
- const algIdLen = parseLength(state);
966
- const algIdStart = state.pos;
967
- return { algIdStart, algIdLength: algIdLen };
968
- }
969
- function spkiFromX509(buf) {
970
- const state = createASN1State(buf);
971
- expectTag(state, 48, "Invalid certificate structure");
972
- parseLength(state);
973
- expectTag(state, 48, "Invalid tbsCertificate structure");
974
- parseLength(state);
975
- if (buf[state.pos] === 160) {
976
- skipElement(state, 6);
977
- } else {
978
- skipElement(state, 5);
979
- }
980
- const spkiStart = state.pos;
981
- expectTag(state, 48, "Invalid SPKI structure");
982
- const spkiContentLen = parseLength(state);
983
- return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));
984
- }
985
- function extractX509SPKI(x509) {
986
- const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g);
987
- return spkiFromX509(derBytes);
988
- }
989
- var formatPEM, genericExport, toSPKI, toPKCS8, bytesEqual, createASN1State, parseLength, skipElement, expectTag, getSubarray, parseAlgorithmOID, parseECAlgorithmIdentifier, genericImport, processPEMData, fromPKCS8, fromSPKI, fromX509;
990
- var init_asn1 = __esm({
991
- "node_modules/jose/dist/webapi/lib/asn1.js"() {
992
- "use strict";
993
- init_cjs_shims();
994
- init_invalid_key_input();
995
- init_base64();
996
- init_errors();
997
- init_is_key_like();
998
- formatPEM = (b64, descriptor) => {
999
- const newlined = (b64.match(/.{1,64}/g) || []).join("\n");
1000
- return `-----BEGIN ${descriptor}-----
1001
- ${newlined}
1002
- -----END ${descriptor}-----`;
1003
- };
1004
- genericExport = async (keyType, keyFormat, key) => {
1005
- if (isKeyObject(key)) {
1006
- if (key.type !== keyType) {
1007
- throw new TypeError(`key is not a ${keyType} key`);
1008
- }
1009
- return key.export({ format: "pem", type: keyFormat });
1010
- }
1011
- if (!isCryptoKey(key)) {
1012
- throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject"));
1013
- }
1014
- if (!key.extractable) {
1015
- throw new TypeError("CryptoKey is not extractable");
1016
- }
1017
- if (key.type !== keyType) {
1018
- throw new TypeError(`key is not a ${keyType} key`);
1019
- }
1020
- return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
1021
- };
1022
- toSPKI = (key) => genericExport("public", "spki", key);
1023
- toPKCS8 = (key) => genericExport("private", "pkcs8", key);
1024
- bytesEqual = (a, b) => {
1025
- if (a.byteLength !== b.length)
1026
- return false;
1027
- for (let i = 0; i < a.byteLength; i++) {
1028
- if (a[i] !== b[i])
1029
- return false;
1030
- }
1031
- return true;
1032
- };
1033
- createASN1State = (data) => ({ data, pos: 0 });
1034
- parseLength = (state) => {
1035
- const first = state.data[state.pos++];
1036
- if (first & 128) {
1037
- const lengthOfLen = first & 127;
1038
- let length = 0;
1039
- for (let i = 0; i < lengthOfLen; i++) {
1040
- length = length << 8 | state.data[state.pos++];
1041
- }
1042
- return length;
1043
- }
1044
- return first;
1045
- };
1046
- skipElement = (state, count = 1) => {
1047
- if (count <= 0)
1048
- return;
1049
- state.pos++;
1050
- const length = parseLength(state);
1051
- state.pos += length;
1052
- if (count > 1) {
1053
- skipElement(state, count - 1);
1054
- }
1055
- };
1056
- expectTag = (state, expectedTag, errorMessage) => {
1057
- if (state.data[state.pos++] !== expectedTag) {
1058
- throw new Error(errorMessage);
1059
- }
1060
- };
1061
- getSubarray = (state, length) => {
1062
- const result = state.data.subarray(state.pos, state.pos + length);
1063
- state.pos += length;
1064
- return result;
1065
- };
1066
- parseAlgorithmOID = (state) => {
1067
- expectTag(state, 6, "Expected algorithm OID");
1068
- const oidLen = parseLength(state);
1069
- return getSubarray(state, oidLen);
1070
- };
1071
- parseECAlgorithmIdentifier = (state) => {
1072
- const algOid = parseAlgorithmOID(state);
1073
- if (bytesEqual(algOid, [43, 101, 110])) {
1074
- return "X25519";
1075
- }
1076
- if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
1077
- throw new Error("Unsupported key algorithm");
1078
- }
1079
- expectTag(state, 6, "Expected curve OID");
1080
- const curveOidLen = parseLength(state);
1081
- const curveOid = getSubarray(state, curveOidLen);
1082
- for (const { name, oid } of [
1083
- { name: "P-256", oid: [42, 134, 72, 206, 61, 3, 1, 7] },
1084
- { name: "P-384", oid: [43, 129, 4, 0, 34] },
1085
- { name: "P-521", oid: [43, 129, 4, 0, 35] }
1086
- ]) {
1087
- if (bytesEqual(curveOid, oid)) {
1088
- return name;
1089
- }
1090
- }
1091
- throw new Error("Unsupported named curve");
1092
- };
1093
- genericImport = async (keyFormat, keyData, alg, options) => {
1094
- let algorithm;
1095
- let keyUsages;
1096
- const isPublic = keyFormat === "spki";
1097
- const getSigUsages = () => isPublic ? ["verify"] : ["sign"];
1098
- const getEncUsages = () => isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
1099
- switch (alg) {
1100
- case "PS256":
1101
- case "PS384":
1102
- case "PS512":
1103
- algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` };
1104
- keyUsages = getSigUsages();
1105
- break;
1106
- case "RS256":
1107
- case "RS384":
1108
- case "RS512":
1109
- algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` };
1110
- keyUsages = getSigUsages();
1111
- break;
1112
- case "RSA-OAEP":
1113
- case "RSA-OAEP-256":
1114
- case "RSA-OAEP-384":
1115
- case "RSA-OAEP-512":
1116
- algorithm = {
1117
- name: "RSA-OAEP",
1118
- hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
1119
- };
1120
- keyUsages = getEncUsages();
1121
- break;
1122
- case "ES256":
1123
- case "ES384":
1124
- case "ES512": {
1125
- const curveMap = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
1126
- algorithm = { name: "ECDSA", namedCurve: curveMap[alg] };
1127
- keyUsages = getSigUsages();
1128
- break;
1129
- }
1130
- case "ECDH-ES":
1131
- case "ECDH-ES+A128KW":
1132
- case "ECDH-ES+A192KW":
1133
- case "ECDH-ES+A256KW": {
1134
- try {
1135
- const namedCurve = options.getNamedCurve(keyData);
1136
- algorithm = namedCurve === "X25519" ? { name: "X25519" } : { name: "ECDH", namedCurve };
1137
- } catch (cause) {
1138
- throw new JOSENotSupported("Invalid or unsupported key format");
1139
- }
1140
- keyUsages = isPublic ? [] : ["deriveBits"];
1141
- break;
1142
- }
1143
- case "Ed25519":
1144
- case "EdDSA":
1145
- algorithm = { name: "Ed25519" };
1146
- keyUsages = getSigUsages();
1147
- break;
1148
- case "ML-DSA-44":
1149
- case "ML-DSA-65":
1150
- case "ML-DSA-87":
1151
- algorithm = { name: alg };
1152
- keyUsages = getSigUsages();
1153
- break;
1154
- default:
1155
- throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
1156
- }
1157
- return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
1158
- };
1159
- processPEMData = (pem, pattern) => {
1160
- return decodeBase64(pem.replace(pattern, ""));
1161
- };
1162
- fromPKCS8 = (pem, alg, options) => {
1163
- const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
1164
- let opts = options;
1165
- if (alg?.startsWith?.("ECDH-ES")) {
1166
- opts ||= {};
1167
- opts.getNamedCurve = (keyData2) => {
1168
- const state = createASN1State(keyData2);
1169
- parsePKCS8Header(state);
1170
- return parseECAlgorithmIdentifier(state);
1171
- };
1172
- }
1173
- return genericImport("pkcs8", keyData, alg, opts);
1174
- };
1175
- fromSPKI = (pem, alg, options) => {
1176
- const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);
1177
- let opts = options;
1178
- if (alg?.startsWith?.("ECDH-ES")) {
1179
- opts ||= {};
1180
- opts.getNamedCurve = (keyData2) => {
1181
- const state = createASN1State(keyData2);
1182
- parseSPKIHeader(state);
1183
- return parseECAlgorithmIdentifier(state);
1184
- };
1185
- }
1186
- return genericImport("spki", keyData, alg, opts);
1187
- };
1188
- fromX509 = (pem, alg, options) => {
1189
- let spki;
1190
- try {
1191
- spki = extractX509SPKI(pem);
1192
- } catch (cause) {
1193
- throw new TypeError("Failed to parse the X.509 certificate", { cause });
1194
- }
1195
- return fromSPKI(formatPEM(encodeBase64(spki), "PUBLIC KEY"), alg, options);
1196
- };
1197
- }
1198
- });
1199
-
1200
- // node_modules/jose/dist/webapi/lib/jwk_to_key.js
1201
- function subtleMapping(jwk) {
1202
- let algorithm;
1203
- let keyUsages;
1204
- switch (jwk.kty) {
1205
- case "AKP": {
1206
- switch (jwk.alg) {
1207
- case "ML-DSA-44":
1208
- case "ML-DSA-65":
1209
- case "ML-DSA-87":
1210
- algorithm = { name: jwk.alg };
1211
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
1212
- break;
1213
- default:
1214
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1215
- }
1216
- break;
1217
- }
1218
- case "RSA": {
1219
- switch (jwk.alg) {
1220
- case "PS256":
1221
- case "PS384":
1222
- case "PS512":
1223
- algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
1224
- keyUsages = jwk.d ? ["sign"] : ["verify"];
1225
- break;
1226
- case "RS256":
1227
- case "RS384":
1228
- case "RS512":
1229
- algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
1230
- keyUsages = jwk.d ? ["sign"] : ["verify"];
1231
- break;
1232
- case "RSA-OAEP":
1233
- case "RSA-OAEP-256":
1234
- case "RSA-OAEP-384":
1235
- case "RSA-OAEP-512":
1236
- algorithm = {
1237
- name: "RSA-OAEP",
1238
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
1239
- };
1240
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
1241
- break;
1242
- default:
1243
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1244
- }
1245
- break;
1246
- }
1247
- case "EC": {
1248
- switch (jwk.alg) {
1249
- case "ES256":
1250
- algorithm = { name: "ECDSA", namedCurve: "P-256" };
1251
- keyUsages = jwk.d ? ["sign"] : ["verify"];
1252
- break;
1253
- case "ES384":
1254
- algorithm = { name: "ECDSA", namedCurve: "P-384" };
1255
- keyUsages = jwk.d ? ["sign"] : ["verify"];
1256
- break;
1257
- case "ES512":
1258
- algorithm = { name: "ECDSA", namedCurve: "P-521" };
1259
- keyUsages = jwk.d ? ["sign"] : ["verify"];
1260
- break;
1261
- case "ECDH-ES":
1262
- case "ECDH-ES+A128KW":
1263
- case "ECDH-ES+A192KW":
1264
- case "ECDH-ES+A256KW":
1265
- algorithm = { name: "ECDH", namedCurve: jwk.crv };
1266
- keyUsages = jwk.d ? ["deriveBits"] : [];
1267
- break;
1268
- default:
1269
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1270
- }
1271
- break;
1272
- }
1273
- case "OKP": {
1274
- switch (jwk.alg) {
1275
- case "Ed25519":
1276
- case "EdDSA":
1277
- algorithm = { name: "Ed25519" };
1278
- keyUsages = jwk.d ? ["sign"] : ["verify"];
1279
- break;
1280
- case "ECDH-ES":
1281
- case "ECDH-ES+A128KW":
1282
- case "ECDH-ES+A192KW":
1283
- case "ECDH-ES+A256KW":
1284
- algorithm = { name: jwk.crv };
1285
- keyUsages = jwk.d ? ["deriveBits"] : [];
1286
- break;
1287
- default:
1288
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
1289
- }
1290
- break;
1291
- }
1292
- default:
1293
- throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
1294
- }
1295
- return { algorithm, keyUsages };
1296
- }
1297
- async function jwkToKey(jwk) {
1298
- if (!jwk.alg) {
1299
- throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
1300
- }
1301
- const { algorithm, keyUsages } = subtleMapping(jwk);
1302
- const keyData = { ...jwk };
1303
- if (keyData.kty !== "AKP") {
1304
- delete keyData.alg;
1305
- }
1306
- delete keyData.use;
1307
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
1308
- }
1309
- var init_jwk_to_key = __esm({
1310
- "node_modules/jose/dist/webapi/lib/jwk_to_key.js"() {
1311
- "use strict";
1312
- init_cjs_shims();
1313
- init_errors();
1314
- }
1315
- });
1316
-
1317
- // node_modules/jose/dist/webapi/key/import.js
1318
- async function importSPKI(spki, alg, options) {
1319
- if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) {
1320
- throw new TypeError('"spki" must be SPKI formatted string');
1321
- }
1322
- return fromSPKI(spki, alg, options);
1323
- }
1324
- async function importX509(x509, alg, options) {
1325
- if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) {
1326
- throw new TypeError('"x509" must be X.509 formatted string');
1327
- }
1328
- return fromX509(x509, alg, options);
1329
- }
1330
- async function importPKCS8(pkcs8, alg, options) {
1331
- if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
1332
- throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
1333
- }
1334
- return fromPKCS8(pkcs8, alg, options);
1335
- }
1336
- async function importJWK(jwk, alg, options) {
1337
- if (!isObject(jwk)) {
1338
- throw new TypeError("JWK must be an object");
1339
- }
1340
- let ext;
1341
- alg ??= jwk.alg;
1342
- ext ??= options?.extractable ?? jwk.ext;
1343
- switch (jwk.kty) {
1344
- case "oct":
1345
- if (typeof jwk.k !== "string" || !jwk.k) {
1346
- throw new TypeError('missing "k" (Key Value) Parameter value');
1347
- }
1348
- return decode(jwk.k);
1349
- case "RSA":
1350
- if ("oth" in jwk && jwk.oth !== void 0) {
1351
- throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
1352
- }
1353
- return jwkToKey({ ...jwk, alg, ext });
1354
- case "AKP": {
1355
- if (typeof jwk.alg !== "string" || !jwk.alg) {
1356
- throw new TypeError('missing "alg" (Algorithm) Parameter value');
1357
- }
1358
- if (alg !== void 0 && alg !== jwk.alg) {
1359
- throw new TypeError("JWK alg and alg option value mismatch");
1360
- }
1361
- return jwkToKey({ ...jwk, ext });
1362
- }
1363
- case "EC":
1364
- case "OKP":
1365
- return jwkToKey({ ...jwk, alg, ext });
1366
- default:
1367
- throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
1368
- }
1369
- }
1370
- var init_import = __esm({
1371
- "node_modules/jose/dist/webapi/key/import.js"() {
1372
- "use strict";
1373
- init_cjs_shims();
1374
- init_base64url();
1375
- init_asn1();
1376
- init_jwk_to_key();
1377
- init_errors();
1378
- init_is_object();
1379
- }
1380
- });
1381
-
1382
- // node_modules/jose/dist/webapi/lib/encrypt.js
1383
- async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
1384
- if (!(cek instanceof Uint8Array)) {
1385
- throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
1386
- }
1387
- const keySize = parseInt(enc.slice(1, 4), 10);
1388
- const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]);
1389
- const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
1390
- hash: `SHA-${keySize << 1}`,
1391
- name: "HMAC"
1392
- }, false, ["sign"]);
1393
- const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
1394
- iv,
1395
- name: "AES-CBC"
1396
- }, encKey, plaintext));
1397
- const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
1398
- const tag2 = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
1399
- return { ciphertext, tag: tag2, iv };
1400
- }
1401
- async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
1402
- let encKey;
1403
- if (cek instanceof Uint8Array) {
1404
- encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
1405
- } else {
1406
- checkEncCryptoKey(cek, enc, "encrypt");
1407
- encKey = cek;
1408
- }
1409
- const encrypted = new Uint8Array(await crypto.subtle.encrypt({
1410
- additionalData: aad,
1411
- iv,
1412
- name: "AES-GCM",
1413
- tagLength: 128
1414
- }, encKey, plaintext));
1415
- const tag2 = encrypted.slice(-16);
1416
- const ciphertext = encrypted.slice(0, -16);
1417
- return { ciphertext, tag: tag2, iv };
1418
- }
1419
- async function encrypt2(enc, plaintext, cek, iv, aad) {
1420
- if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
1421
- throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
1422
- }
1423
- if (iv) {
1424
- checkIvLength(enc, iv);
1425
- } else {
1426
- iv = generateIv(enc);
1427
- }
1428
- switch (enc) {
1429
- case "A128CBC-HS256":
1430
- case "A192CBC-HS384":
1431
- case "A256CBC-HS512":
1432
- if (cek instanceof Uint8Array) {
1433
- checkCekLength(cek, parseInt(enc.slice(-3), 10));
1434
- }
1435
- return cbcEncrypt(enc, plaintext, cek, iv, aad);
1436
- case "A128GCM":
1437
- case "A192GCM":
1438
- case "A256GCM":
1439
- if (cek instanceof Uint8Array) {
1440
- checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
1441
- }
1442
- return gcmEncrypt(enc, plaintext, cek, iv, aad);
1443
- default:
1444
- throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
1445
- }
1446
- }
1447
- var init_encrypt = __esm({
1448
- "node_modules/jose/dist/webapi/lib/encrypt.js"() {
1449
- "use strict";
1450
- init_cjs_shims();
1451
- init_buffer_utils();
1452
- init_check_iv_length();
1453
- init_check_cek_length();
1454
- init_crypto_key();
1455
- init_invalid_key_input();
1456
- init_iv();
1457
- init_errors();
1458
- init_is_key_like();
1459
- }
1460
- });
1461
-
1462
- // node_modules/jose/dist/webapi/lib/aesgcmkw.js
1463
- async function wrap3(alg, key, cek, iv) {
1464
- const jweAlgorithm = alg.slice(0, 7);
1465
- const wrapped = await encrypt2(jweAlgorithm, cek, key, iv, new Uint8Array());
1466
- return {
1467
- encryptedKey: wrapped.ciphertext,
1468
- iv: encode2(wrapped.iv),
1469
- tag: encode2(wrapped.tag)
1470
- };
1471
- }
1472
- async function unwrap3(alg, key, encryptedKey, iv, tag2) {
1473
- const jweAlgorithm = alg.slice(0, 7);
1474
- return decrypt(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array());
1475
- }
1476
- var init_aesgcmkw = __esm({
1477
- "node_modules/jose/dist/webapi/lib/aesgcmkw.js"() {
1478
- "use strict";
1479
- init_cjs_shims();
1480
- init_encrypt();
1481
- init_decrypt();
1482
- init_base64url();
1483
- }
1484
- });
1485
-
1486
- // node_modules/jose/dist/webapi/lib/decrypt_key_management.js
1487
- async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
1488
- switch (alg) {
1489
- case "dir": {
1490
- if (encryptedKey !== void 0)
1491
- throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
1492
- return key;
1493
- }
1494
- case "ECDH-ES":
1495
- if (encryptedKey !== void 0)
1496
- throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
1497
- case "ECDH-ES+A128KW":
1498
- case "ECDH-ES+A192KW":
1499
- case "ECDH-ES+A256KW": {
1500
- if (!isObject(joseHeader.epk))
1501
- throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
1502
- assertCryptoKey(key);
1503
- if (!allowed(key))
1504
- throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
1505
- const epk = await importJWK(joseHeader.epk, alg);
1506
- assertCryptoKey(epk);
1507
- let partyUInfo;
1508
- let partyVInfo;
1509
- if (joseHeader.apu !== void 0) {
1510
- if (typeof joseHeader.apu !== "string")
1511
- throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
1512
- try {
1513
- partyUInfo = decode(joseHeader.apu);
1514
- } catch {
1515
- throw new JWEInvalid("Failed to base64url decode the apu");
1516
- }
1517
- }
1518
- if (joseHeader.apv !== void 0) {
1519
- if (typeof joseHeader.apv !== "string")
1520
- throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
1521
- try {
1522
- partyVInfo = decode(joseHeader.apv);
1523
- } catch {
1524
- throw new JWEInvalid("Failed to base64url decode the apv");
1525
- }
1526
- }
1527
- 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);
1528
- if (alg === "ECDH-ES")
1529
- return sharedSecret;
1530
- if (encryptedKey === void 0)
1531
- throw new JWEInvalid("JWE Encrypted Key missing");
1532
- return unwrap(alg.slice(-6), sharedSecret, encryptedKey);
1533
- }
1534
- case "RSA-OAEP":
1535
- case "RSA-OAEP-256":
1536
- case "RSA-OAEP-384":
1537
- case "RSA-OAEP-512": {
1538
- if (encryptedKey === void 0)
1539
- throw new JWEInvalid("JWE Encrypted Key missing");
1540
- assertCryptoKey(key);
1541
- return decrypt2(alg, key, encryptedKey);
1542
- }
1543
- case "PBES2-HS256+A128KW":
1544
- case "PBES2-HS384+A192KW":
1545
- case "PBES2-HS512+A256KW": {
1546
- if (encryptedKey === void 0)
1547
- throw new JWEInvalid("JWE Encrypted Key missing");
1548
- if (typeof joseHeader.p2c !== "number")
1549
- throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
1550
- const p2cLimit = options?.maxPBES2Count || 1e4;
1551
- if (joseHeader.p2c > p2cLimit)
1552
- throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
1553
- if (typeof joseHeader.p2s !== "string")
1554
- throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
1555
- let p2s;
1556
- try {
1557
- p2s = decode(joseHeader.p2s);
1558
- } catch {
1559
- throw new JWEInvalid("Failed to base64url decode the p2s");
1560
- }
1561
- return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s);
1562
- }
1563
- case "A128KW":
1564
- case "A192KW":
1565
- case "A256KW": {
1566
- if (encryptedKey === void 0)
1567
- throw new JWEInvalid("JWE Encrypted Key missing");
1568
- return unwrap(alg, key, encryptedKey);
1569
- }
1570
- case "A128GCMKW":
1571
- case "A192GCMKW":
1572
- case "A256GCMKW": {
1573
- if (encryptedKey === void 0)
1574
- throw new JWEInvalid("JWE Encrypted Key missing");
1575
- if (typeof joseHeader.iv !== "string")
1576
- throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
1577
- if (typeof joseHeader.tag !== "string")
1578
- throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
1579
- let iv;
1580
- try {
1581
- iv = decode(joseHeader.iv);
1582
- } catch {
1583
- throw new JWEInvalid("Failed to base64url decode the iv");
1584
- }
1585
- let tag2;
1586
- try {
1587
- tag2 = decode(joseHeader.tag);
1588
- } catch {
1589
- throw new JWEInvalid("Failed to base64url decode the tag");
1590
- }
1591
- return unwrap3(alg, key, encryptedKey, iv, tag2);
1592
- }
1593
- default: {
1594
- throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
1595
- }
1596
- }
1597
- }
1598
- var init_decrypt_key_management = __esm({
1599
- "node_modules/jose/dist/webapi/lib/decrypt_key_management.js"() {
1600
- "use strict";
1601
- init_cjs_shims();
1602
- init_aeskw();
1603
- init_ecdhes();
1604
- init_pbes2kw();
1605
- init_rsaes();
1606
- init_base64url();
1607
- init_errors();
1608
- init_cek();
1609
- init_import();
1610
- init_is_object();
1611
- init_aesgcmkw();
1612
- init_is_key_like();
1613
- }
1614
- });
1615
-
1616
- // node_modules/jose/dist/webapi/lib/validate_crit.js
1617
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
1618
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
1619
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
1620
- }
1621
- if (!protectedHeader || protectedHeader.crit === void 0) {
1622
- return /* @__PURE__ */ new Set();
1623
- }
1624
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
1625
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
1626
- }
1627
- let recognized;
1628
- if (recognizedOption !== void 0) {
1629
- recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
1630
- } else {
1631
- recognized = recognizedDefault;
1632
- }
1633
- for (const parameter of protectedHeader.crit) {
1634
- if (!recognized.has(parameter)) {
1635
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
1636
- }
1637
- if (joseHeader[parameter] === void 0) {
1638
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
1639
- }
1640
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
1641
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
1642
- }
1643
- }
1644
- return new Set(protectedHeader.crit);
1645
- }
1646
- var init_validate_crit = __esm({
1647
- "node_modules/jose/dist/webapi/lib/validate_crit.js"() {
1648
- "use strict";
1649
- init_cjs_shims();
1650
- init_errors();
1651
- }
1652
- });
1653
-
1654
- // node_modules/jose/dist/webapi/lib/validate_algorithms.js
1655
- function validateAlgorithms(option, algorithms) {
1656
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
1657
- throw new TypeError(`"${option}" option must be an array of strings`);
1658
- }
1659
- if (!algorithms) {
1660
- return void 0;
1661
- }
1662
- return new Set(algorithms);
1663
- }
1664
- var init_validate_algorithms = __esm({
1665
- "node_modules/jose/dist/webapi/lib/validate_algorithms.js"() {
1666
- "use strict";
1667
- init_cjs_shims();
1668
- }
1669
- });
1670
-
1671
- // node_modules/jose/dist/webapi/lib/is_jwk.js
1672
- var isJWK, isPrivateJWK, isPublicJWK, isSecretJWK;
1673
- var init_is_jwk = __esm({
1674
- "node_modules/jose/dist/webapi/lib/is_jwk.js"() {
1675
- "use strict";
1676
- init_cjs_shims();
1677
- init_is_object();
1678
- isJWK = (key) => isObject(key) && typeof key.kty === "string";
1679
- isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
1680
- isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
1681
- isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
1682
- }
1683
- });
1684
-
1685
- // node_modules/jose/dist/webapi/lib/normalize_key.js
1686
- async function normalizeKey(key, alg) {
1687
- if (key instanceof Uint8Array) {
1688
- return key;
1689
- }
1690
- if (isCryptoKey(key)) {
1691
- return key;
1692
- }
1693
- if (isKeyObject(key)) {
1694
- if (key.type === "secret") {
1695
- return key.export();
1696
- }
1697
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
1698
- try {
1699
- return handleKeyObject(key, alg);
1700
- } catch (err) {
1701
- if (err instanceof TypeError) {
1702
- throw err;
1703
- }
1704
- }
1705
- }
1706
- let jwk = key.export({ format: "jwk" });
1707
- return handleJWK(key, jwk, alg);
1708
- }
1709
- if (isJWK(key)) {
1710
- if (key.k) {
1711
- return decode(key.k);
1712
- }
1713
- return handleJWK(key, key, alg, true);
1714
- }
1715
- throw new Error("unreachable");
1716
- }
1717
- var cache, handleJWK, handleKeyObject;
1718
- var init_normalize_key = __esm({
1719
- "node_modules/jose/dist/webapi/lib/normalize_key.js"() {
1720
- "use strict";
1721
- init_cjs_shims();
1722
- init_is_jwk();
1723
- init_base64url();
1724
- init_jwk_to_key();
1725
- init_is_key_like();
1726
- handleJWK = async (key, jwk, alg, freeze = false) => {
1727
- cache ||= /* @__PURE__ */ new WeakMap();
1728
- let cached = cache.get(key);
1729
- if (cached?.[alg]) {
1730
- return cached[alg];
1731
- }
1732
- const cryptoKey = await jwkToKey({ ...jwk, alg });
1733
- if (freeze)
1734
- Object.freeze(key);
1735
- if (!cached) {
1736
- cache.set(key, { [alg]: cryptoKey });
1737
- } else {
1738
- cached[alg] = cryptoKey;
1739
- }
1740
- return cryptoKey;
1741
- };
1742
- handleKeyObject = (keyObject, alg) => {
1743
- cache ||= /* @__PURE__ */ new WeakMap();
1744
- let cached = cache.get(keyObject);
1745
- if (cached?.[alg]) {
1746
- return cached[alg];
1747
- }
1748
- const isPublic = keyObject.type === "public";
1749
- const extractable = isPublic ? true : false;
1750
- let cryptoKey;
1751
- if (keyObject.asymmetricKeyType === "x25519") {
1752
- switch (alg) {
1753
- case "ECDH-ES":
1754
- case "ECDH-ES+A128KW":
1755
- case "ECDH-ES+A192KW":
1756
- case "ECDH-ES+A256KW":
1757
- break;
1758
- default:
1759
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1760
- }
1761
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
1762
- }
1763
- if (keyObject.asymmetricKeyType === "ed25519") {
1764
- if (alg !== "EdDSA" && alg !== "Ed25519") {
1765
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1766
- }
1767
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
1768
- isPublic ? "verify" : "sign"
1769
- ]);
1770
- }
1771
- switch (keyObject.asymmetricKeyType) {
1772
- case "ml-dsa-44":
1773
- case "ml-dsa-65":
1774
- case "ml-dsa-87": {
1775
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
1776
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1777
- }
1778
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
1779
- isPublic ? "verify" : "sign"
1780
- ]);
1781
- }
1782
- }
1783
- if (keyObject.asymmetricKeyType === "rsa") {
1784
- let hash;
1785
- switch (alg) {
1786
- case "RSA-OAEP":
1787
- hash = "SHA-1";
1788
- break;
1789
- case "RS256":
1790
- case "PS256":
1791
- case "RSA-OAEP-256":
1792
- hash = "SHA-256";
1793
- break;
1794
- case "RS384":
1795
- case "PS384":
1796
- case "RSA-OAEP-384":
1797
- hash = "SHA-384";
1798
- break;
1799
- case "RS512":
1800
- case "PS512":
1801
- case "RSA-OAEP-512":
1802
- hash = "SHA-512";
1803
- break;
1804
- default:
1805
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1806
- }
1807
- if (alg.startsWith("RSA-OAEP")) {
1808
- return keyObject.toCryptoKey({
1809
- name: "RSA-OAEP",
1810
- hash
1811
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
1812
- }
1813
- cryptoKey = keyObject.toCryptoKey({
1814
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
1815
- hash
1816
- }, extractable, [isPublic ? "verify" : "sign"]);
1817
- }
1818
- if (keyObject.asymmetricKeyType === "ec") {
1819
- const nist = /* @__PURE__ */ new Map([
1820
- ["prime256v1", "P-256"],
1821
- ["secp384r1", "P-384"],
1822
- ["secp521r1", "P-521"]
1823
- ]);
1824
- const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
1825
- if (!namedCurve) {
1826
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1827
- }
1828
- if (alg === "ES256" && namedCurve === "P-256") {
1829
- cryptoKey = keyObject.toCryptoKey({
1830
- name: "ECDSA",
1831
- namedCurve
1832
- }, extractable, [isPublic ? "verify" : "sign"]);
1833
- }
1834
- if (alg === "ES384" && namedCurve === "P-384") {
1835
- cryptoKey = keyObject.toCryptoKey({
1836
- name: "ECDSA",
1837
- namedCurve
1838
- }, extractable, [isPublic ? "verify" : "sign"]);
1839
- }
1840
- if (alg === "ES512" && namedCurve === "P-521") {
1841
- cryptoKey = keyObject.toCryptoKey({
1842
- name: "ECDSA",
1843
- namedCurve
1844
- }, extractable, [isPublic ? "verify" : "sign"]);
1845
- }
1846
- if (alg.startsWith("ECDH-ES")) {
1847
- cryptoKey = keyObject.toCryptoKey({
1848
- name: "ECDH",
1849
- namedCurve
1850
- }, extractable, isPublic ? [] : ["deriveBits"]);
1851
- }
1852
- }
1853
- if (!cryptoKey) {
1854
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
1855
- }
1856
- if (!cached) {
1857
- cache.set(keyObject, { [alg]: cryptoKey });
1858
- } else {
1859
- cached[alg] = cryptoKey;
1860
- }
1861
- return cryptoKey;
1862
- };
1863
- }
1864
- });
1865
-
1866
- // node_modules/jose/dist/webapi/lib/check_key_type.js
1867
- function checkKeyType(alg, key, usage) {
1868
- switch (alg.substring(0, 2)) {
1869
- case "A1":
1870
- case "A2":
1871
- case "di":
1872
- case "HS":
1873
- case "PB":
1874
- symmetricTypeCheck(alg, key, usage);
1875
- break;
1876
- default:
1877
- asymmetricTypeCheck(alg, key, usage);
1878
- }
1879
- }
1880
- var tag, jwkMatchesOp, symmetricTypeCheck, asymmetricTypeCheck;
1881
- var init_check_key_type = __esm({
1882
- "node_modules/jose/dist/webapi/lib/check_key_type.js"() {
1883
- "use strict";
1884
- init_cjs_shims();
1885
- init_invalid_key_input();
1886
- init_is_key_like();
1887
- init_is_jwk();
1888
- tag = (key) => key?.[Symbol.toStringTag];
1889
- jwkMatchesOp = (alg, key, usage) => {
1890
- if (key.use !== void 0) {
1891
- let expected;
1892
- switch (usage) {
1893
- case "sign":
1894
- case "verify":
1895
- expected = "sig";
1896
- break;
1897
- case "encrypt":
1898
- case "decrypt":
1899
- expected = "enc";
1900
- break;
1901
- }
1902
- if (key.use !== expected) {
1903
- throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
1904
- }
1905
- }
1906
- if (key.alg !== void 0 && key.alg !== alg) {
1907
- throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
1908
- }
1909
- if (Array.isArray(key.key_ops)) {
1910
- let expectedKeyOp;
1911
- switch (true) {
1912
- case (usage === "sign" || usage === "verify"):
1913
- case alg === "dir":
1914
- case alg.includes("CBC-HS"):
1915
- expectedKeyOp = usage;
1916
- break;
1917
- case alg.startsWith("PBES2"):
1918
- expectedKeyOp = "deriveBits";
1919
- break;
1920
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
1921
- if (!alg.includes("GCM") && alg.endsWith("KW")) {
1922
- expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
1923
- } else {
1924
- expectedKeyOp = usage;
1925
- }
1926
- break;
1927
- case (usage === "encrypt" && alg.startsWith("RSA")):
1928
- expectedKeyOp = "wrapKey";
1929
- break;
1930
- case usage === "decrypt":
1931
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
1932
- break;
1933
- }
1934
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
1935
- throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
1936
- }
1937
- }
1938
- return true;
1939
- };
1940
- symmetricTypeCheck = (alg, key, usage) => {
1941
- if (key instanceof Uint8Array)
1942
- return;
1943
- if (isJWK(key)) {
1944
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
1945
- return;
1946
- 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`);
1947
- }
1948
- if (!isKeyLike(key)) {
1949
- throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
1950
- }
1951
- if (key.type !== "secret") {
1952
- throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
1953
- }
1954
- };
1955
- asymmetricTypeCheck = (alg, key, usage) => {
1956
- if (isJWK(key)) {
1957
- switch (usage) {
1958
- case "decrypt":
1959
- case "sign":
1960
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
1961
- return;
1962
- throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
1963
- case "encrypt":
1964
- case "verify":
1965
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
1966
- return;
1967
- throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
1968
- }
1969
- }
1970
- if (!isKeyLike(key)) {
1971
- throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
1972
- }
1973
- if (key.type === "secret") {
1974
- throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
1975
- }
1976
- if (key.type === "public") {
1977
- switch (usage) {
1978
- case "sign":
1979
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
1980
- case "decrypt":
1981
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
1982
- }
1983
- }
1984
- if (key.type === "private") {
1985
- switch (usage) {
1986
- case "verify":
1987
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
1988
- case "encrypt":
1989
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
1990
- }
1991
- }
1992
- };
1993
- }
1994
- });
1995
-
1996
- // node_modules/jose/dist/webapi/jwe/flattened/decrypt.js
1997
- async function flattenedDecrypt(jwe, key, options) {
1998
- if (!isObject(jwe)) {
1999
- throw new JWEInvalid("Flattened JWE must be an object");
2000
- }
2001
- if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) {
2002
- throw new JWEInvalid("JOSE Header missing");
2003
- }
2004
- if (jwe.iv !== void 0 && typeof jwe.iv !== "string") {
2005
- throw new JWEInvalid("JWE Initialization Vector incorrect type");
2006
- }
2007
- if (typeof jwe.ciphertext !== "string") {
2008
- throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
2009
- }
2010
- if (jwe.tag !== void 0 && typeof jwe.tag !== "string") {
2011
- throw new JWEInvalid("JWE Authentication Tag incorrect type");
2012
- }
2013
- if (jwe.protected !== void 0 && typeof jwe.protected !== "string") {
2014
- throw new JWEInvalid("JWE Protected Header incorrect type");
2015
- }
2016
- if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") {
2017
- throw new JWEInvalid("JWE Encrypted Key incorrect type");
2018
- }
2019
- if (jwe.aad !== void 0 && typeof jwe.aad !== "string") {
2020
- throw new JWEInvalid("JWE AAD incorrect type");
2021
- }
2022
- if (jwe.header !== void 0 && !isObject(jwe.header)) {
2023
- throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
2024
- }
2025
- if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) {
2026
- throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
2027
- }
2028
- let parsedProt;
2029
- if (jwe.protected) {
2030
- try {
2031
- const protectedHeader2 = decode(jwe.protected);
2032
- parsedProt = JSON.parse(decoder.decode(protectedHeader2));
2033
- } catch {
2034
- throw new JWEInvalid("JWE Protected Header is invalid");
2035
- }
2036
- }
2037
- if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
2038
- throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
2039
- }
2040
- const joseHeader = {
2041
- ...parsedProt,
2042
- ...jwe.header,
2043
- ...jwe.unprotected
2044
- };
2045
- validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
2046
- if (joseHeader.zip !== void 0) {
2047
- throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
2048
- }
2049
- const { alg, enc } = joseHeader;
2050
- if (typeof alg !== "string" || !alg) {
2051
- throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
2052
- }
2053
- if (typeof enc !== "string" || !enc) {
2054
- throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
2055
- }
2056
- const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms);
2057
- const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
2058
- if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) {
2059
- throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
2060
- }
2061
- if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
2062
- throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
2063
- }
2064
- let encryptedKey;
2065
- if (jwe.encrypted_key !== void 0) {
2066
- try {
2067
- encryptedKey = decode(jwe.encrypted_key);
2068
- } catch {
2069
- throw new JWEInvalid("Failed to base64url decode the encrypted_key");
2070
- }
2071
- }
2072
- let resolvedKey = false;
2073
- if (typeof key === "function") {
2074
- key = await key(parsedProt, jwe);
2075
- resolvedKey = true;
2076
- }
2077
- checkKeyType(alg === "dir" ? enc : alg, key, "decrypt");
2078
- const k = await normalizeKey(key, alg);
2079
- let cek;
2080
- try {
2081
- cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);
2082
- } catch (err) {
2083
- if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
2084
- throw err;
2085
- }
2086
- cek = generateCek(enc);
2087
- }
2088
- let iv;
2089
- let tag2;
2090
- if (jwe.iv !== void 0) {
2091
- try {
2092
- iv = decode(jwe.iv);
2093
- } catch {
2094
- throw new JWEInvalid("Failed to base64url decode the iv");
2095
- }
2096
- }
2097
- if (jwe.tag !== void 0) {
2098
- try {
2099
- tag2 = decode(jwe.tag);
2100
- } catch {
2101
- throw new JWEInvalid("Failed to base64url decode the tag");
2102
- }
2103
- }
2104
- const protectedHeader = jwe.protected !== void 0 ? encode(jwe.protected) : new Uint8Array();
2105
- let additionalData;
2106
- if (jwe.aad !== void 0) {
2107
- additionalData = concat(protectedHeader, encode("."), encode(jwe.aad));
2108
- } else {
2109
- additionalData = protectedHeader;
2110
- }
2111
- let ciphertext;
2112
- try {
2113
- ciphertext = decode(jwe.ciphertext);
2114
- } catch {
2115
- throw new JWEInvalid("Failed to base64url decode the ciphertext");
2116
- }
2117
- const plaintext = await decrypt(enc, cek, ciphertext, iv, tag2, additionalData);
2118
- const result = { plaintext };
2119
- if (jwe.protected !== void 0) {
2120
- result.protectedHeader = parsedProt;
2121
- }
2122
- if (jwe.aad !== void 0) {
2123
- try {
2124
- result.additionalAuthenticatedData = decode(jwe.aad);
2125
- } catch {
2126
- throw new JWEInvalid("Failed to base64url decode the aad");
2127
- }
2128
- }
2129
- if (jwe.unprotected !== void 0) {
2130
- result.sharedUnprotectedHeader = jwe.unprotected;
2131
- }
2132
- if (jwe.header !== void 0) {
2133
- result.unprotectedHeader = jwe.header;
2134
- }
2135
- if (resolvedKey) {
2136
- return { ...result, key: k };
2137
- }
2138
- return result;
2139
- }
2140
- var init_decrypt2 = __esm({
2141
- "node_modules/jose/dist/webapi/jwe/flattened/decrypt.js"() {
2142
- "use strict";
2143
- init_cjs_shims();
2144
- init_base64url();
2145
- init_decrypt();
2146
- init_errors();
2147
- init_is_disjoint();
2148
- init_is_object();
2149
- init_decrypt_key_management();
2150
- init_buffer_utils();
2151
- init_cek();
2152
- init_validate_crit();
2153
- init_validate_algorithms();
2154
- init_normalize_key();
2155
- init_check_key_type();
2156
- }
2157
- });
2158
-
2159
- // node_modules/jose/dist/webapi/jwe/compact/decrypt.js
2160
- async function compactDecrypt(jwe, key, options) {
2161
- if (jwe instanceof Uint8Array) {
2162
- jwe = decoder.decode(jwe);
2163
- }
2164
- if (typeof jwe !== "string") {
2165
- throw new JWEInvalid("Compact JWE must be a string or Uint8Array");
2166
- }
2167
- const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split(".");
2168
- if (length !== 5) {
2169
- throw new JWEInvalid("Invalid Compact JWE");
2170
- }
2171
- const decrypted = await flattenedDecrypt({
2172
- ciphertext,
2173
- iv: iv || void 0,
2174
- protected: protectedHeader,
2175
- tag: tag2 || void 0,
2176
- encrypted_key: encryptedKey || void 0
2177
- }, key, options);
2178
- const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
2179
- if (typeof key === "function") {
2180
- return { ...result, key: decrypted.key };
2181
- }
2182
- return result;
2183
- }
2184
- var init_decrypt3 = __esm({
2185
- "node_modules/jose/dist/webapi/jwe/compact/decrypt.js"() {
2186
- "use strict";
2187
- init_cjs_shims();
2188
- init_decrypt2();
2189
- init_errors();
2190
- init_buffer_utils();
2191
- }
2192
- });
2193
-
2194
- // node_modules/jose/dist/webapi/jwe/general/decrypt.js
2195
- async function generalDecrypt(jwe, key, options) {
2196
- if (!isObject(jwe)) {
2197
- throw new JWEInvalid("General JWE must be an object");
2198
- }
2199
- if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) {
2200
- throw new JWEInvalid("JWE Recipients missing or incorrect type");
2201
- }
2202
- if (!jwe.recipients.length) {
2203
- throw new JWEInvalid("JWE Recipients has no members");
2204
- }
2205
- for (const recipient of jwe.recipients) {
2206
- try {
2207
- return await flattenedDecrypt({
2208
- aad: jwe.aad,
2209
- ciphertext: jwe.ciphertext,
2210
- encrypted_key: recipient.encrypted_key,
2211
- header: recipient.header,
2212
- iv: jwe.iv,
2213
- protected: jwe.protected,
2214
- tag: jwe.tag,
2215
- unprotected: jwe.unprotected
2216
- }, key, options);
2217
- } catch {
2218
- }
2219
- }
2220
- throw new JWEDecryptionFailed();
2221
- }
2222
- var init_decrypt4 = __esm({
2223
- "node_modules/jose/dist/webapi/jwe/general/decrypt.js"() {
2224
- "use strict";
2225
- init_cjs_shims();
2226
- init_decrypt2();
2227
- init_errors();
2228
- init_is_object();
2229
- }
2230
- });
2231
-
2232
- // node_modules/jose/dist/webapi/lib/private_symbols.js
2233
- var unprotected;
2234
- var init_private_symbols = __esm({
2235
- "node_modules/jose/dist/webapi/lib/private_symbols.js"() {
2236
- "use strict";
2237
- init_cjs_shims();
2238
- unprotected = /* @__PURE__ */ Symbol();
2239
- }
2240
- });
2241
-
2242
- // node_modules/jose/dist/webapi/lib/key_to_jwk.js
2243
- async function keyToJWK(key) {
2244
- if (isKeyObject(key)) {
2245
- if (key.type === "secret") {
2246
- key = key.export();
2247
- } else {
2248
- return key.export({ format: "jwk" });
2249
- }
2250
- }
2251
- if (key instanceof Uint8Array) {
2252
- return {
2253
- kty: "oct",
2254
- k: encode2(key)
2255
- };
2256
- }
2257
- if (!isCryptoKey(key)) {
2258
- throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
2259
- }
2260
- if (!key.extractable) {
2261
- throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
2262
- }
2263
- const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
2264
- if (jwk.kty === "AKP") {
2265
- ;
2266
- jwk.alg = alg;
2267
- }
2268
- return jwk;
2269
- }
2270
- var init_key_to_jwk = __esm({
2271
- "node_modules/jose/dist/webapi/lib/key_to_jwk.js"() {
2272
- "use strict";
2273
- init_cjs_shims();
2274
- init_invalid_key_input();
2275
- init_base64url();
2276
- init_is_key_like();
2277
- }
2278
- });
2279
-
2280
- // node_modules/jose/dist/webapi/key/export.js
2281
- async function exportSPKI(key) {
2282
- return toSPKI(key);
2283
- }
2284
- async function exportPKCS8(key) {
2285
- return toPKCS8(key);
2286
- }
2287
- async function exportJWK(key) {
2288
- return keyToJWK(key);
2289
- }
2290
- var init_export = __esm({
2291
- "node_modules/jose/dist/webapi/key/export.js"() {
2292
- "use strict";
2293
- init_cjs_shims();
2294
- init_asn1();
2295
- init_key_to_jwk();
2296
- }
2297
- });
2298
-
2299
- // node_modules/jose/dist/webapi/lib/encrypt_key_management.js
2300
- async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
2301
- let encryptedKey;
2302
- let parameters;
2303
- let cek;
2304
- switch (alg) {
2305
- case "dir": {
2306
- cek = key;
2307
- break;
2308
- }
2309
- case "ECDH-ES":
2310
- case "ECDH-ES+A128KW":
2311
- case "ECDH-ES+A192KW":
2312
- case "ECDH-ES+A256KW": {
2313
- assertCryptoKey(key);
2314
- if (!allowed(key)) {
2315
- throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
2316
- }
2317
- const { apu, apv } = providedParameters;
2318
- let ephemeralKey;
2319
- if (providedParameters.epk) {
2320
- ephemeralKey = await normalizeKey(providedParameters.epk, alg);
2321
- } else {
2322
- ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
2323
- }
2324
- const { x, y, crv, kty } = await exportJWK(ephemeralKey);
2325
- const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
2326
- parameters = { epk: { x, crv, kty } };
2327
- if (kty === "EC")
2328
- parameters.epk.y = y;
2329
- if (apu)
2330
- parameters.apu = encode2(apu);
2331
- if (apv)
2332
- parameters.apv = encode2(apv);
2333
- if (alg === "ECDH-ES") {
2334
- cek = sharedSecret;
2335
- break;
2336
- }
2337
- cek = providedCek || generateCek(enc);
2338
- const kwAlg = alg.slice(-6);
2339
- encryptedKey = await wrap(kwAlg, sharedSecret, cek);
2340
- break;
2341
- }
2342
- case "RSA-OAEP":
2343
- case "RSA-OAEP-256":
2344
- case "RSA-OAEP-384":
2345
- case "RSA-OAEP-512": {
2346
- cek = providedCek || generateCek(enc);
2347
- assertCryptoKey(key);
2348
- encryptedKey = await encrypt(alg, key, cek);
2349
- break;
2350
- }
2351
- case "PBES2-HS256+A128KW":
2352
- case "PBES2-HS384+A192KW":
2353
- case "PBES2-HS512+A256KW": {
2354
- cek = providedCek || generateCek(enc);
2355
- const { p2c, p2s } = providedParameters;
2356
- ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s));
2357
- break;
2358
- }
2359
- case "A128KW":
2360
- case "A192KW":
2361
- case "A256KW": {
2362
- cek = providedCek || generateCek(enc);
2363
- encryptedKey = await wrap(alg, key, cek);
2364
- break;
2365
- }
2366
- case "A128GCMKW":
2367
- case "A192GCMKW":
2368
- case "A256GCMKW": {
2369
- cek = providedCek || generateCek(enc);
2370
- const { iv } = providedParameters;
2371
- ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv));
2372
- break;
2373
- }
2374
- default: {
2375
- throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
2376
- }
2377
- }
2378
- return { cek, encryptedKey, parameters };
2379
- }
2380
- var init_encrypt_key_management = __esm({
2381
- "node_modules/jose/dist/webapi/lib/encrypt_key_management.js"() {
2382
- "use strict";
2383
- init_cjs_shims();
2384
- init_aeskw();
2385
- init_ecdhes();
2386
- init_pbes2kw();
2387
- init_rsaes();
2388
- init_base64url();
2389
- init_normalize_key();
2390
- init_cek();
2391
- init_errors();
2392
- init_export();
2393
- init_aesgcmkw();
2394
- init_is_key_like();
2395
- }
2396
- });
2397
-
2398
- // node_modules/jose/dist/webapi/jwe/flattened/encrypt.js
2399
- var FlattenedEncrypt;
2400
- var init_encrypt2 = __esm({
2401
- "node_modules/jose/dist/webapi/jwe/flattened/encrypt.js"() {
2402
- "use strict";
2403
- init_cjs_shims();
2404
- init_base64url();
2405
- init_private_symbols();
2406
- init_encrypt();
2407
- init_encrypt_key_management();
2408
- init_errors();
2409
- init_is_disjoint();
2410
- init_buffer_utils();
2411
- init_validate_crit();
2412
- init_normalize_key();
2413
- init_check_key_type();
2414
- FlattenedEncrypt = class {
2415
- #plaintext;
2416
- #protectedHeader;
2417
- #sharedUnprotectedHeader;
2418
- #unprotectedHeader;
2419
- #aad;
2420
- #cek;
2421
- #iv;
2422
- #keyManagementParameters;
2423
- constructor(plaintext) {
2424
- if (!(plaintext instanceof Uint8Array)) {
2425
- throw new TypeError("plaintext must be an instance of Uint8Array");
2426
- }
2427
- this.#plaintext = plaintext;
2428
- }
2429
- setKeyManagementParameters(parameters) {
2430
- if (this.#keyManagementParameters) {
2431
- throw new TypeError("setKeyManagementParameters can only be called once");
2432
- }
2433
- this.#keyManagementParameters = parameters;
2434
- return this;
2435
- }
2436
- setProtectedHeader(protectedHeader) {
2437
- if (this.#protectedHeader) {
2438
- throw new TypeError("setProtectedHeader can only be called once");
2439
- }
2440
- this.#protectedHeader = protectedHeader;
2441
- return this;
2442
- }
2443
- setSharedUnprotectedHeader(sharedUnprotectedHeader) {
2444
- if (this.#sharedUnprotectedHeader) {
2445
- throw new TypeError("setSharedUnprotectedHeader can only be called once");
2446
- }
2447
- this.#sharedUnprotectedHeader = sharedUnprotectedHeader;
2448
- return this;
2449
- }
2450
- setUnprotectedHeader(unprotectedHeader) {
2451
- if (this.#unprotectedHeader) {
2452
- throw new TypeError("setUnprotectedHeader can only be called once");
2453
- }
2454
- this.#unprotectedHeader = unprotectedHeader;
2455
- return this;
2456
- }
2457
- setAdditionalAuthenticatedData(aad) {
2458
- this.#aad = aad;
2459
- return this;
2460
- }
2461
- setContentEncryptionKey(cek) {
2462
- if (this.#cek) {
2463
- throw new TypeError("setContentEncryptionKey can only be called once");
2464
- }
2465
- this.#cek = cek;
2466
- return this;
2467
- }
2468
- setInitializationVector(iv) {
2469
- if (this.#iv) {
2470
- throw new TypeError("setInitializationVector can only be called once");
2471
- }
2472
- this.#iv = iv;
2473
- return this;
2474
- }
2475
- async encrypt(key, options) {
2476
- if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) {
2477
- throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
2478
- }
2479
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {
2480
- throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
2481
- }
2482
- const joseHeader = {
2483
- ...this.#protectedHeader,
2484
- ...this.#unprotectedHeader,
2485
- ...this.#sharedUnprotectedHeader
2486
- };
2487
- validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader);
2488
- if (joseHeader.zip !== void 0) {
2489
- throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
2490
- }
2491
- const { alg, enc } = joseHeader;
2492
- if (typeof alg !== "string" || !alg) {
2493
- throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
2494
- }
2495
- if (typeof enc !== "string" || !enc) {
2496
- throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
2497
- }
2498
- let encryptedKey;
2499
- if (this.#cek && (alg === "dir" || alg === "ECDH-ES")) {
2500
- throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
2501
- }
2502
- checkKeyType(alg === "dir" ? enc : alg, key, "encrypt");
2503
- let cek;
2504
- {
2505
- let parameters;
2506
- const k = await normalizeKey(key, alg);
2507
- ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters));
2508
- if (parameters) {
2509
- if (options && unprotected in options) {
2510
- if (!this.#unprotectedHeader) {
2511
- this.setUnprotectedHeader(parameters);
2512
- } else {
2513
- this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters };
2514
- }
2515
- } else if (!this.#protectedHeader) {
2516
- this.setProtectedHeader(parameters);
2517
- } else {
2518
- this.#protectedHeader = { ...this.#protectedHeader, ...parameters };
2519
- }
2520
- }
2521
- }
2522
- let additionalData;
2523
- let protectedHeaderS;
2524
- let protectedHeaderB;
2525
- let aadMember;
2526
- if (this.#protectedHeader) {
2527
- protectedHeaderS = encode2(JSON.stringify(this.#protectedHeader));
2528
- protectedHeaderB = encode(protectedHeaderS);
2529
- } else {
2530
- protectedHeaderS = "";
2531
- protectedHeaderB = new Uint8Array();
2532
- }
2533
- if (this.#aad) {
2534
- aadMember = encode2(this.#aad);
2535
- const aadMemberBytes = encode(aadMember);
2536
- additionalData = concat(protectedHeaderB, encode("."), aadMemberBytes);
2537
- } else {
2538
- additionalData = protectedHeaderB;
2539
- }
2540
- const { ciphertext, tag: tag2, iv } = await encrypt2(enc, this.#plaintext, cek, this.#iv, additionalData);
2541
- const jwe = {
2542
- ciphertext: encode2(ciphertext)
2543
- };
2544
- if (iv) {
2545
- jwe.iv = encode2(iv);
2546
- }
2547
- if (tag2) {
2548
- jwe.tag = encode2(tag2);
2549
- }
2550
- if (encryptedKey) {
2551
- jwe.encrypted_key = encode2(encryptedKey);
2552
- }
2553
- if (aadMember) {
2554
- jwe.aad = aadMember;
2555
- }
2556
- if (this.#protectedHeader) {
2557
- jwe.protected = protectedHeaderS;
2558
- }
2559
- if (this.#sharedUnprotectedHeader) {
2560
- jwe.unprotected = this.#sharedUnprotectedHeader;
2561
- }
2562
- if (this.#unprotectedHeader) {
2563
- jwe.header = this.#unprotectedHeader;
2564
- }
2565
- return jwe;
2566
- }
2567
- };
2568
- }
2569
- });
2570
-
2571
- // node_modules/jose/dist/webapi/jwe/general/encrypt.js
2572
- var IndividualRecipient, GeneralEncrypt;
2573
- var init_encrypt3 = __esm({
2574
- "node_modules/jose/dist/webapi/jwe/general/encrypt.js"() {
2575
- "use strict";
2576
- init_cjs_shims();
2577
- init_encrypt2();
2578
- init_private_symbols();
2579
- init_errors();
2580
- init_cek();
2581
- init_is_disjoint();
2582
- init_encrypt_key_management();
2583
- init_base64url();
2584
- init_validate_crit();
2585
- init_normalize_key();
2586
- init_check_key_type();
2587
- IndividualRecipient = class {
2588
- #parent;
2589
- unprotectedHeader;
2590
- keyManagementParameters;
2591
- key;
2592
- options;
2593
- constructor(enc, key, options) {
2594
- this.#parent = enc;
2595
- this.key = key;
2596
- this.options = options;
2597
- }
2598
- setUnprotectedHeader(unprotectedHeader) {
2599
- if (this.unprotectedHeader) {
2600
- throw new TypeError("setUnprotectedHeader can only be called once");
2601
- }
2602
- this.unprotectedHeader = unprotectedHeader;
2603
- return this;
2604
- }
2605
- setKeyManagementParameters(parameters) {
2606
- if (this.keyManagementParameters) {
2607
- throw new TypeError("setKeyManagementParameters can only be called once");
2608
- }
2609
- this.keyManagementParameters = parameters;
2610
- return this;
2611
- }
2612
- addRecipient(...args) {
2613
- return this.#parent.addRecipient(...args);
2614
- }
2615
- encrypt(...args) {
2616
- return this.#parent.encrypt(...args);
2617
- }
2618
- done() {
2619
- return this.#parent;
2620
- }
2621
- };
2622
- GeneralEncrypt = class {
2623
- #plaintext;
2624
- #recipients = [];
2625
- #protectedHeader;
2626
- #unprotectedHeader;
2627
- #aad;
2628
- constructor(plaintext) {
2629
- this.#plaintext = plaintext;
2630
- }
2631
- addRecipient(key, options) {
2632
- const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
2633
- this.#recipients.push(recipient);
2634
- return recipient;
2635
- }
2636
- setProtectedHeader(protectedHeader) {
2637
- if (this.#protectedHeader) {
2638
- throw new TypeError("setProtectedHeader can only be called once");
2639
- }
2640
- this.#protectedHeader = protectedHeader;
2641
- return this;
2642
- }
2643
- setSharedUnprotectedHeader(sharedUnprotectedHeader) {
2644
- if (this.#unprotectedHeader) {
2645
- throw new TypeError("setSharedUnprotectedHeader can only be called once");
2646
- }
2647
- this.#unprotectedHeader = sharedUnprotectedHeader;
2648
- return this;
2649
- }
2650
- setAdditionalAuthenticatedData(aad) {
2651
- this.#aad = aad;
2652
- return this;
2653
- }
2654
- async encrypt() {
2655
- if (!this.#recipients.length) {
2656
- throw new JWEInvalid("at least one recipient must be added");
2657
- }
2658
- if (this.#recipients.length === 1) {
2659
- const [recipient] = this.#recipients;
2660
- const flattened = await new FlattenedEncrypt(this.#plaintext).setAdditionalAuthenticatedData(this.#aad).setProtectedHeader(this.#protectedHeader).setSharedUnprotectedHeader(this.#unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options });
2661
- const jwe2 = {
2662
- ciphertext: flattened.ciphertext,
2663
- iv: flattened.iv,
2664
- recipients: [{}],
2665
- tag: flattened.tag
2666
- };
2667
- if (flattened.aad)
2668
- jwe2.aad = flattened.aad;
2669
- if (flattened.protected)
2670
- jwe2.protected = flattened.protected;
2671
- if (flattened.unprotected)
2672
- jwe2.unprotected = flattened.unprotected;
2673
- if (flattened.encrypted_key)
2674
- jwe2.recipients[0].encrypted_key = flattened.encrypted_key;
2675
- if (flattened.header)
2676
- jwe2.recipients[0].header = flattened.header;
2677
- return jwe2;
2678
- }
2679
- let enc;
2680
- for (let i = 0; i < this.#recipients.length; i++) {
2681
- const recipient = this.#recipients[i];
2682
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, recipient.unprotectedHeader)) {
2683
- throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
2684
- }
2685
- const joseHeader = {
2686
- ...this.#protectedHeader,
2687
- ...this.#unprotectedHeader,
2688
- ...recipient.unprotectedHeader
2689
- };
2690
- const { alg } = joseHeader;
2691
- if (typeof alg !== "string" || !alg) {
2692
- throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
2693
- }
2694
- if (alg === "dir" || alg === "ECDH-ES") {
2695
- throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
2696
- }
2697
- if (typeof joseHeader.enc !== "string" || !joseHeader.enc) {
2698
- throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
2699
- }
2700
- if (!enc) {
2701
- enc = joseHeader.enc;
2702
- } else if (enc !== joseHeader.enc) {
2703
- throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
2704
- }
2705
- validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this.#protectedHeader, joseHeader);
2706
- if (joseHeader.zip !== void 0) {
2707
- throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
2708
- }
2709
- }
2710
- const cek = generateCek(enc);
2711
- const jwe = {
2712
- ciphertext: "",
2713
- recipients: []
2714
- };
2715
- for (let i = 0; i < this.#recipients.length; i++) {
2716
- const recipient = this.#recipients[i];
2717
- const target = {};
2718
- jwe.recipients.push(target);
2719
- if (i === 0) {
2720
- 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, {
2721
- ...recipient.options,
2722
- [unprotected]: true
2723
- });
2724
- jwe.ciphertext = flattened.ciphertext;
2725
- jwe.iv = flattened.iv;
2726
- jwe.tag = flattened.tag;
2727
- if (flattened.aad)
2728
- jwe.aad = flattened.aad;
2729
- if (flattened.protected)
2730
- jwe.protected = flattened.protected;
2731
- if (flattened.unprotected)
2732
- jwe.unprotected = flattened.unprotected;
2733
- target.encrypted_key = flattened.encrypted_key;
2734
- if (flattened.header)
2735
- target.header = flattened.header;
2736
- continue;
2737
- }
2738
- const alg = recipient.unprotectedHeader?.alg || this.#protectedHeader?.alg || this.#unprotectedHeader?.alg;
2739
- checkKeyType(alg === "dir" ? enc : alg, recipient.key, "encrypt");
2740
- const k = await normalizeKey(recipient.key, alg);
2741
- const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters);
2742
- target.encrypted_key = encode2(encryptedKey);
2743
- if (recipient.unprotectedHeader || parameters)
2744
- target.header = { ...recipient.unprotectedHeader, ...parameters };
2745
- }
2746
- return jwe;
2747
- }
2748
- };
2749
- }
2750
- });
2751
-
2752
- // node_modules/jose/dist/webapi/lib/subtle_dsa.js
2753
- function subtleAlgorithm2(alg, algorithm) {
2754
- const hash = `SHA-${alg.slice(-3)}`;
2755
- switch (alg) {
2756
- case "HS256":
2757
- case "HS384":
2758
- case "HS512":
2759
- return { hash, name: "HMAC" };
2760
- case "PS256":
2761
- case "PS384":
2762
- case "PS512":
2763
- return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
2764
- case "RS256":
2765
- case "RS384":
2766
- case "RS512":
2767
- return { hash, name: "RSASSA-PKCS1-v1_5" };
2768
- case "ES256":
2769
- case "ES384":
2770
- case "ES512":
2771
- return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
2772
- case "Ed25519":
2773
- case "EdDSA":
2774
- return { name: "Ed25519" };
2775
- case "ML-DSA-44":
2776
- case "ML-DSA-65":
2777
- case "ML-DSA-87":
2778
- return { name: alg };
2779
- default:
2780
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
2781
- }
2782
- }
2783
- var init_subtle_dsa = __esm({
2784
- "node_modules/jose/dist/webapi/lib/subtle_dsa.js"() {
2785
- "use strict";
2786
- init_cjs_shims();
2787
- init_errors();
2788
- }
2789
- });
2790
-
2791
- // node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
2792
- async function getSigKey(alg, key, usage) {
2793
- if (key instanceof Uint8Array) {
2794
- if (!alg.startsWith("HS")) {
2795
- throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
2796
- }
2797
- return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
2798
- }
2799
- checkSigCryptoKey(key, alg, usage);
2800
- return key;
2801
- }
2802
- var init_get_sign_verify_key = __esm({
2803
- "node_modules/jose/dist/webapi/lib/get_sign_verify_key.js"() {
2804
- "use strict";
2805
- init_cjs_shims();
2806
- init_crypto_key();
2807
- init_invalid_key_input();
2808
- }
2809
- });
2810
-
2811
- // node_modules/jose/dist/webapi/lib/verify.js
2812
- async function verify(alg, key, signature, data) {
2813
- const cryptoKey = await getSigKey(alg, key, "verify");
2814
- checkKeyLength(alg, cryptoKey);
2815
- const algorithm = subtleAlgorithm2(alg, cryptoKey.algorithm);
2816
- try {
2817
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
2818
- } catch {
2819
- return false;
2820
- }
2821
- }
2822
- var init_verify = __esm({
2823
- "node_modules/jose/dist/webapi/lib/verify.js"() {
2824
- "use strict";
2825
- init_cjs_shims();
2826
- init_subtle_dsa();
2827
- init_check_key_length();
2828
- init_get_sign_verify_key();
2829
- }
2830
- });
2831
-
2832
- // node_modules/jose/dist/webapi/jws/flattened/verify.js
2833
- async function flattenedVerify(jws, key, options) {
2834
- if (!isObject(jws)) {
2835
- throw new JWSInvalid("Flattened JWS must be an object");
2836
- }
2837
- if (jws.protected === void 0 && jws.header === void 0) {
2838
- throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
2839
- }
2840
- if (jws.protected !== void 0 && typeof jws.protected !== "string") {
2841
- throw new JWSInvalid("JWS Protected Header incorrect type");
2842
- }
2843
- if (jws.payload === void 0) {
2844
- throw new JWSInvalid("JWS Payload missing");
2845
- }
2846
- if (typeof jws.signature !== "string") {
2847
- throw new JWSInvalid("JWS Signature missing or incorrect type");
2848
- }
2849
- if (jws.header !== void 0 && !isObject(jws.header)) {
2850
- throw new JWSInvalid("JWS Unprotected Header incorrect type");
2851
- }
2852
- let parsedProt = {};
2853
- if (jws.protected) {
2854
- try {
2855
- const protectedHeader = decode(jws.protected);
2856
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
2857
- } catch {
2858
- throw new JWSInvalid("JWS Protected Header is invalid");
2859
- }
2860
- }
2861
- if (!isDisjoint(parsedProt, jws.header)) {
2862
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
2863
- }
2864
- const joseHeader = {
2865
- ...parsedProt,
2866
- ...jws.header
2867
- };
2868
- const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
2869
- let b64 = true;
2870
- if (extensions.has("b64")) {
2871
- b64 = parsedProt.b64;
2872
- if (typeof b64 !== "boolean") {
2873
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
2874
- }
2875
- }
2876
- const { alg } = joseHeader;
2877
- if (typeof alg !== "string" || !alg) {
2878
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
2879
- }
2880
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
2881
- if (algorithms && !algorithms.has(alg)) {
2882
- throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
2883
- }
2884
- if (b64) {
2885
- if (typeof jws.payload !== "string") {
2886
- throw new JWSInvalid("JWS Payload must be a string");
2887
- }
2888
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
2889
- throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
2890
- }
2891
- let resolvedKey = false;
2892
- if (typeof key === "function") {
2893
- key = await key(parsedProt, jws);
2894
- resolvedKey = true;
2895
- }
2896
- checkKeyType(alg, key, "verify");
2897
- 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);
2898
- let signature;
2899
- try {
2900
- signature = decode(jws.signature);
2901
- } catch {
2902
- throw new JWSInvalid("Failed to base64url decode the signature");
2903
- }
2904
- const k = await normalizeKey(key, alg);
2905
- const verified = await verify(alg, k, signature, data);
2906
- if (!verified) {
2907
- throw new JWSSignatureVerificationFailed();
2908
- }
2909
- let payload;
2910
- if (b64) {
2911
- try {
2912
- payload = decode(jws.payload);
2913
- } catch {
2914
- throw new JWSInvalid("Failed to base64url decode the payload");
2915
- }
2916
- } else if (typeof jws.payload === "string") {
2917
- payload = encoder.encode(jws.payload);
2918
- } else {
2919
- payload = jws.payload;
2920
- }
2921
- const result = { payload };
2922
- if (jws.protected !== void 0) {
2923
- result.protectedHeader = parsedProt;
2924
- }
2925
- if (jws.header !== void 0) {
2926
- result.unprotectedHeader = jws.header;
2927
- }
2928
- if (resolvedKey) {
2929
- return { ...result, key: k };
2930
- }
2931
- return result;
2932
- }
2933
- var init_verify2 = __esm({
2934
- "node_modules/jose/dist/webapi/jws/flattened/verify.js"() {
2935
- "use strict";
2936
- init_cjs_shims();
2937
- init_base64url();
2938
- init_verify();
2939
- init_errors();
2940
- init_buffer_utils();
2941
- init_is_disjoint();
2942
- init_is_object();
2943
- init_check_key_type();
2944
- init_validate_crit();
2945
- init_validate_algorithms();
2946
- init_normalize_key();
2947
- }
2948
- });
2949
-
2950
- // node_modules/jose/dist/webapi/jws/compact/verify.js
2951
- async function compactVerify(jws, key, options) {
2952
- if (jws instanceof Uint8Array) {
2953
- jws = decoder.decode(jws);
2954
- }
2955
- if (typeof jws !== "string") {
2956
- throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
2957
- }
2958
- const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
2959
- if (length !== 3) {
2960
- throw new JWSInvalid("Invalid Compact JWS");
2961
- }
2962
- const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
2963
- const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
2964
- if (typeof key === "function") {
2965
- return { ...result, key: verified.key };
2966
- }
2967
- return result;
2968
- }
2969
- var init_verify3 = __esm({
2970
- "node_modules/jose/dist/webapi/jws/compact/verify.js"() {
2971
- "use strict";
2972
- init_cjs_shims();
2973
- init_verify2();
2974
- init_errors();
2975
- init_buffer_utils();
2976
- }
2977
- });
2978
-
2979
- // node_modules/jose/dist/webapi/jws/general/verify.js
2980
- async function generalVerify(jws, key, options) {
2981
- if (!isObject(jws)) {
2982
- throw new JWSInvalid("General JWS must be an object");
2983
- }
2984
- if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) {
2985
- throw new JWSInvalid("JWS Signatures missing or incorrect type");
2986
- }
2987
- for (const signature of jws.signatures) {
2988
- try {
2989
- return await flattenedVerify({
2990
- header: signature.header,
2991
- payload: jws.payload,
2992
- protected: signature.protected,
2993
- signature: signature.signature
2994
- }, key, options);
2995
- } catch {
2996
- }
2997
- }
2998
- throw new JWSSignatureVerificationFailed();
2999
- }
3000
- var init_verify4 = __esm({
3001
- "node_modules/jose/dist/webapi/jws/general/verify.js"() {
3002
- "use strict";
3003
- init_cjs_shims();
3004
- init_verify2();
3005
- init_errors();
3006
- init_is_object();
3007
- }
3008
- });
3009
-
3010
- // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
3011
- function secs(str) {
3012
- const matched = REGEX.exec(str);
3013
- if (!matched || matched[4] && matched[1]) {
3014
- throw new TypeError("Invalid time period format");
3015
- }
3016
- const value = parseFloat(matched[2]);
3017
- const unit = matched[3].toLowerCase();
3018
- let numericDate;
3019
- switch (unit) {
3020
- case "sec":
3021
- case "secs":
3022
- case "second":
3023
- case "seconds":
3024
- case "s":
3025
- numericDate = Math.round(value);
3026
- break;
3027
- case "minute":
3028
- case "minutes":
3029
- case "min":
3030
- case "mins":
3031
- case "m":
3032
- numericDate = Math.round(value * minute);
3033
- break;
3034
- case "hour":
3035
- case "hours":
3036
- case "hr":
3037
- case "hrs":
3038
- case "h":
3039
- numericDate = Math.round(value * hour);
3040
- break;
3041
- case "day":
3042
- case "days":
3043
- case "d":
3044
- numericDate = Math.round(value * day);
3045
- break;
3046
- case "week":
3047
- case "weeks":
3048
- case "w":
3049
- numericDate = Math.round(value * week);
3050
- break;
3051
- default:
3052
- numericDate = Math.round(value * year);
3053
- break;
3054
- }
3055
- if (matched[1] === "-" || matched[4] === "ago") {
3056
- return -numericDate;
3057
- }
3058
- return numericDate;
3059
- }
3060
- function validateInput(label, input) {
3061
- if (!Number.isFinite(input)) {
3062
- throw new TypeError(`Invalid ${label} input`);
3063
- }
3064
- return input;
3065
- }
3066
- function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
3067
- let payload;
3068
- try {
3069
- payload = JSON.parse(decoder.decode(encodedPayload));
3070
- } catch {
3071
- }
3072
- if (!isObject(payload)) {
3073
- throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
3074
- }
3075
- const { typ } = options;
3076
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
3077
- throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
3078
- }
3079
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
3080
- const presenceCheck = [...requiredClaims];
3081
- if (maxTokenAge !== void 0)
3082
- presenceCheck.push("iat");
3083
- if (audience !== void 0)
3084
- presenceCheck.push("aud");
3085
- if (subject !== void 0)
3086
- presenceCheck.push("sub");
3087
- if (issuer !== void 0)
3088
- presenceCheck.push("iss");
3089
- for (const claim of new Set(presenceCheck.reverse())) {
3090
- if (!(claim in payload)) {
3091
- throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
3092
- }
3093
- }
3094
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
3095
- throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
3096
- }
3097
- if (subject && payload.sub !== subject) {
3098
- throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
3099
- }
3100
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
3101
- throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
3102
- }
3103
- let tolerance;
3104
- switch (typeof options.clockTolerance) {
3105
- case "string":
3106
- tolerance = secs(options.clockTolerance);
3107
- break;
3108
- case "number":
3109
- tolerance = options.clockTolerance;
3110
- break;
3111
- case "undefined":
3112
- tolerance = 0;
3113
- break;
3114
- default:
3115
- throw new TypeError("Invalid clockTolerance option type");
3116
- }
3117
- const { currentDate } = options;
3118
- const now = epoch(currentDate || /* @__PURE__ */ new Date());
3119
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
3120
- throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
3121
- }
3122
- if (payload.nbf !== void 0) {
3123
- if (typeof payload.nbf !== "number") {
3124
- throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
3125
- }
3126
- if (payload.nbf > now + tolerance) {
3127
- throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
3128
- }
3129
- }
3130
- if (payload.exp !== void 0) {
3131
- if (typeof payload.exp !== "number") {
3132
- throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
3133
- }
3134
- if (payload.exp <= now - tolerance) {
3135
- throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
3136
- }
3137
- }
3138
- if (maxTokenAge) {
3139
- const age = now - payload.iat;
3140
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
3141
- if (age - tolerance > max) {
3142
- throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
3143
- }
3144
- if (age < 0 - tolerance) {
3145
- throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
3146
- }
3147
- }
3148
- return payload;
3149
- }
3150
- var epoch, minute, hour, day, week, year, REGEX, normalizeTyp, checkAudiencePresence, JWTClaimsBuilder;
3151
- var init_jwt_claims_set = __esm({
3152
- "node_modules/jose/dist/webapi/lib/jwt_claims_set.js"() {
3153
- "use strict";
3154
- init_cjs_shims();
3155
- init_errors();
3156
- init_buffer_utils();
3157
- init_is_object();
3158
- epoch = (date) => Math.floor(date.getTime() / 1e3);
3159
- minute = 60;
3160
- hour = minute * 60;
3161
- day = hour * 24;
3162
- week = day * 7;
3163
- year = day * 365.25;
3164
- REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
3165
- normalizeTyp = (value) => {
3166
- if (value.includes("/")) {
3167
- return value.toLowerCase();
3168
- }
3169
- return `application/${value.toLowerCase()}`;
3170
- };
3171
- checkAudiencePresence = (audPayload, audOption) => {
3172
- if (typeof audPayload === "string") {
3173
- return audOption.includes(audPayload);
3174
- }
3175
- if (Array.isArray(audPayload)) {
3176
- return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
3177
- }
3178
- return false;
3179
- };
3180
- JWTClaimsBuilder = class {
3181
- #payload;
3182
- constructor(payload) {
3183
- if (!isObject(payload)) {
3184
- throw new TypeError("JWT Claims Set MUST be an object");
3185
- }
3186
- this.#payload = structuredClone(payload);
3187
- }
3188
- data() {
3189
- return encoder.encode(JSON.stringify(this.#payload));
3190
- }
3191
- get iss() {
3192
- return this.#payload.iss;
3193
- }
3194
- set iss(value) {
3195
- this.#payload.iss = value;
3196
- }
3197
- get sub() {
3198
- return this.#payload.sub;
3199
- }
3200
- set sub(value) {
3201
- this.#payload.sub = value;
3202
- }
3203
- get aud() {
3204
- return this.#payload.aud;
3205
- }
3206
- set aud(value) {
3207
- this.#payload.aud = value;
3208
- }
3209
- set jti(value) {
3210
- this.#payload.jti = value;
3211
- }
3212
- set nbf(value) {
3213
- if (typeof value === "number") {
3214
- this.#payload.nbf = validateInput("setNotBefore", value);
3215
- } else if (value instanceof Date) {
3216
- this.#payload.nbf = validateInput("setNotBefore", epoch(value));
3217
- } else {
3218
- this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
3219
- }
3220
- }
3221
- set exp(value) {
3222
- if (typeof value === "number") {
3223
- this.#payload.exp = validateInput("setExpirationTime", value);
3224
- } else if (value instanceof Date) {
3225
- this.#payload.exp = validateInput("setExpirationTime", epoch(value));
3226
- } else {
3227
- this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
3228
- }
3229
- }
3230
- set iat(value) {
3231
- if (value === void 0) {
3232
- this.#payload.iat = epoch(/* @__PURE__ */ new Date());
3233
- } else if (value instanceof Date) {
3234
- this.#payload.iat = validateInput("setIssuedAt", epoch(value));
3235
- } else if (typeof value === "string") {
3236
- this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
3237
- } else {
3238
- this.#payload.iat = validateInput("setIssuedAt", value);
3239
- }
3240
- }
3241
- };
3242
- }
3243
- });
3244
-
3245
- // node_modules/jose/dist/webapi/jwt/verify.js
3246
- async function jwtVerify(jwt, key, options) {
3247
- const verified = await compactVerify(jwt, key, options);
3248
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
3249
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3250
- }
3251
- const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
3252
- const result = { payload, protectedHeader: verified.protectedHeader };
3253
- if (typeof key === "function") {
3254
- return { ...result, key: verified.key };
3255
- }
3256
- return result;
3257
- }
3258
- var init_verify5 = __esm({
3259
- "node_modules/jose/dist/webapi/jwt/verify.js"() {
3260
- "use strict";
3261
- init_cjs_shims();
3262
- init_verify3();
3263
- init_jwt_claims_set();
3264
- init_errors();
3265
- }
3266
- });
3267
-
3268
- // node_modules/jose/dist/webapi/jwt/decrypt.js
3269
- async function jwtDecrypt(jwt, key, options) {
3270
- const decrypted = await compactDecrypt(jwt, key, options);
3271
- const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options);
3272
- const { protectedHeader } = decrypted;
3273
- if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) {
3274
- throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch");
3275
- }
3276
- if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) {
3277
- throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch");
3278
- }
3279
- if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
3280
- throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch");
3281
- }
3282
- const result = { payload, protectedHeader };
3283
- if (typeof key === "function") {
3284
- return { ...result, key: decrypted.key };
3285
- }
3286
- return result;
3287
- }
3288
- var init_decrypt5 = __esm({
3289
- "node_modules/jose/dist/webapi/jwt/decrypt.js"() {
3290
- "use strict";
3291
- init_cjs_shims();
3292
- init_decrypt3();
3293
- init_jwt_claims_set();
3294
- init_errors();
3295
- }
3296
- });
3297
-
3298
- // node_modules/jose/dist/webapi/jwe/compact/encrypt.js
3299
- var CompactEncrypt;
3300
- var init_encrypt4 = __esm({
3301
- "node_modules/jose/dist/webapi/jwe/compact/encrypt.js"() {
3302
- "use strict";
3303
- init_cjs_shims();
3304
- init_encrypt2();
3305
- CompactEncrypt = class {
3306
- #flattened;
3307
- constructor(plaintext) {
3308
- this.#flattened = new FlattenedEncrypt(plaintext);
3309
- }
3310
- setContentEncryptionKey(cek) {
3311
- this.#flattened.setContentEncryptionKey(cek);
3312
- return this;
3313
- }
3314
- setInitializationVector(iv) {
3315
- this.#flattened.setInitializationVector(iv);
3316
- return this;
3317
- }
3318
- setProtectedHeader(protectedHeader) {
3319
- this.#flattened.setProtectedHeader(protectedHeader);
3320
- return this;
3321
- }
3322
- setKeyManagementParameters(parameters) {
3323
- this.#flattened.setKeyManagementParameters(parameters);
3324
- return this;
3325
- }
3326
- async encrypt(key, options) {
3327
- const jwe = await this.#flattened.encrypt(key, options);
3328
- return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join(".");
3329
- }
3330
- };
3331
- }
3332
- });
3333
-
3334
- // node_modules/jose/dist/webapi/lib/sign.js
3335
- async function sign(alg, key, data) {
3336
- const cryptoKey = await getSigKey(alg, key, "sign");
3337
- checkKeyLength(alg, cryptoKey);
3338
- const signature = await crypto.subtle.sign(subtleAlgorithm2(alg, cryptoKey.algorithm), cryptoKey, data);
3339
- return new Uint8Array(signature);
3340
- }
3341
- var init_sign = __esm({
3342
- "node_modules/jose/dist/webapi/lib/sign.js"() {
3343
- "use strict";
3344
- init_cjs_shims();
3345
- init_subtle_dsa();
3346
- init_check_key_length();
3347
- init_get_sign_verify_key();
3348
- }
3349
- });
3350
-
3351
- // node_modules/jose/dist/webapi/jws/flattened/sign.js
3352
- var FlattenedSign;
3353
- var init_sign2 = __esm({
3354
- "node_modules/jose/dist/webapi/jws/flattened/sign.js"() {
3355
- "use strict";
3356
- init_cjs_shims();
3357
- init_base64url();
3358
- init_sign();
3359
- init_is_disjoint();
3360
- init_errors();
3361
- init_buffer_utils();
3362
- init_check_key_type();
3363
- init_validate_crit();
3364
- init_normalize_key();
3365
- FlattenedSign = class {
3366
- #payload;
3367
- #protectedHeader;
3368
- #unprotectedHeader;
3369
- constructor(payload) {
3370
- if (!(payload instanceof Uint8Array)) {
3371
- throw new TypeError("payload must be an instance of Uint8Array");
3372
- }
3373
- this.#payload = payload;
3374
- }
3375
- setProtectedHeader(protectedHeader) {
3376
- if (this.#protectedHeader) {
3377
- throw new TypeError("setProtectedHeader can only be called once");
3378
- }
3379
- this.#protectedHeader = protectedHeader;
3380
- return this;
3381
- }
3382
- setUnprotectedHeader(unprotectedHeader) {
3383
- if (this.#unprotectedHeader) {
3384
- throw new TypeError("setUnprotectedHeader can only be called once");
3385
- }
3386
- this.#unprotectedHeader = unprotectedHeader;
3387
- return this;
3388
- }
3389
- async sign(key, options) {
3390
- if (!this.#protectedHeader && !this.#unprotectedHeader) {
3391
- throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
3392
- }
3393
- if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {
3394
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
3395
- }
3396
- const joseHeader = {
3397
- ...this.#protectedHeader,
3398
- ...this.#unprotectedHeader
3399
- };
3400
- const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
3401
- let b64 = true;
3402
- if (extensions.has("b64")) {
3403
- b64 = this.#protectedHeader.b64;
3404
- if (typeof b64 !== "boolean") {
3405
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
3406
- }
3407
- }
3408
- const { alg } = joseHeader;
3409
- if (typeof alg !== "string" || !alg) {
3410
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
3411
- }
3412
- checkKeyType(alg, key, "sign");
3413
- let payloadS;
3414
- let payloadB;
3415
- if (b64) {
3416
- payloadS = encode2(this.#payload);
3417
- payloadB = encode(payloadS);
3418
- } else {
3419
- payloadB = this.#payload;
3420
- payloadS = "";
3421
- }
3422
- let protectedHeaderString;
3423
- let protectedHeaderBytes;
3424
- if (this.#protectedHeader) {
3425
- protectedHeaderString = encode2(JSON.stringify(this.#protectedHeader));
3426
- protectedHeaderBytes = encode(protectedHeaderString);
3427
- } else {
3428
- protectedHeaderString = "";
3429
- protectedHeaderBytes = new Uint8Array();
3430
- }
3431
- const data = concat(protectedHeaderBytes, encode("."), payloadB);
3432
- const k = await normalizeKey(key, alg);
3433
- const signature = await sign(alg, k, data);
3434
- const jws = {
3435
- signature: encode2(signature),
3436
- payload: payloadS
3437
- };
3438
- if (this.#unprotectedHeader) {
3439
- jws.header = this.#unprotectedHeader;
3440
- }
3441
- if (this.#protectedHeader) {
3442
- jws.protected = protectedHeaderString;
3443
- }
3444
- return jws;
3445
- }
3446
- };
3447
- }
3448
- });
3449
-
3450
- // node_modules/jose/dist/webapi/jws/compact/sign.js
3451
- var CompactSign;
3452
- var init_sign3 = __esm({
3453
- "node_modules/jose/dist/webapi/jws/compact/sign.js"() {
3454
- "use strict";
3455
- init_cjs_shims();
3456
- init_sign2();
3457
- CompactSign = class {
3458
- #flattened;
3459
- constructor(payload) {
3460
- this.#flattened = new FlattenedSign(payload);
3461
- }
3462
- setProtectedHeader(protectedHeader) {
3463
- this.#flattened.setProtectedHeader(protectedHeader);
3464
- return this;
3465
- }
3466
- async sign(key, options) {
3467
- const jws = await this.#flattened.sign(key, options);
3468
- if (jws.payload === void 0) {
3469
- throw new TypeError("use the flattened module for creating JWS with b64: false");
3470
- }
3471
- return `${jws.protected}.${jws.payload}.${jws.signature}`;
3472
- }
3473
- };
3474
- }
3475
- });
3476
-
3477
- // node_modules/jose/dist/webapi/jws/general/sign.js
3478
- var IndividualSignature, GeneralSign;
3479
- var init_sign4 = __esm({
3480
- "node_modules/jose/dist/webapi/jws/general/sign.js"() {
3481
- "use strict";
3482
- init_cjs_shims();
3483
- init_sign2();
3484
- init_errors();
3485
- IndividualSignature = class {
3486
- #parent;
3487
- protectedHeader;
3488
- unprotectedHeader;
3489
- options;
3490
- key;
3491
- constructor(sig, key, options) {
3492
- this.#parent = sig;
3493
- this.key = key;
3494
- this.options = options;
3495
- }
3496
- setProtectedHeader(protectedHeader) {
3497
- if (this.protectedHeader) {
3498
- throw new TypeError("setProtectedHeader can only be called once");
3499
- }
3500
- this.protectedHeader = protectedHeader;
3501
- return this;
3502
- }
3503
- setUnprotectedHeader(unprotectedHeader) {
3504
- if (this.unprotectedHeader) {
3505
- throw new TypeError("setUnprotectedHeader can only be called once");
3506
- }
3507
- this.unprotectedHeader = unprotectedHeader;
3508
- return this;
3509
- }
3510
- addSignature(...args) {
3511
- return this.#parent.addSignature(...args);
3512
- }
3513
- sign(...args) {
3514
- return this.#parent.sign(...args);
3515
- }
3516
- done() {
3517
- return this.#parent;
3518
- }
3519
- };
3520
- GeneralSign = class {
3521
- #payload;
3522
- #signatures = [];
3523
- constructor(payload) {
3524
- this.#payload = payload;
3525
- }
3526
- addSignature(key, options) {
3527
- const signature = new IndividualSignature(this, key, options);
3528
- this.#signatures.push(signature);
3529
- return signature;
3530
- }
3531
- async sign() {
3532
- if (!this.#signatures.length) {
3533
- throw new JWSInvalid("at least one signature must be added");
3534
- }
3535
- const jws = {
3536
- signatures: [],
3537
- payload: ""
3538
- };
3539
- for (let i = 0; i < this.#signatures.length; i++) {
3540
- const signature = this.#signatures[i];
3541
- const flattened = new FlattenedSign(this.#payload);
3542
- flattened.setProtectedHeader(signature.protectedHeader);
3543
- flattened.setUnprotectedHeader(signature.unprotectedHeader);
3544
- const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
3545
- if (i === 0) {
3546
- jws.payload = payload;
3547
- } else if (jws.payload !== payload) {
3548
- throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");
3549
- }
3550
- jws.signatures.push(rest);
3551
- }
3552
- return jws;
3553
- }
3554
- };
3555
- }
3556
- });
3557
-
3558
- // node_modules/jose/dist/webapi/jwt/sign.js
3559
- var SignJWT;
3560
- var init_sign5 = __esm({
3561
- "node_modules/jose/dist/webapi/jwt/sign.js"() {
3562
- "use strict";
3563
- init_cjs_shims();
3564
- init_sign3();
3565
- init_errors();
3566
- init_jwt_claims_set();
3567
- SignJWT = class {
3568
- #protectedHeader;
3569
- #jwt;
3570
- constructor(payload = {}) {
3571
- this.#jwt = new JWTClaimsBuilder(payload);
3572
- }
3573
- setIssuer(issuer) {
3574
- this.#jwt.iss = issuer;
3575
- return this;
3576
- }
3577
- setSubject(subject) {
3578
- this.#jwt.sub = subject;
3579
- return this;
3580
- }
3581
- setAudience(audience) {
3582
- this.#jwt.aud = audience;
3583
- return this;
3584
- }
3585
- setJti(jwtId) {
3586
- this.#jwt.jti = jwtId;
3587
- return this;
3588
- }
3589
- setNotBefore(input) {
3590
- this.#jwt.nbf = input;
3591
- return this;
3592
- }
3593
- setExpirationTime(input) {
3594
- this.#jwt.exp = input;
3595
- return this;
3596
- }
3597
- setIssuedAt(input) {
3598
- this.#jwt.iat = input;
3599
- return this;
3600
- }
3601
- setProtectedHeader(protectedHeader) {
3602
- this.#protectedHeader = protectedHeader;
3603
- return this;
3604
- }
3605
- async sign(key, options) {
3606
- const sig = new CompactSign(this.#jwt.data());
3607
- sig.setProtectedHeader(this.#protectedHeader);
3608
- if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) {
3609
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3610
- }
3611
- return sig.sign(key, options);
3612
- }
3613
- };
3614
- }
3615
- });
3616
-
3617
- // node_modules/jose/dist/webapi/jwt/encrypt.js
3618
- var EncryptJWT;
3619
- var init_encrypt5 = __esm({
3620
- "node_modules/jose/dist/webapi/jwt/encrypt.js"() {
3621
- "use strict";
3622
- init_cjs_shims();
3623
- init_encrypt4();
3624
- init_jwt_claims_set();
3625
- EncryptJWT = class {
3626
- #cek;
3627
- #iv;
3628
- #keyManagementParameters;
3629
- #protectedHeader;
3630
- #replicateIssuerAsHeader;
3631
- #replicateSubjectAsHeader;
3632
- #replicateAudienceAsHeader;
3633
- #jwt;
3634
- constructor(payload = {}) {
3635
- this.#jwt = new JWTClaimsBuilder(payload);
3636
- }
3637
- setIssuer(issuer) {
3638
- this.#jwt.iss = issuer;
3639
- return this;
3640
- }
3641
- setSubject(subject) {
3642
- this.#jwt.sub = subject;
3643
- return this;
3644
- }
3645
- setAudience(audience) {
3646
- this.#jwt.aud = audience;
3647
- return this;
3648
- }
3649
- setJti(jwtId) {
3650
- this.#jwt.jti = jwtId;
3651
- return this;
3652
- }
3653
- setNotBefore(input) {
3654
- this.#jwt.nbf = input;
3655
- return this;
3656
- }
3657
- setExpirationTime(input) {
3658
- this.#jwt.exp = input;
3659
- return this;
3660
- }
3661
- setIssuedAt(input) {
3662
- this.#jwt.iat = input;
3663
- return this;
3664
- }
3665
- setProtectedHeader(protectedHeader) {
3666
- if (this.#protectedHeader) {
3667
- throw new TypeError("setProtectedHeader can only be called once");
3668
- }
3669
- this.#protectedHeader = protectedHeader;
3670
- return this;
3671
- }
3672
- setKeyManagementParameters(parameters) {
3673
- if (this.#keyManagementParameters) {
3674
- throw new TypeError("setKeyManagementParameters can only be called once");
3675
- }
3676
- this.#keyManagementParameters = parameters;
3677
- return this;
3678
- }
3679
- setContentEncryptionKey(cek) {
3680
- if (this.#cek) {
3681
- throw new TypeError("setContentEncryptionKey can only be called once");
3682
- }
3683
- this.#cek = cek;
3684
- return this;
3685
- }
3686
- setInitializationVector(iv) {
3687
- if (this.#iv) {
3688
- throw new TypeError("setInitializationVector can only be called once");
3689
- }
3690
- this.#iv = iv;
3691
- return this;
3692
- }
3693
- replicateIssuerAsHeader() {
3694
- this.#replicateIssuerAsHeader = true;
3695
- return this;
3696
- }
3697
- replicateSubjectAsHeader() {
3698
- this.#replicateSubjectAsHeader = true;
3699
- return this;
3700
- }
3701
- replicateAudienceAsHeader() {
3702
- this.#replicateAudienceAsHeader = true;
3703
- return this;
3704
- }
3705
- async encrypt(key, options) {
3706
- const enc = new CompactEncrypt(this.#jwt.data());
3707
- if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) {
3708
- this.#protectedHeader = {
3709
- ...this.#protectedHeader,
3710
- iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : void 0,
3711
- sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : void 0,
3712
- aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : void 0
3713
- };
3714
- }
3715
- enc.setProtectedHeader(this.#protectedHeader);
3716
- if (this.#iv) {
3717
- enc.setInitializationVector(this.#iv);
3718
- }
3719
- if (this.#cek) {
3720
- enc.setContentEncryptionKey(this.#cek);
3721
- }
3722
- if (this.#keyManagementParameters) {
3723
- enc.setKeyManagementParameters(this.#keyManagementParameters);
3724
- }
3725
- return enc.encrypt(key, options);
3726
- }
3727
- };
3728
- }
3729
- });
3730
-
3731
- // node_modules/jose/dist/webapi/jwk/thumbprint.js
3732
- async function calculateJwkThumbprint(key, digestAlgorithm) {
3733
- let jwk;
3734
- if (isJWK(key)) {
3735
- jwk = key;
3736
- } else if (isKeyLike(key)) {
3737
- jwk = await exportJWK(key);
3738
- } else {
3739
- throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
3740
- }
3741
- digestAlgorithm ??= "sha256";
3742
- if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") {
3743
- throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
3744
- }
3745
- let components;
3746
- switch (jwk.kty) {
3747
- case "AKP":
3748
- check(jwk.alg, '"alg" (Algorithm) Parameter');
3749
- check(jwk.pub, '"pub" (Public key) Parameter');
3750
- components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
3751
- break;
3752
- case "EC":
3753
- check(jwk.crv, '"crv" (Curve) Parameter');
3754
- check(jwk.x, '"x" (X Coordinate) Parameter');
3755
- check(jwk.y, '"y" (Y Coordinate) Parameter');
3756
- components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
3757
- break;
3758
- case "OKP":
3759
- check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
3760
- check(jwk.x, '"x" (Public Key) Parameter');
3761
- components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
3762
- break;
3763
- case "RSA":
3764
- check(jwk.e, '"e" (Exponent) Parameter');
3765
- check(jwk.n, '"n" (Modulus) Parameter');
3766
- components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
3767
- break;
3768
- case "oct":
3769
- check(jwk.k, '"k" (Key Value) Parameter');
3770
- components = { k: jwk.k, kty: jwk.kty };
3771
- break;
3772
- default:
3773
- throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
3774
- }
3775
- const data = encode(JSON.stringify(components));
3776
- return encode2(await digest(digestAlgorithm, data));
3777
- }
3778
- async function calculateJwkThumbprintUri(key, digestAlgorithm) {
3779
- digestAlgorithm ??= "sha256";
3780
- const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);
3781
- return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
3782
- }
3783
- var check;
3784
- var init_thumbprint = __esm({
3785
- "node_modules/jose/dist/webapi/jwk/thumbprint.js"() {
3786
- "use strict";
3787
- init_cjs_shims();
3788
- init_digest();
3789
- init_base64url();
3790
- init_errors();
3791
- init_buffer_utils();
3792
- init_is_key_like();
3793
- init_is_jwk();
3794
- init_export();
3795
- init_invalid_key_input();
3796
- check = (value, description) => {
3797
- if (typeof value !== "string" || !value) {
3798
- throw new JWKInvalid(`${description} missing or invalid`);
3799
- }
3800
- };
3801
- }
3802
- });
3803
-
3804
- // node_modules/jose/dist/webapi/jwk/embedded.js
3805
- async function EmbeddedJWK(protectedHeader, token) {
3806
- const joseHeader = {
3807
- ...protectedHeader,
3808
- ...token?.header
3809
- };
3810
- if (!isObject(joseHeader.jwk)) {
3811
- throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
3812
- }
3813
- const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
3814
- if (key instanceof Uint8Array || key.type !== "public") {
3815
- throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
3816
- }
3817
- return key;
3818
- }
3819
- var init_embedded = __esm({
3820
- "node_modules/jose/dist/webapi/jwk/embedded.js"() {
3821
- "use strict";
3822
- init_cjs_shims();
3823
- init_import();
3824
- init_is_object();
3825
- init_errors();
3826
- }
3827
- });
3828
-
3829
- // node_modules/jose/dist/webapi/jwks/local.js
3830
- function getKtyFromAlg(alg) {
3831
- switch (typeof alg === "string" && alg.slice(0, 2)) {
3832
- case "RS":
3833
- case "PS":
3834
- return "RSA";
3835
- case "ES":
3836
- return "EC";
3837
- case "Ed":
3838
- return "OKP";
3839
- case "ML":
3840
- return "AKP";
3841
- default:
3842
- throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
3843
- }
3844
- }
3845
- function isJWKSLike(jwks) {
3846
- return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
3847
- }
3848
- function isJWKLike(key) {
3849
- return isObject(key);
3850
- }
3851
- async function importWithAlgCache(cache2, jwk, alg) {
3852
- const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk);
3853
- if (cached[alg] === void 0) {
3854
- const key = await importJWK({ ...jwk, ext: true }, alg);
3855
- if (key instanceof Uint8Array || key.type !== "public") {
3856
- throw new JWKSInvalid("JSON Web Key Set members must be public keys");
3857
- }
3858
- cached[alg] = key;
3859
- }
3860
- return cached[alg];
3861
- }
3862
- function createLocalJWKSet(jwks) {
3863
- const set = new LocalJWKSet(jwks);
3864
- const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
3865
- Object.defineProperties(localJWKSet, {
3866
- jwks: {
3867
- value: () => structuredClone(set.jwks()),
3868
- enumerable: false,
3869
- configurable: false,
3870
- writable: false
3871
- }
3872
- });
3873
- return localJWKSet;
3874
- }
3875
- var LocalJWKSet;
3876
- var init_local = __esm({
3877
- "node_modules/jose/dist/webapi/jwks/local.js"() {
3878
- "use strict";
3879
- init_cjs_shims();
3880
- init_import();
3881
- init_errors();
3882
- init_is_object();
3883
- LocalJWKSet = class {
3884
- #jwks;
3885
- #cached = /* @__PURE__ */ new WeakMap();
3886
- constructor(jwks) {
3887
- if (!isJWKSLike(jwks)) {
3888
- throw new JWKSInvalid("JSON Web Key Set malformed");
3889
- }
3890
- this.#jwks = structuredClone(jwks);
3891
- }
3892
- jwks() {
3893
- return this.#jwks;
3894
- }
3895
- async getKey(protectedHeader, token) {
3896
- const { alg, kid } = { ...protectedHeader, ...token?.header };
3897
- const kty = getKtyFromAlg(alg);
3898
- const candidates = this.#jwks.keys.filter((jwk2) => {
3899
- let candidate = kty === jwk2.kty;
3900
- if (candidate && typeof kid === "string") {
3901
- candidate = kid === jwk2.kid;
3902
- }
3903
- if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) {
3904
- candidate = alg === jwk2.alg;
3905
- }
3906
- if (candidate && typeof jwk2.use === "string") {
3907
- candidate = jwk2.use === "sig";
3908
- }
3909
- if (candidate && Array.isArray(jwk2.key_ops)) {
3910
- candidate = jwk2.key_ops.includes("verify");
3911
- }
3912
- if (candidate) {
3913
- switch (alg) {
3914
- case "ES256":
3915
- candidate = jwk2.crv === "P-256";
3916
- break;
3917
- case "ES384":
3918
- candidate = jwk2.crv === "P-384";
3919
- break;
3920
- case "ES512":
3921
- candidate = jwk2.crv === "P-521";
3922
- break;
3923
- case "Ed25519":
3924
- case "EdDSA":
3925
- candidate = jwk2.crv === "Ed25519";
3926
- break;
3927
- }
3928
- }
3929
- return candidate;
3930
- });
3931
- const { 0: jwk, length } = candidates;
3932
- if (length === 0) {
3933
- throw new JWKSNoMatchingKey();
3934
- }
3935
- if (length !== 1) {
3936
- const error = new JWKSMultipleMatchingKeys();
3937
- const _cached = this.#cached;
3938
- error[Symbol.asyncIterator] = async function* () {
3939
- for (const jwk2 of candidates) {
3940
- try {
3941
- yield await importWithAlgCache(_cached, jwk2, alg);
3942
- } catch {
3943
- }
3944
- }
3945
- };
3946
- throw error;
3947
- }
3948
- return importWithAlgCache(this.#cached, jwk, alg);
3949
- }
3950
- };
3951
- }
3952
- });
3953
-
3954
- // node_modules/jose/dist/webapi/jwks/remote.js
3955
- function isCloudflareWorkers() {
3956
- return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
3957
- }
3958
- async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
3959
- const response = await fetchImpl(url, {
3960
- method: "GET",
3961
- signal,
3962
- redirect: "manual",
3963
- headers
3964
- }).catch((err) => {
3965
- if (err.name === "TimeoutError") {
3966
- throw new JWKSTimeout();
3967
- }
3968
- throw err;
3969
- });
3970
- if (response.status !== 200) {
3971
- throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
3972
- }
3973
- try {
3974
- return await response.json();
3975
- } catch {
3976
- throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
3977
- }
3978
- }
3979
- function isFreshJwksCache(input, cacheMaxAge) {
3980
- if (typeof input !== "object" || input === null) {
3981
- return false;
3982
- }
3983
- if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) {
3984
- return false;
3985
- }
3986
- if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) {
3987
- return false;
3988
- }
3989
- return true;
3990
- }
3991
- function createRemoteJWKSet(url, options) {
3992
- const set = new RemoteJWKSet(url, options);
3993
- const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
3994
- Object.defineProperties(remoteJWKSet, {
3995
- coolingDown: {
3996
- get: () => set.coolingDown(),
3997
- enumerable: true,
3998
- configurable: false
3999
- },
4000
- fresh: {
4001
- get: () => set.fresh(),
4002
- enumerable: true,
4003
- configurable: false
4004
- },
4005
- reload: {
4006
- value: () => set.reload(),
4007
- enumerable: true,
4008
- configurable: false,
4009
- writable: false
4010
- },
4011
- reloading: {
4012
- get: () => set.pendingFetch(),
4013
- enumerable: true,
4014
- configurable: false
4015
- },
4016
- jwks: {
4017
- value: () => set.jwks(),
4018
- enumerable: true,
4019
- configurable: false,
4020
- writable: false
4021
- }
4022
- });
4023
- return remoteJWKSet;
4024
- }
4025
- var USER_AGENT, customFetch, jwksCache, RemoteJWKSet;
4026
- var init_remote = __esm({
4027
- "node_modules/jose/dist/webapi/jwks/remote.js"() {
4028
- "use strict";
4029
- init_cjs_shims();
4030
- init_errors();
4031
- init_local();
4032
- init_is_object();
4033
- if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
4034
- const NAME = "jose";
4035
- const VERSION = "v6.1.3";
4036
- USER_AGENT = `${NAME}/${VERSION}`;
4037
- }
4038
- customFetch = /* @__PURE__ */ Symbol();
4039
- jwksCache = /* @__PURE__ */ Symbol();
4040
- RemoteJWKSet = class {
4041
- #url;
4042
- #timeoutDuration;
4043
- #cooldownDuration;
4044
- #cacheMaxAge;
4045
- #jwksTimestamp;
4046
- #pendingFetch;
4047
- #headers;
4048
- #customFetch;
4049
- #local;
4050
- #cache;
4051
- constructor(url, options) {
4052
- if (!(url instanceof URL)) {
4053
- throw new TypeError("url must be an instance of URL");
4054
- }
4055
- this.#url = new URL(url.href);
4056
- this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
4057
- this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
4058
- this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
4059
- this.#headers = new Headers(options?.headers);
4060
- if (USER_AGENT && !this.#headers.has("User-Agent")) {
4061
- this.#headers.set("User-Agent", USER_AGENT);
4062
- }
4063
- if (!this.#headers.has("accept")) {
4064
- this.#headers.set("accept", "application/json");
4065
- this.#headers.append("accept", "application/jwk-set+json");
4066
- }
4067
- this.#customFetch = options?.[customFetch];
4068
- if (options?.[jwksCache] !== void 0) {
4069
- this.#cache = options?.[jwksCache];
4070
- if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
4071
- this.#jwksTimestamp = this.#cache.uat;
4072
- this.#local = createLocalJWKSet(this.#cache.jwks);
4073
- }
4074
- }
4075
- }
4076
- pendingFetch() {
4077
- return !!this.#pendingFetch;
4078
- }
4079
- coolingDown() {
4080
- return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false;
4081
- }
4082
- fresh() {
4083
- return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false;
4084
- }
4085
- jwks() {
4086
- return this.#local?.jwks();
4087
- }
4088
- async getKey(protectedHeader, token) {
4089
- if (!this.#local || !this.fresh()) {
4090
- await this.reload();
4091
- }
4092
- try {
4093
- return await this.#local(protectedHeader, token);
4094
- } catch (err) {
4095
- if (err instanceof JWKSNoMatchingKey) {
4096
- if (this.coolingDown() === false) {
4097
- await this.reload();
4098
- return this.#local(protectedHeader, token);
4099
- }
4100
- }
4101
- throw err;
4102
- }
4103
- }
4104
- async reload() {
4105
- if (this.#pendingFetch && isCloudflareWorkers()) {
4106
- this.#pendingFetch = void 0;
4107
- }
4108
- this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => {
4109
- this.#local = createLocalJWKSet(json);
4110
- if (this.#cache) {
4111
- this.#cache.uat = Date.now();
4112
- this.#cache.jwks = json;
4113
- }
4114
- this.#jwksTimestamp = Date.now();
4115
- this.#pendingFetch = void 0;
4116
- }).catch((err) => {
4117
- this.#pendingFetch = void 0;
4118
- throw err;
4119
- });
4120
- await this.#pendingFetch;
4121
- }
4122
- };
4123
- }
4124
- });
4125
-
4126
- // node_modules/jose/dist/webapi/jwt/unsecured.js
4127
- var UnsecuredJWT;
4128
- var init_unsecured = __esm({
4129
- "node_modules/jose/dist/webapi/jwt/unsecured.js"() {
4130
- "use strict";
4131
- init_cjs_shims();
4132
- init_base64url();
4133
- init_buffer_utils();
4134
- init_errors();
4135
- init_jwt_claims_set();
4136
- UnsecuredJWT = class {
4137
- #jwt;
4138
- constructor(payload = {}) {
4139
- this.#jwt = new JWTClaimsBuilder(payload);
4140
- }
4141
- encode() {
4142
- const header = encode2(JSON.stringify({ alg: "none" }));
4143
- const payload = encode2(this.#jwt.data());
4144
- return `${header}.${payload}.`;
4145
- }
4146
- setIssuer(issuer) {
4147
- this.#jwt.iss = issuer;
4148
- return this;
4149
- }
4150
- setSubject(subject) {
4151
- this.#jwt.sub = subject;
4152
- return this;
4153
- }
4154
- setAudience(audience) {
4155
- this.#jwt.aud = audience;
4156
- return this;
4157
- }
4158
- setJti(jwtId) {
4159
- this.#jwt.jti = jwtId;
4160
- return this;
4161
- }
4162
- setNotBefore(input) {
4163
- this.#jwt.nbf = input;
4164
- return this;
4165
- }
4166
- setExpirationTime(input) {
4167
- this.#jwt.exp = input;
4168
- return this;
4169
- }
4170
- setIssuedAt(input) {
4171
- this.#jwt.iat = input;
4172
- return this;
4173
- }
4174
- static decode(jwt, options) {
4175
- if (typeof jwt !== "string") {
4176
- throw new JWTInvalid("Unsecured JWT must be a string");
4177
- }
4178
- const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split(".");
4179
- if (length !== 3 || signature !== "") {
4180
- throw new JWTInvalid("Invalid Unsecured JWT");
4181
- }
4182
- let header;
4183
- try {
4184
- header = JSON.parse(decoder.decode(decode(encodedHeader)));
4185
- if (header.alg !== "none")
4186
- throw new Error();
4187
- } catch {
4188
- throw new JWTInvalid("Invalid Unsecured JWT");
4189
- }
4190
- const payload = validateClaimsSet(header, decode(encodedPayload), options);
4191
- return { payload, header };
4192
- }
4193
- };
4194
- }
4195
- });
4196
-
4197
- // node_modules/jose/dist/webapi/util/decode_protected_header.js
4198
- function decodeProtectedHeader(token) {
4199
- let protectedB64u;
4200
- if (typeof token === "string") {
4201
- const parts = token.split(".");
4202
- if (parts.length === 3 || parts.length === 5) {
4203
- ;
4204
- [protectedB64u] = parts;
4205
- }
4206
- } else if (typeof token === "object" && token) {
4207
- if ("protected" in token) {
4208
- protectedB64u = token.protected;
4209
- } else {
4210
- throw new TypeError("Token does not contain a Protected Header");
4211
- }
4212
- }
4213
- try {
4214
- if (typeof protectedB64u !== "string" || !protectedB64u) {
4215
- throw new Error();
4216
- }
4217
- const result = JSON.parse(decoder.decode(decode(protectedB64u)));
4218
- if (!isObject(result)) {
4219
- throw new Error();
4220
- }
4221
- return result;
4222
- } catch {
4223
- throw new TypeError("Invalid Token or Protected Header formatting");
4224
- }
4225
- }
4226
- var init_decode_protected_header = __esm({
4227
- "node_modules/jose/dist/webapi/util/decode_protected_header.js"() {
4228
- "use strict";
4229
- init_cjs_shims();
4230
- init_base64url();
4231
- init_buffer_utils();
4232
- init_is_object();
4233
- }
4234
- });
4235
-
4236
- // node_modules/jose/dist/webapi/util/decode_jwt.js
4237
- function decodeJwt(jwt) {
4238
- if (typeof jwt !== "string")
4239
- throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
4240
- const { 1: payload, length } = jwt.split(".");
4241
- if (length === 5)
4242
- throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
4243
- if (length !== 3)
4244
- throw new JWTInvalid("Invalid JWT");
4245
- if (!payload)
4246
- throw new JWTInvalid("JWTs must contain a payload");
4247
- let decoded;
4248
- try {
4249
- decoded = decode(payload);
4250
- } catch {
4251
- throw new JWTInvalid("Failed to base64url decode the payload");
4252
- }
4253
- let result;
4254
- try {
4255
- result = JSON.parse(decoder.decode(decoded));
4256
- } catch {
4257
- throw new JWTInvalid("Failed to parse the decoded payload as JSON");
4258
- }
4259
- if (!isObject(result))
4260
- throw new JWTInvalid("Invalid JWT Claims Set");
4261
- return result;
4262
- }
4263
- var init_decode_jwt = __esm({
4264
- "node_modules/jose/dist/webapi/util/decode_jwt.js"() {
4265
- "use strict";
4266
- init_cjs_shims();
4267
- init_base64url();
4268
- init_buffer_utils();
4269
- init_is_object();
4270
- init_errors();
4271
- }
4272
- });
4273
-
4274
- // node_modules/jose/dist/webapi/key/generate_key_pair.js
4275
- function getModulusLengthOption(options) {
4276
- const modulusLength = options?.modulusLength ?? 2048;
4277
- if (typeof modulusLength !== "number" || modulusLength < 2048) {
4278
- throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
4279
- }
4280
- return modulusLength;
4281
- }
4282
- async function generateKeyPair(alg, options) {
4283
- let algorithm;
4284
- let keyUsages;
4285
- switch (alg) {
4286
- case "PS256":
4287
- case "PS384":
4288
- case "PS512":
4289
- algorithm = {
4290
- name: "RSA-PSS",
4291
- hash: `SHA-${alg.slice(-3)}`,
4292
- publicExponent: Uint8Array.of(1, 0, 1),
4293
- modulusLength: getModulusLengthOption(options)
4294
- };
4295
- keyUsages = ["sign", "verify"];
4296
- break;
4297
- case "RS256":
4298
- case "RS384":
4299
- case "RS512":
4300
- algorithm = {
4301
- name: "RSASSA-PKCS1-v1_5",
4302
- hash: `SHA-${alg.slice(-3)}`,
4303
- publicExponent: Uint8Array.of(1, 0, 1),
4304
- modulusLength: getModulusLengthOption(options)
4305
- };
4306
- keyUsages = ["sign", "verify"];
4307
- break;
4308
- case "RSA-OAEP":
4309
- case "RSA-OAEP-256":
4310
- case "RSA-OAEP-384":
4311
- case "RSA-OAEP-512":
4312
- algorithm = {
4313
- name: "RSA-OAEP",
4314
- hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
4315
- publicExponent: Uint8Array.of(1, 0, 1),
4316
- modulusLength: getModulusLengthOption(options)
4317
- };
4318
- keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"];
4319
- break;
4320
- case "ES256":
4321
- algorithm = { name: "ECDSA", namedCurve: "P-256" };
4322
- keyUsages = ["sign", "verify"];
4323
- break;
4324
- case "ES384":
4325
- algorithm = { name: "ECDSA", namedCurve: "P-384" };
4326
- keyUsages = ["sign", "verify"];
4327
- break;
4328
- case "ES512":
4329
- algorithm = { name: "ECDSA", namedCurve: "P-521" };
4330
- keyUsages = ["sign", "verify"];
4331
- break;
4332
- case "Ed25519":
4333
- case "EdDSA": {
4334
- keyUsages = ["sign", "verify"];
4335
- algorithm = { name: "Ed25519" };
4336
- break;
4337
- }
4338
- case "ML-DSA-44":
4339
- case "ML-DSA-65":
4340
- case "ML-DSA-87": {
4341
- keyUsages = ["sign", "verify"];
4342
- algorithm = { name: alg };
4343
- break;
4344
- }
4345
- case "ECDH-ES":
4346
- case "ECDH-ES+A128KW":
4347
- case "ECDH-ES+A192KW":
4348
- case "ECDH-ES+A256KW": {
4349
- keyUsages = ["deriveBits"];
4350
- const crv = options?.crv ?? "P-256";
4351
- switch (crv) {
4352
- case "P-256":
4353
- case "P-384":
4354
- case "P-521": {
4355
- algorithm = { name: "ECDH", namedCurve: crv };
4356
- break;
4357
- }
4358
- case "X25519":
4359
- algorithm = { name: "X25519" };
4360
- break;
4361
- default:
4362
- throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
4363
- }
4364
- break;
4365
- }
4366
- default:
4367
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
4368
- }
4369
- return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
4370
- }
4371
- var init_generate_key_pair = __esm({
4372
- "node_modules/jose/dist/webapi/key/generate_key_pair.js"() {
4373
- "use strict";
4374
- init_cjs_shims();
4375
- init_errors();
4376
- }
4377
- });
4378
-
4379
- // node_modules/jose/dist/webapi/key/generate_secret.js
4380
- async function generateSecret(alg, options) {
4381
- let length;
4382
- let algorithm;
4383
- let keyUsages;
4384
- switch (alg) {
4385
- case "HS256":
4386
- case "HS384":
4387
- case "HS512":
4388
- length = parseInt(alg.slice(-3), 10);
4389
- algorithm = { name: "HMAC", hash: `SHA-${length}`, length };
4390
- keyUsages = ["sign", "verify"];
4391
- break;
4392
- case "A128CBC-HS256":
4393
- case "A192CBC-HS384":
4394
- case "A256CBC-HS512":
4395
- length = parseInt(alg.slice(-3), 10);
4396
- return crypto.getRandomValues(new Uint8Array(length >> 3));
4397
- case "A128KW":
4398
- case "A192KW":
4399
- case "A256KW":
4400
- length = parseInt(alg.slice(1, 4), 10);
4401
- algorithm = { name: "AES-KW", length };
4402
- keyUsages = ["wrapKey", "unwrapKey"];
4403
- break;
4404
- case "A128GCMKW":
4405
- case "A192GCMKW":
4406
- case "A256GCMKW":
4407
- case "A128GCM":
4408
- case "A192GCM":
4409
- case "A256GCM":
4410
- length = parseInt(alg.slice(1, 4), 10);
4411
- algorithm = { name: "AES-GCM", length };
4412
- keyUsages = ["encrypt", "decrypt"];
4413
- break;
4414
- default:
4415
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
4416
- }
4417
- return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
4418
- }
4419
- var init_generate_secret = __esm({
4420
- "node_modules/jose/dist/webapi/key/generate_secret.js"() {
4421
- "use strict";
4422
- init_cjs_shims();
4423
- init_errors();
4424
- }
4425
- });
4426
-
4427
- // node_modules/jose/dist/webapi/index.js
4428
- var webapi_exports = {};
4429
- __export(webapi_exports, {
4430
- CompactEncrypt: () => CompactEncrypt,
4431
- CompactSign: () => CompactSign,
4432
- EmbeddedJWK: () => EmbeddedJWK,
4433
- EncryptJWT: () => EncryptJWT,
4434
- FlattenedEncrypt: () => FlattenedEncrypt,
4435
- FlattenedSign: () => FlattenedSign,
4436
- GeneralEncrypt: () => GeneralEncrypt,
4437
- GeneralSign: () => GeneralSign,
4438
- SignJWT: () => SignJWT,
4439
- UnsecuredJWT: () => UnsecuredJWT,
4440
- base64url: () => base64url_exports,
4441
- calculateJwkThumbprint: () => calculateJwkThumbprint,
4442
- calculateJwkThumbprintUri: () => calculateJwkThumbprintUri,
4443
- compactDecrypt: () => compactDecrypt,
4444
- compactVerify: () => compactVerify,
4445
- createLocalJWKSet: () => createLocalJWKSet,
4446
- createRemoteJWKSet: () => createRemoteJWKSet,
4447
- cryptoRuntime: () => cryptoRuntime,
4448
- customFetch: () => customFetch,
4449
- decodeJwt: () => decodeJwt,
4450
- decodeProtectedHeader: () => decodeProtectedHeader,
4451
- errors: () => errors_exports,
4452
- exportJWK: () => exportJWK,
4453
- exportPKCS8: () => exportPKCS8,
4454
- exportSPKI: () => exportSPKI,
4455
- flattenedDecrypt: () => flattenedDecrypt,
4456
- flattenedVerify: () => flattenedVerify,
4457
- generalDecrypt: () => generalDecrypt,
4458
- generalVerify: () => generalVerify,
4459
- generateKeyPair: () => generateKeyPair,
4460
- generateSecret: () => generateSecret,
4461
- importJWK: () => importJWK,
4462
- importPKCS8: () => importPKCS8,
4463
- importSPKI: () => importSPKI,
4464
- importX509: () => importX509,
4465
- jwksCache: () => jwksCache,
4466
- jwtDecrypt: () => jwtDecrypt,
4467
- jwtVerify: () => jwtVerify
4468
- });
4469
- var cryptoRuntime;
4470
- var init_webapi = __esm({
4471
- "node_modules/jose/dist/webapi/index.js"() {
4472
- "use strict";
4473
- init_cjs_shims();
4474
- init_decrypt3();
4475
- init_decrypt2();
4476
- init_decrypt4();
4477
- init_encrypt3();
4478
- init_verify3();
4479
- init_verify2();
4480
- init_verify4();
4481
- init_verify5();
4482
- init_decrypt5();
4483
- init_encrypt4();
4484
- init_encrypt2();
4485
- init_sign3();
4486
- init_sign2();
4487
- init_sign4();
4488
- init_sign5();
4489
- init_encrypt5();
4490
- init_thumbprint();
4491
- init_embedded();
4492
- init_local();
4493
- init_remote();
4494
- init_unsecured();
4495
- init_export();
4496
- init_import();
4497
- init_decode_protected_header();
4498
- init_decode_jwt();
4499
- init_errors();
4500
- init_generate_key_pair();
4501
- init_generate_secret();
4502
- init_base64url();
4503
- cryptoRuntime = "WebCryptoAPI";
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
4504
17
  }
4505
- });
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
4506
28
 
4507
- // src/onramp/index.ts
4508
- var onramp_exports = {};
4509
- __export(onramp_exports, {
4510
- generateOnrampUrl: () => generateOnrampUrl,
4511
- printQRCode: () => printQRCode
4512
- });
4513
- function loadCredentials() {
4514
- let apiKeyId = process.env.CDP_API_KEY_ID;
4515
- let apiKeySecret = process.env.CDP_API_KEY_SECRET;
4516
- if (!apiKeyId || !apiKeySecret) {
4517
- const envPath = (0, import_path2.join)((0, import_os2.homedir)(), ".moltspay", ".env");
4518
- if ((0, import_fs4.existsSync)(envPath)) {
4519
- const envContent = (0, import_fs4.readFileSync)(envPath, "utf-8");
4520
- for (const line of envContent.split("\n")) {
4521
- const [key, ...valueParts] = line.split("=");
4522
- const value = valueParts.join("=").trim();
4523
- if (key === "CDP_API_KEY_ID") apiKeyId = value;
4524
- if (key === "CDP_API_KEY_SECRET") apiKeySecret = value;
4525
- }
4526
- }
4527
- }
4528
- if (!apiKeyId || !apiKeySecret) {
4529
- return null;
4530
- }
4531
- return { apiKeyId, apiKeySecret };
4532
- }
4533
- async function getPublicIp() {
4534
- const response = await fetch("https://api.ipify.org");
4535
- if (!response.ok) {
4536
- throw new Error("Failed to get public IP");
4537
- }
4538
- return (await response.text()).trim();
4539
- }
4540
- async function generateCdpJwt(credentials, method, path3) {
4541
- const { SignJWT: SignJWT2, importJWK: importJWK2 } = await Promise.resolve().then(() => (init_webapi(), webapi_exports));
4542
- const crypto2 = await import("crypto");
4543
- const now = Math.floor(Date.now() / 1e3);
4544
- const nonce = crypto2.randomBytes(16).toString("hex");
4545
- const uri = `${method} api.developer.coinbase.com${path3}`;
4546
- const claims = {
4547
- sub: credentials.apiKeyId,
4548
- iss: "cdp",
4549
- nbf: now,
4550
- exp: now + 120,
4551
- uri
4552
- };
4553
- const decoded = Buffer.from(credentials.apiKeySecret, "base64");
4554
- const seed = decoded.subarray(0, 32);
4555
- const publicKey = decoded.subarray(32);
4556
- const jwk = {
4557
- kty: "OKP",
4558
- crv: "Ed25519",
4559
- d: seed.toString("base64url"),
4560
- x: publicKey.toString("base64url")
4561
- };
4562
- const key = await importJWK2(jwk, "EdDSA");
4563
- return await new SignJWT2(claims).setProtectedHeader({ alg: "EdDSA", kid: credentials.apiKeyId, typ: "JWT", nonce }).sign(key);
4564
- }
4565
- async function getSessionToken(params) {
4566
- const credentials = loadCredentials();
4567
- if (!credentials) {
4568
- throw new Error("CDP credentials not found. Set CDP_API_KEY_ID and CDP_API_KEY_SECRET.");
4569
- }
4570
- const path3 = "/onramp/v1/token";
4571
- const jwt = await generateCdpJwt(credentials, "POST", path3);
4572
- const response = await fetch(`${CDP_API_BASE}${path3}`, {
4573
- method: "POST",
4574
- headers: {
4575
- "Authorization": `Bearer ${jwt}`,
4576
- "Content-Type": "application/json"
4577
- },
4578
- body: JSON.stringify({
4579
- addresses: [
4580
- {
4581
- address: params.address,
4582
- blockchains: [params.chain]
4583
- }
4584
- ],
4585
- clientIp: params.clientIp
4586
- })
4587
- });
4588
- if (!response.ok) {
4589
- const errorText = await response.text();
4590
- throw new Error(`CDP API error (${response.status}): ${errorText}`);
4591
- }
4592
- const result = await response.json();
4593
- return {
4594
- token: result.token,
4595
- channelId: result.channel_id
4596
- };
4597
- }
4598
- async function generateOnrampUrl(params) {
4599
- const chain = params.chain || "base";
4600
- const clientIp = await getPublicIp();
4601
- const { token } = await getSessionToken({
4602
- address: params.destinationAddress,
4603
- chain,
4604
- clientIp
4605
- });
4606
- const queryParams = new URLSearchParams({
4607
- sessionToken: token,
4608
- defaultAsset: "USDC",
4609
- defaultNetwork: chain,
4610
- presetFiatAmount: params.amount.toString()
4611
- });
4612
- return `https://pay.coinbase.com/buy/select-asset?${queryParams.toString()}`;
4613
- }
4614
- async function printQRCode(url) {
4615
- const qrcodeModule = await import("qrcode-terminal");
4616
- const qrcode = qrcodeModule.default || qrcodeModule;
4617
- return new Promise((resolve2) => {
4618
- qrcode.generate(url, { small: true }, (qr) => {
4619
- console.log(qr);
4620
- resolve2();
4621
- });
4622
- });
4623
- }
4624
- var import_fs4, import_path2, import_os2, CDP_API_BASE;
4625
- var init_onramp = __esm({
4626
- "src/onramp/index.ts"() {
29
+ // node_modules/tsup/assets/cjs_shims.js
30
+ var init_cjs_shims = __esm({
31
+ "node_modules/tsup/assets/cjs_shims.js"() {
4627
32
  "use strict";
4628
- init_cjs_shims();
4629
- import_fs4 = require("fs");
4630
- import_path2 = require("path");
4631
- import_os2 = require("os");
4632
- CDP_API_BASE = "https://api.developer.coinbase.com";
4633
33
  }
4634
34
  });
4635
35
 
4636
36
  // src/cli/index.ts
4637
37
  init_cjs_shims();
4638
38
  var import_commander = require("commander");
4639
- var import_os3 = require("os");
4640
- var import_path3 = require("path");
4641
- var import_fs5 = require("fs");
39
+ var import_os2 = require("os");
40
+ var import_path2 = require("path");
41
+ var import_fs4 = require("fs");
4642
42
  var import_child_process = require("child_process");
4643
43
 
4644
44
  // src/client/index.ts
@@ -6211,11 +1611,11 @@ var MoltsPayServer = class {
6211
1611
  return false;
6212
1612
  }
6213
1613
  const normalizedIP = clientIP === "::1" ? "127.0.0.1" : clientIP.replace("::ffff:", "");
6214
- const allowed2 = allowedIPs.includes(normalizedIP) || allowedIPs.includes(clientIP);
6215
- if (!allowed2) {
1614
+ const allowed = allowedIPs.includes(normalizedIP) || allowedIPs.includes(clientIP);
1615
+ if (!allowed) {
6216
1616
  console.log(`[MoltsPay] /proxy denied for IP: ${clientIP} (normalized: ${normalizedIP})`);
6217
1617
  }
6218
- return allowed2;
1618
+ return allowed;
6219
1619
  }
6220
1620
  /**
6221
1621
  * POST /proxy - Handle payment for external services (moltspay-creators)
@@ -6430,14 +1830,26 @@ var MoltsPayServer = class {
6430
1830
  }
6431
1831
  };
6432
1832
 
1833
+ // src/onramp/index.ts
1834
+ init_cjs_shims();
1835
+ async function printQRCode(url) {
1836
+ const qrcodeModule = await import("qrcode-terminal");
1837
+ const qrcode = qrcodeModule.default || qrcodeModule;
1838
+ return new Promise((resolve2) => {
1839
+ qrcode.generate(url, { small: true }, (qr) => {
1840
+ console.log(qr);
1841
+ resolve2();
1842
+ });
1843
+ });
1844
+ }
1845
+
6433
1846
  // src/cli/index.ts
6434
- init_onramp();
6435
1847
  var readline = __toESM(require("readline"));
6436
1848
  var program = new import_commander.Command();
6437
- var DEFAULT_CONFIG_DIR = (0, import_path3.join)((0, import_os3.homedir)(), ".moltspay");
6438
- var PID_FILE = (0, import_path3.join)(DEFAULT_CONFIG_DIR, "server.pid");
6439
- if (!(0, import_fs5.existsSync)(DEFAULT_CONFIG_DIR)) {
6440
- (0, import_fs5.mkdirSync)(DEFAULT_CONFIG_DIR, { recursive: true });
1849
+ var DEFAULT_CONFIG_DIR = (0, import_path2.join)((0, import_os2.homedir)(), ".moltspay");
1850
+ var PID_FILE = (0, import_path2.join)(DEFAULT_CONFIG_DIR, "server.pid");
1851
+ if (!(0, import_fs4.existsSync)(DEFAULT_CONFIG_DIR)) {
1852
+ (0, import_fs4.mkdirSync)(DEFAULT_CONFIG_DIR, { recursive: true });
6441
1853
  }
6442
1854
  function prompt(question) {
6443
1855
  const rl = readline.createInterface({
@@ -6454,7 +1866,7 @@ function prompt(question) {
6454
1866
  program.name("moltspay").description("MoltsPay - Payment infrastructure for AI Agents").version("1.0.0");
6455
1867
  program.command("init").description("Initialize MoltsPay client (create wallet, set limits)").option("--chain <chain>", "Blockchain to use", "base").option("--max-per-tx <amount>", "Max amount per transaction").option("--max-per-day <amount>", "Max amount per day").option("--config-dir <dir>", "Config directory", DEFAULT_CONFIG_DIR).action(async (options) => {
6456
1868
  console.log("\n\u{1F510} MoltsPay Client Setup\n");
6457
- if ((0, import_fs5.existsSync)((0, import_path3.join)(options.configDir, "wallet.json"))) {
1869
+ if ((0, import_fs4.existsSync)((0, import_path2.join)(options.configDir, "wallet.json"))) {
6458
1870
  console.log('\u26A0\uFE0F Already initialized. Use "moltspay config" to update settings.');
6459
1871
  console.log(` Config dir: ${options.configDir}`);
6460
1872
  return;
@@ -6481,7 +1893,7 @@ program.command("init").description("Initialize MoltsPay client (create wallet,
6481
1893
  console.log(`
6482
1894
  \u{1F4C1} Config saved to: ${result.configDir}`);
6483
1895
  console.log(`
6484
- \u26A0\uFE0F IMPORTANT: Back up ${(0, import_path3.join)(result.configDir, "wallet.json")}`);
1896
+ \u26A0\uFE0F IMPORTANT: Back up ${(0, import_path2.join)(result.configDir, "wallet.json")}`);
6485
1897
  console.log(` This file contains your private key!
6486
1898
  `);
6487
1899
  console.log(`\u{1F4B0} Fund your wallet with USDC on ${chain} to start using services.
@@ -6544,12 +1956,22 @@ program.command("fund <amount>").description("Fund wallet with USDC via Coinbase
6544
1956
  console.log(` Amount: $${amount.toFixed(2)}
6545
1957
  `);
6546
1958
  try {
6547
- const { generateOnrampUrl: generateOnrampUrl2 } = await Promise.resolve().then(() => (init_onramp(), onramp_exports));
6548
- const url = await generateOnrampUrl2({
6549
- destinationAddress: client.address,
6550
- amount,
6551
- chain
1959
+ const ONRAMP_API = process.env.MOLTSPAY_ONRAMP_API || "https://moltspay.com/api/v1/onramp";
1960
+ const response = await fetch(`${ONRAMP_API}/create`, {
1961
+ method: "POST",
1962
+ headers: { "Content-Type": "application/json" },
1963
+ body: JSON.stringify({
1964
+ address: client.address,
1965
+ amount,
1966
+ chain
1967
+ })
6552
1968
  });
1969
+ if (!response.ok) {
1970
+ const errorData = await response.json().catch(() => ({ error: "Server error" }));
1971
+ throw new Error(errorData.error || `Server returned ${response.status}`);
1972
+ }
1973
+ const result = await response.json();
1974
+ const { url } = result;
6553
1975
  console.log(" Scan to pay (US debit card / Apple Pay):\n");
6554
1976
  await printQRCode(url);
6555
1977
  console.log("\n \u23F1\uFE0F QR code expires in 5 minutes\n");
@@ -6660,12 +2082,12 @@ program.command("list").description("List recent transactions").option("--days <
6660
2082
  console.log(" (no transactions found)\n");
6661
2083
  } else {
6662
2084
  for (const tx of allTxns) {
6663
- const sign2 = tx.type === "IN" ? "+" : "-";
2085
+ const sign = tx.type === "IN" ? "+" : "-";
6664
2086
  const color = tx.type === "IN" ? "\x1B[32m" : "\x1B[31m";
6665
2087
  const reset = "\x1B[0m";
6666
2088
  const date = new Date(tx.timestamp).toISOString().slice(5, 16).replace("T", " ");
6667
2089
  const chainTag = chain === "all" ? `[${tx.chain.toUpperCase()}] ` : "";
6668
- console.log(` ${color}${sign2}${tx.amount.toFixed(2)} USDC${reset} | ${chainTag}${tx.type === "IN" ? "from" : "to"} ${tx.other.slice(0, 10)}...${tx.other.slice(-4)} | ${date}`);
2090
+ console.log(` ${color}${sign}${tx.amount.toFixed(2)} USDC${reset} | ${chainTag}${tx.type === "IN" ? "from" : "to"} ${tx.other.slice(0, 10)}...${tx.other.slice(-4)} | ${date}`);
6669
2091
  }
6670
2092
  const inTotal = allTxns.filter((t) => t.type === "IN").reduce((s, t) => s + t.amount, 0);
6671
2093
  const outTotal = allTxns.filter((t) => t.type === "OUT").reduce((s, t) => s + t.amount, 0);
@@ -6725,18 +2147,18 @@ program.command("start <paths...>").description("Start MoltsPay server from skil
6725
2147
  const handlers = /* @__PURE__ */ new Map();
6726
2148
  let provider = null;
6727
2149
  for (const inputPath of allPaths) {
6728
- const resolvedPath = (0, import_path3.resolve)(inputPath);
2150
+ const resolvedPath = (0, import_path2.resolve)(inputPath);
6729
2151
  let manifestPath;
6730
2152
  let skillDir;
6731
2153
  let isSkillDir = false;
6732
- if ((0, import_fs5.existsSync)((0, import_path3.join)(resolvedPath, "moltspay.services.json"))) {
6733
- manifestPath = (0, import_path3.join)(resolvedPath, "moltspay.services.json");
2154
+ if ((0, import_fs4.existsSync)((0, import_path2.join)(resolvedPath, "moltspay.services.json"))) {
2155
+ manifestPath = (0, import_path2.join)(resolvedPath, "moltspay.services.json");
6734
2156
  skillDir = resolvedPath;
6735
2157
  isSkillDir = true;
6736
- } else if ((0, import_fs5.existsSync)(resolvedPath) && resolvedPath.endsWith(".json")) {
2158
+ } else if ((0, import_fs4.existsSync)(resolvedPath) && resolvedPath.endsWith(".json")) {
6737
2159
  manifestPath = resolvedPath;
6738
- skillDir = (0, import_path3.dirname)(resolvedPath);
6739
- } else if ((0, import_fs5.existsSync)(resolvedPath)) {
2160
+ skillDir = (0, import_path2.dirname)(resolvedPath);
2161
+ } else if ((0, import_fs4.existsSync)(resolvedPath)) {
6740
2162
  console.error(`\u274C No moltspay.services.json found in: ${resolvedPath}`);
6741
2163
  continue;
6742
2164
  } else {
@@ -6745,25 +2167,25 @@ program.command("start <paths...>").description("Start MoltsPay server from skil
6745
2167
  }
6746
2168
  console.log(`\u{1F4E6} Loading: ${manifestPath}`);
6747
2169
  try {
6748
- const manifestContent = JSON.parse((0, import_fs5.readFileSync)(manifestPath, "utf-8"));
2170
+ const manifestContent = JSON.parse((0, import_fs4.readFileSync)(manifestPath, "utf-8"));
6749
2171
  if (!provider) {
6750
2172
  provider = manifestContent.provider;
6751
2173
  }
6752
2174
  let skillModule = null;
6753
2175
  if (isSkillDir) {
6754
2176
  let entryPoint = "index.js";
6755
- const pkgJsonPath = (0, import_path3.join)(skillDir, "package.json");
6756
- if ((0, import_fs5.existsSync)(pkgJsonPath)) {
2177
+ const pkgJsonPath = (0, import_path2.join)(skillDir, "package.json");
2178
+ if ((0, import_fs4.existsSync)(pkgJsonPath)) {
6757
2179
  try {
6758
- const pkgJson = JSON.parse((0, import_fs5.readFileSync)(pkgJsonPath, "utf-8"));
2180
+ const pkgJson = JSON.parse((0, import_fs4.readFileSync)(pkgJsonPath, "utf-8"));
6759
2181
  if (pkgJson.main) {
6760
2182
  entryPoint = pkgJson.main;
6761
2183
  }
6762
2184
  } catch {
6763
2185
  }
6764
2186
  }
6765
- const modulePath = (0, import_path3.join)(skillDir, entryPoint);
6766
- if ((0, import_fs5.existsSync)(modulePath)) {
2187
+ const modulePath = (0, import_path2.join)(skillDir, entryPoint);
2188
+ if ((0, import_fs4.existsSync)(modulePath)) {
6767
2189
  try {
6768
2190
  skillModule = await import(modulePath);
6769
2191
  console.log(` \u2705 Loaded module: ${modulePath}`);
@@ -6841,8 +2263,8 @@ program.command("start <paths...>").description("Start MoltsPay server from skil
6841
2263
  provider,
6842
2264
  services: allServices
6843
2265
  };
6844
- const tempManifestPath = (0, import_path3.join)(DEFAULT_CONFIG_DIR, "combined-manifest.json");
6845
- (0, import_fs5.writeFileSync)(tempManifestPath, JSON.stringify(combinedManifest, null, 2));
2266
+ const tempManifestPath = (0, import_path2.join)(DEFAULT_CONFIG_DIR, "combined-manifest.json");
2267
+ (0, import_fs4.writeFileSync)(tempManifestPath, JSON.stringify(combinedManifest, null, 2));
6846
2268
  console.log(`
6847
2269
  \u{1F4CB} Combined manifest: ${allServices.length} services`);
6848
2270
  console.log(` Provider: ${provider.name}`);
@@ -6855,12 +2277,12 @@ program.command("start <paths...>").description("Start MoltsPay server from skil
6855
2277
  server.skill(serviceId, handler);
6856
2278
  }
6857
2279
  const pidData = { pid: process.pid, port, paths: allPaths };
6858
- (0, import_fs5.writeFileSync)(PID_FILE, JSON.stringify(pidData, null, 2));
2280
+ (0, import_fs4.writeFileSync)(PID_FILE, JSON.stringify(pidData, null, 2));
6859
2281
  server.listen(port);
6860
2282
  const cleanup = () => {
6861
2283
  try {
6862
- if ((0, import_fs5.existsSync)(PID_FILE)) (0, import_fs5.unlinkSync)(PID_FILE);
6863
- if ((0, import_fs5.existsSync)(tempManifestPath)) (0, import_fs5.unlinkSync)(tempManifestPath);
2284
+ if ((0, import_fs4.existsSync)(PID_FILE)) (0, import_fs4.unlinkSync)(PID_FILE);
2285
+ if ((0, import_fs4.existsSync)(tempManifestPath)) (0, import_fs4.unlinkSync)(tempManifestPath);
6864
2286
  } catch {
6865
2287
  }
6866
2288
  };
@@ -6881,12 +2303,12 @@ program.command("start <paths...>").description("Start MoltsPay server from skil
6881
2303
  }
6882
2304
  });
6883
2305
  program.command("stop").description("Stop the running MoltsPay server").action(async () => {
6884
- if (!(0, import_fs5.existsSync)(PID_FILE)) {
2306
+ if (!(0, import_fs4.existsSync)(PID_FILE)) {
6885
2307
  console.log("\u274C No running server found (no PID file)");
6886
2308
  process.exit(1);
6887
2309
  }
6888
2310
  try {
6889
- const pidData = JSON.parse((0, import_fs5.readFileSync)(PID_FILE, "utf-8"));
2311
+ const pidData = JSON.parse((0, import_fs4.readFileSync)(PID_FILE, "utf-8"));
6890
2312
  const { pid, port, manifest } = pidData;
6891
2313
  console.log(`
6892
2314
  \u{1F6D1} Stopping MoltsPay Server
@@ -6899,7 +2321,7 @@ program.command("stop").description("Stop the running MoltsPay server").action(a
6899
2321
  process.kill(pid, 0);
6900
2322
  } catch {
6901
2323
  console.log("\u26A0\uFE0F Process not running, cleaning up PID file...");
6902
- (0, import_fs5.unlinkSync)(PID_FILE);
2324
+ (0, import_fs4.unlinkSync)(PID_FILE);
6903
2325
  process.exit(0);
6904
2326
  }
6905
2327
  process.kill(pid, "SIGTERM");
@@ -6911,8 +2333,8 @@ program.command("stop").description("Stop the running MoltsPay server").action(a
6911
2333
  process.kill(pid, "SIGKILL");
6912
2334
  } catch {
6913
2335
  }
6914
- if ((0, import_fs5.existsSync)(PID_FILE)) {
6915
- (0, import_fs5.unlinkSync)(PID_FILE);
2336
+ if ((0, import_fs4.existsSync)(PID_FILE)) {
2337
+ (0, import_fs4.unlinkSync)(PID_FILE);
6916
2338
  }
6917
2339
  console.log("\u2705 Server stopped\n");
6918
2340
  } catch (err) {
@@ -6941,12 +2363,12 @@ program.command("pay <server> <service> [params]").description("Pay for a servic
6941
2363
  if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
6942
2364
  params.image_url = imagePath;
6943
2365
  } else {
6944
- const filePath = (0, import_path3.resolve)(imagePath);
6945
- if (!(0, import_fs5.existsSync)(filePath)) {
2366
+ const filePath = (0, import_path2.resolve)(imagePath);
2367
+ if (!(0, import_fs4.existsSync)(filePath)) {
6946
2368
  console.error(`\u274C Image file not found: ${filePath}`);
6947
2369
  process.exit(1);
6948
2370
  }
6949
- const imageData = (0, import_fs5.readFileSync)(filePath);
2371
+ const imageData = (0, import_fs4.readFileSync)(filePath);
6950
2372
  params.image_base64 = imageData.toString("base64");
6951
2373
  }
6952
2374
  }
@@ -7008,11 +2430,11 @@ program.command("pay <server> <service> [params]").description("Pay for a servic
7008
2430
  }
7009
2431
  });
7010
2432
  program.command("validate <path>").description("Validate a moltspay.services.json file against the schema").action(async (inputPath) => {
7011
- const resolvedPath = (0, import_path3.resolve)(inputPath);
2433
+ const resolvedPath = (0, import_path2.resolve)(inputPath);
7012
2434
  let manifestPath;
7013
- if ((0, import_fs5.existsSync)((0, import_path3.join)(resolvedPath, "moltspay.services.json"))) {
7014
- manifestPath = (0, import_path3.join)(resolvedPath, "moltspay.services.json");
7015
- } else if (resolvedPath.endsWith(".json") && (0, import_fs5.existsSync)(resolvedPath)) {
2435
+ if ((0, import_fs4.existsSync)((0, import_path2.join)(resolvedPath, "moltspay.services.json"))) {
2436
+ manifestPath = (0, import_path2.join)(resolvedPath, "moltspay.services.json");
2437
+ } else if (resolvedPath.endsWith(".json") && (0, import_fs4.existsSync)(resolvedPath)) {
7016
2438
  manifestPath = resolvedPath;
7017
2439
  } else {
7018
2440
  console.error(`\u274C Not found: ${resolvedPath}`);
@@ -7022,7 +2444,7 @@ program.command("validate <path>").description("Validate a moltspay.services.jso
7022
2444
  \u{1F4CB} Validating: ${manifestPath}
7023
2445
  `);
7024
2446
  try {
7025
- const content = JSON.parse((0, import_fs5.readFileSync)(manifestPath, "utf-8"));
2447
+ const content = JSON.parse((0, import_fs4.readFileSync)(manifestPath, "utf-8"));
7026
2448
  const errors = [];
7027
2449
  if (!content.provider) {
7028
2450
  errors.push("Missing required field: provider");