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