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