@camstack/addon-auth 1.2.126 → 1.2.127

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.
@@ -3,23 +3,23 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../chunk-Cek0wNdY.js");
6
- const require_dist = require("../dist-Y4IbR-lV.js");
6
+ const require_dist = require("../dist-CrTS14S8.js");
7
7
  let node_crypto = require("node:crypto");
8
8
  node_crypto = require_chunk.__toESM(node_crypto);
9
- //#region node_modules/jose/dist/webapi/lib/buffer_utils.js
10
- var encoder = new TextEncoder();
11
- var decoder = new TextDecoder();
9
+ //#region ../../node_modules/jose/dist/webapi/lib/buffer_utils.js
10
+ var encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder("utf-8", { fatal: !0 });
12
11
  function concat(...buffers) {
13
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
14
- const buf = new Uint8Array(size);
12
+ const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);
15
13
  let i = 0;
16
- for (const buffer of buffers) {
17
- buf.set(buffer, i);
18
- i += buffer.length;
19
- }
14
+ for (const buffer of buffers) buf.set(buffer, i), i += buffer.length;
20
15
  return buf;
21
16
  }
17
+ var NON_ASCII = /[^\x00-\x7f]/;
22
18
  function encode(string) {
19
+ if (typeof string == "string" && string.length >= 128) {
20
+ if (NON_ASCII.test(string)) throw new TypeError("non-ASCII string encountered in encode()");
21
+ return encoder.encode(string);
22
+ }
23
23
  const bytes = new Uint8Array(string.length);
24
24
  for (let i = 0; i < string.length; i++) {
25
25
  const code = string.charCodeAt(i);
@@ -28,117 +28,23 @@ function encode(string) {
28
28
  }
29
29
  return bytes;
30
30
  }
31
- //#endregion
32
- //#region node_modules/jose/dist/webapi/lib/base64.js
33
- function decodeBase64(encoded) {
34
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
35
- const binary = atob(encoded);
36
- const bytes = new Uint8Array(binary.length);
31
+ function decodeBase64(encoded, url = !1) {
32
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
33
+ if (url) {
34
+ if (encoded.includes("+") || encoded.includes("/")) throw new TypeError("Invalid base64url");
35
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
36
+ }
37
+ const binary = atob(encoded), bytes = new Uint8Array(binary.length);
37
38
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
38
39
  return bytes;
39
40
  }
40
41
  //#endregion
41
- //#region node_modules/jose/dist/webapi/util/base64url.js
42
- function decode(input) {
43
- if (Uint8Array.fromBase64) return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" });
44
- let encoded = input;
45
- if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
46
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
47
- try {
48
- return decodeBase64(encoded);
49
- } catch {
50
- throw new TypeError("The input to be decoded is not correctly encoded.");
51
- }
52
- }
53
- //#endregion
54
- //#region node_modules/jose/dist/webapi/lib/crypto_key.js
55
- var unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
56
- var isAlgorithm = (algorithm, name) => algorithm.name === name;
57
- function getHashLength(hash) {
58
- return parseInt(hash.name.slice(4), 10);
59
- }
60
- function checkHashLength(algorithm, expected) {
61
- if (getHashLength(algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
62
- }
63
- function getNamedCurve(alg) {
64
- switch (alg) {
65
- case "ES256": return "P-256";
66
- case "ES384": return "P-384";
67
- case "ES512": return "P-521";
68
- default: throw new Error("unreachable");
69
- }
70
- }
71
- function checkUsage(key, usage) {
72
- if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
73
- }
74
- function checkSigCryptoKey(key, alg, usage) {
75
- switch (alg) {
76
- case "HS256":
77
- case "HS384":
78
- case "HS512":
79
- if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
80
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
81
- break;
82
- case "RS256":
83
- case "RS384":
84
- case "RS512":
85
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
86
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
87
- break;
88
- case "PS256":
89
- case "PS384":
90
- case "PS512":
91
- if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
92
- checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
93
- break;
94
- case "Ed25519":
95
- case "EdDSA":
96
- if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
97
- break;
98
- case "ML-DSA-44":
99
- case "ML-DSA-65":
100
- case "ML-DSA-87":
101
- if (!isAlgorithm(key.algorithm, alg)) throw unusable(alg);
102
- break;
103
- case "ES256":
104
- case "ES384":
105
- case "ES512": {
106
- if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
107
- const expected = getNamedCurve(alg);
108
- if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
109
- break;
110
- }
111
- default: throw new TypeError("CryptoKey does not support this operation");
112
- }
113
- checkUsage(key, usage);
114
- }
115
- //#endregion
116
- //#region node_modules/jose/dist/webapi/lib/invalid_key_input.js
117
- function message(msg, actual, ...types) {
118
- types = types.filter(Boolean);
119
- if (types.length > 2) {
120
- const last = types.pop();
121
- msg += `one of type ${types.join(", ")}, or ${last}.`;
122
- } else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`;
123
- else msg += `of type ${types[0]}.`;
124
- if (actual == null) msg += ` Received ${actual}`;
125
- else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`;
126
- else if (typeof actual === "object" && actual != null) {
127
- if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
128
- }
129
- return msg;
130
- }
131
- var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
132
- var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
133
- //#endregion
134
- //#region node_modules/jose/dist/webapi/util/errors.js
42
+ //#region ../../node_modules/jose/dist/webapi/util/errors.js
135
43
  var JOSEError = class extends Error {
136
44
  static code = "ERR_JOSE_GENERIC";
137
45
  code = "ERR_JOSE_GENERIC";
138
46
  constructor(message, options) {
139
- super(message, options);
140
- this.name = this.constructor.name;
141
- Error.captureStackTrace?.(this, this.constructor);
47
+ super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
142
48
  }
143
49
  };
144
50
  var JWTClaimValidationFailed = class extends JOSEError {
@@ -152,10 +58,7 @@ var JWTClaimValidationFailed = class extends JOSEError {
152
58
  claim,
153
59
  reason,
154
60
  payload
155
- } });
156
- this.claim = claim;
157
- this.reason = reason;
158
- this.payload = payload;
61
+ } }), this.claim = claim, this.reason = reason, this.payload = payload;
159
62
  }
160
63
  };
161
64
  var JWTExpired = class extends JOSEError {
@@ -169,10 +72,7 @@ var JWTExpired = class extends JOSEError {
169
72
  claim,
170
73
  reason,
171
74
  payload
172
- } });
173
- this.claim = claim;
174
- this.reason = reason;
175
- this.payload = payload;
75
+ } }), this.claim = claim, this.reason = reason, this.payload = payload;
176
76
  }
177
77
  };
178
78
  var JOSEAlgNotAllowed = class extends JOSEError {
@@ -203,7 +103,7 @@ var JWKSNoMatchingKey = class extends JOSEError {
203
103
  }
204
104
  };
205
105
  var JWKSMultipleMatchingKeys = class extends JOSEError {
206
- [Symbol.asyncIterator];
106
+ [Symbol.asyncIterator] = async function* () {};
207
107
  static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
208
108
  code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
209
109
  constructor(message = "multiple matching keys found in the JSON Web Key Set", options) {
@@ -225,810 +125,504 @@ var JWSSignatureVerificationFailed = class extends JOSEError {
225
125
  }
226
126
  };
227
127
  //#endregion
228
- //#region node_modules/jose/dist/webapi/lib/is_key_like.js
229
- var isCryptoKey = (key) => {
230
- if (key?.[Symbol.toStringTag] === "CryptoKey") return true;
231
- try {
232
- return key instanceof CryptoKey;
233
- } catch {
234
- return false;
235
- }
236
- };
237
- var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
238
- var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
239
- //#endregion
240
- //#region node_modules/jose/dist/webapi/lib/helpers.js
241
- function decodeBase64url(value, label, ErrorClass) {
128
+ //#region ../../node_modules/jose/dist/webapi/util/base64url.js
129
+ var invalid = "The input to be decoded is not correctly encoded.";
130
+ function decode(input) {
242
131
  try {
243
- return decode(value);
244
- } catch {
245
- throw new ErrorClass(`Failed to base64url decode the ${label}`);
132
+ return decodeBase64(typeof input == "string" ? input : decoder.decode(input), !0);
133
+ } catch (cause) {
134
+ throw new TypeError(invalid, { cause });
246
135
  }
247
136
  }
248
137
  //#endregion
249
- //#region node_modules/jose/dist/webapi/lib/type_checks.js
250
- var isObjectLike = (value) => typeof value === "object" && value !== null;
138
+ //#region ../../node_modules/jose/dist/webapi/lib/validate.js
251
139
  function isObject(input) {
252
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
253
- if (Object.getPrototypeOf(input) === null) return true;
254
- let proto = input;
255
- while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
256
- return Object.getPrototypeOf(input) === proto;
257
- }
258
- function isDisjoint(...headers) {
259
- const sources = headers.filter(Boolean);
260
- if (sources.length === 0 || sources.length === 1) return true;
261
- let acc;
262
- for (const header of sources) {
263
- const parameters = Object.keys(header);
264
- if (!acc || acc.size === 0) {
265
- acc = new Set(parameters);
266
- continue;
267
- }
268
- for (const parameter of parameters) {
269
- if (acc.has(parameter)) return false;
270
- acc.add(parameter);
271
- }
272
- }
273
- return true;
140
+ if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") return !1;
141
+ const prototype = Object.getPrototypeOf(input);
142
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
274
143
  }
275
- var isJWK = (key) => isObject(key) && typeof key.kty === "string";
276
- var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
277
- var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
278
- var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
279
- //#endregion
280
- //#region node_modules/jose/dist/webapi/lib/signing.js
281
- function checkKeyLength(alg, key) {
282
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
283
- const { modulusLength } = key.algorithm;
284
- if (typeof modulusLength !== "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
285
- }
144
+ function isJwkSet(input) {
145
+ return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);
286
146
  }
287
- function subtleAlgorithm(alg, algorithm) {
288
- const hash = `SHA-${alg.slice(-3)}`;
289
- switch (alg) {
290
- case "HS256":
291
- case "HS384":
292
- case "HS512": return {
293
- hash,
294
- name: "HMAC"
295
- };
296
- case "PS256":
297
- case "PS384":
298
- case "PS512": return {
299
- hash,
300
- name: "RSA-PSS",
301
- saltLength: parseInt(alg.slice(-3), 10) >> 3
302
- };
303
- case "RS256":
304
- case "RS384":
305
- case "RS512": return {
306
- hash,
307
- name: "RSASSA-PKCS1-v1_5"
308
- };
309
- case "ES256":
310
- case "ES384":
311
- case "ES512": return {
312
- hash,
313
- name: "ECDSA",
314
- namedCurve: algorithm.namedCurve
315
- };
316
- case "Ed25519":
317
- case "EdDSA": return { name: "Ed25519" };
318
- case "ML-DSA-44":
319
- case "ML-DSA-65":
320
- case "ML-DSA-87": return { name: alg };
321
- default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
147
+ function isDisjoint(...headers) {
148
+ const parameters = /* @__PURE__ */ new Set();
149
+ for (const header of headers) if (header) for (const parameter of Object.keys(header)) {
150
+ if (parameters.has(parameter)) return !1;
151
+ parameters.add(parameter);
322
152
  }
153
+ return !0;
323
154
  }
324
- async function getSigKey(alg, key, usage) {
325
- if (key instanceof Uint8Array) {
326
- if (!alg.startsWith("HS")) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
327
- return crypto.subtle.importKey("raw", key, {
328
- hash: `SHA-${alg.slice(-3)}`,
329
- name: "HMAC"
330
- }, false, [usage]);
155
+ function decodeBase64url(value, label, ErrorClass) {
156
+ try {
157
+ return decode(value);
158
+ } catch {
159
+ throw new ErrorClass(`Failed to base64url decode the ${label}`);
331
160
  }
332
- checkSigCryptoKey(key, alg, usage);
333
- return key;
334
161
  }
335
- async function verify(alg, key, signature, data) {
336
- const cryptoKey = await getSigKey(alg, key, "verify");
337
- checkKeyLength(alg, cryptoKey);
338
- const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
162
+ function encodeBase64url(value, label, ErrorClass) {
339
163
  try {
340
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
164
+ return encode(value);
341
165
  } catch {
342
- return false;
166
+ throw new ErrorClass(`The ${label} is not a valid base64url string`);
343
167
  }
344
168
  }
345
- //#endregion
346
- //#region node_modules/jose/dist/webapi/lib/jwk_to_key.js
347
- var unsupportedAlg = "Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value";
348
- function subtleMapping(jwk) {
349
- let algorithm;
350
- let keyUsages;
351
- switch (jwk.kty) {
352
- case "AKP":
353
- switch (jwk.alg) {
354
- case "ML-DSA-44":
355
- case "ML-DSA-65":
356
- case "ML-DSA-87":
357
- algorithm = { name: jwk.alg };
358
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
359
- break;
360
- default: throw new JOSENotSupported(unsupportedAlg);
361
- }
362
- break;
363
- case "RSA":
364
- switch (jwk.alg) {
365
- case "PS256":
366
- case "PS384":
367
- case "PS512":
368
- algorithm = {
369
- name: "RSA-PSS",
370
- hash: `SHA-${jwk.alg.slice(-3)}`
371
- };
372
- keyUsages = jwk.d ? ["sign"] : ["verify"];
373
- break;
374
- case "RS256":
375
- case "RS384":
376
- case "RS512":
377
- algorithm = {
378
- name: "RSASSA-PKCS1-v1_5",
379
- hash: `SHA-${jwk.alg.slice(-3)}`
380
- };
381
- keyUsages = jwk.d ? ["sign"] : ["verify"];
382
- break;
383
- case "RSA-OAEP":
384
- case "RSA-OAEP-256":
385
- case "RSA-OAEP-384":
386
- case "RSA-OAEP-512":
387
- algorithm = {
388
- name: "RSA-OAEP",
389
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
390
- };
391
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
392
- break;
393
- default: throw new JOSENotSupported(unsupportedAlg);
394
- }
395
- break;
396
- case "EC":
397
- switch (jwk.alg) {
398
- case "ES256":
399
- case "ES384":
400
- case "ES512":
401
- algorithm = {
402
- name: "ECDSA",
403
- namedCurve: {
404
- ES256: "P-256",
405
- ES384: "P-384",
406
- ES512: "P-521"
407
- }[jwk.alg]
408
- };
409
- keyUsages = jwk.d ? ["sign"] : ["verify"];
410
- break;
411
- case "ECDH-ES":
412
- case "ECDH-ES+A128KW":
413
- case "ECDH-ES+A192KW":
414
- case "ECDH-ES+A256KW":
415
- algorithm = {
416
- name: "ECDH",
417
- namedCurve: jwk.crv
418
- };
419
- keyUsages = jwk.d ? ["deriveBits"] : [];
420
- break;
421
- default: throw new JOSENotSupported(unsupportedAlg);
422
- }
423
- break;
424
- case "OKP":
425
- switch (jwk.alg) {
426
- case "Ed25519":
427
- case "EdDSA":
428
- algorithm = { name: "Ed25519" };
429
- keyUsages = jwk.d ? ["sign"] : ["verify"];
430
- break;
431
- case "ECDH-ES":
432
- case "ECDH-ES+A128KW":
433
- case "ECDH-ES+A192KW":
434
- case "ECDH-ES+A256KW":
435
- algorithm = { name: jwk.crv };
436
- keyUsages = jwk.d ? ["deriveBits"] : [];
437
- break;
438
- default: throw new JOSENotSupported(unsupportedAlg);
439
- }
440
- break;
441
- default: throw new JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
169
+ function parseJoseHeader(b64, ErrorClass, message) {
170
+ let parsed;
171
+ try {
172
+ parsed = JSON.parse(strictDecoder.decode(decode(b64)));
173
+ } catch {
174
+ throw new ErrorClass(message);
442
175
  }
443
- return {
444
- algorithm,
445
- keyUsages
446
- };
176
+ if (!isObject(parsed)) throw new ErrorClass(message);
177
+ return parsed;
447
178
  }
448
- async function jwkToKey(jwk) {
449
- if (!jwk.alg) throw new TypeError("\"alg\" argument is required when \"jwk.alg\" is not present");
450
- const { algorithm, keyUsages } = subtleMapping(jwk);
451
- const keyData = { ...jwk };
452
- if (keyData.kty !== "AKP") delete keyData.alg;
453
- delete keyData.use;
454
- return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
455
- }
456
- //#endregion
457
- //#region node_modules/jose/dist/webapi/lib/normalize_key.js
458
- var unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
459
- var cache;
460
- var handleJWK = async (key, jwk, alg, freeze = false) => {
461
- cache ||= /* @__PURE__ */ new WeakMap();
462
- let cached = cache.get(key);
463
- if (cached?.[alg]) return cached[alg];
464
- const cryptoKey = await jwkToKey({
465
- ...jwk,
466
- alg
467
- });
468
- if (freeze) Object.freeze(key);
469
- if (!cached) cache.set(key, { [alg]: cryptoKey });
470
- else cached[alg] = cryptoKey;
471
- return cryptoKey;
472
- };
473
- var handleKeyObject = (keyObject, alg) => {
474
- cache ||= /* @__PURE__ */ new WeakMap();
475
- let cached = cache.get(keyObject);
476
- if (cached?.[alg]) return cached[alg];
477
- const isPublic = keyObject.type === "public";
478
- const extractable = isPublic ? true : false;
479
- let cryptoKey;
480
- if (keyObject.asymmetricKeyType === "x25519") {
481
- switch (alg) {
482
- case "ECDH-ES":
483
- case "ECDH-ES+A128KW":
484
- case "ECDH-ES+A192KW":
485
- case "ECDH-ES+A256KW": break;
486
- default: throw new TypeError(unusableForAlg);
487
- }
488
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
489
- }
490
- if (keyObject.asymmetricKeyType === "ed25519") {
491
- if (alg !== "EdDSA" && alg !== "Ed25519") throw new TypeError(unusableForAlg);
492
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
493
- }
494
- switch (keyObject.asymmetricKeyType) {
495
- case "ml-dsa-44":
496
- case "ml-dsa-65":
497
- case "ml-dsa-87":
498
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) throw new TypeError(unusableForAlg);
499
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [isPublic ? "verify" : "sign"]);
500
- }
501
- if (keyObject.asymmetricKeyType === "rsa") {
502
- let hash;
503
- switch (alg) {
504
- case "RSA-OAEP":
505
- hash = "SHA-1";
506
- break;
507
- case "RS256":
508
- case "PS256":
509
- case "RSA-OAEP-256":
510
- hash = "SHA-256";
511
- break;
512
- case "RS384":
513
- case "PS384":
514
- case "RSA-OAEP-384":
515
- hash = "SHA-384";
516
- break;
517
- case "RS512":
518
- case "PS512":
519
- case "RSA-OAEP-512":
520
- hash = "SHA-512";
521
- break;
522
- default: throw new TypeError(unusableForAlg);
523
- }
524
- if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
525
- name: "RSA-OAEP",
526
- hash
527
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
528
- cryptoKey = keyObject.toCryptoKey({
529
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
530
- hash
531
- }, extractable, [isPublic ? "verify" : "sign"]);
532
- }
533
- if (keyObject.asymmetricKeyType === "ec") {
534
- const namedCurve = new Map([
535
- ["prime256v1", "P-256"],
536
- ["secp384r1", "P-384"],
537
- ["secp521r1", "P-521"]
538
- ]).get(keyObject.asymmetricKeyDetails?.namedCurve);
539
- if (!namedCurve) throw new TypeError(unusableForAlg);
540
- const expectedCurve = {
541
- ES256: "P-256",
542
- ES384: "P-384",
543
- ES512: "P-521"
544
- };
545
- if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) cryptoKey = keyObject.toCryptoKey({
546
- name: "ECDSA",
547
- namedCurve
548
- }, extractable, [isPublic ? "verify" : "sign"]);
549
- if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
550
- name: "ECDH",
551
- namedCurve
552
- }, extractable, isPublic ? [] : ["deriveBits"]);
553
- }
554
- if (!cryptoKey) throw new TypeError(unusableForAlg);
555
- if (!cached) cache.set(keyObject, { [alg]: cryptoKey });
556
- else cached[alg] = cryptoKey;
557
- return cryptoKey;
179
+ var JWS_RECOGNIZED = {
180
+ __proto__: null,
181
+ b64: !0
558
182
  };
559
- async function normalizeKey(key, alg) {
560
- if (key instanceof Uint8Array) return key;
561
- if (isCryptoKey(key)) return key;
562
- if (isKeyObject(key)) {
563
- if (key.type === "secret") return key.export();
564
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") try {
565
- return handleKeyObject(key, alg);
566
- } catch (err) {
567
- if (err instanceof TypeError) throw err;
568
- }
569
- return handleJWK(key, key.export({ format: "jwk" }), alg);
570
- }
571
- if (isJWK(key)) {
572
- if (key.k) return decode(key.k);
573
- return handleJWK(key, key, alg, true);
574
- }
575
- throw new Error("unreachable");
576
- }
577
- //#endregion
578
- //#region node_modules/jose/dist/webapi/key/import.js
579
- async function importJWK(jwk, alg, options) {
580
- if (!isObject(jwk)) throw new TypeError("JWK must be an object");
581
- let ext;
582
- alg ??= jwk.alg;
583
- ext ??= options?.extractable ?? jwk.ext;
584
- switch (jwk.kty) {
585
- case "oct":
586
- if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
587
- return decode(jwk.k);
588
- case "RSA":
589
- if ("oth" in jwk && jwk.oth !== void 0) throw new JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
590
- return jwkToKey({
591
- ...jwk,
592
- alg,
593
- ext
594
- });
595
- case "AKP":
596
- if (typeof jwk.alg !== "string" || !jwk.alg) throw new TypeError("missing \"alg\" (Algorithm) Parameter value");
597
- if (alg !== void 0 && alg !== jwk.alg) throw new TypeError("JWK alg and alg option value mismatch");
598
- return jwkToKey({
599
- ...jwk,
600
- ext
601
- });
602
- case "EC":
603
- case "OKP": return jwkToKey({
604
- ...jwk,
605
- alg,
606
- ext
607
- });
608
- default: throw new JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
609
- }
183
+ function validateAlgorithms(option, algorithms) {
184
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
185
+ return algorithms === void 0 ? void 0 : new Set(algorithms);
610
186
  }
611
- //#endregion
612
- //#region node_modules/jose/dist/webapi/lib/validate_crit.js
613
187
  function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
614
188
  if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
615
- if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set();
616
- 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");
617
- let recognized;
618
- if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
619
- else recognized = recognizedDefault;
189
+ if (!protectedHeader || protectedHeader.crit === void 0) return [];
190
+ 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");
191
+ const recognized = recognizedOption === void 0 ? recognizedDefault : {
192
+ __proto__: null,
193
+ ...recognizedOption,
194
+ ...recognizedDefault
195
+ };
620
196
  for (const parameter of protectedHeader.crit) {
621
- if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
622
- if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
623
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
197
+ if (!(parameter in recognized)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
198
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
199
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0)) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
624
200
  }
625
- return new Set(protectedHeader.crit);
201
+ return protectedHeader.crit;
626
202
  }
627
- //#endregion
628
- //#region node_modules/jose/dist/webapi/lib/validate_algorithms.js
629
- function validateAlgorithms(option, algorithms) {
630
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
631
- if (!algorithms) return;
632
- return new Set(algorithms);
203
+ function validateB64(protectedHeader, extensions) {
204
+ if (extensions.includes("b64")) {
205
+ const b64 = protectedHeader.b64;
206
+ if (typeof b64 != "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
207
+ return b64;
208
+ }
209
+ return !0;
633
210
  }
634
211
  //#endregion
635
- //#region node_modules/jose/dist/webapi/lib/check_key_type.js
636
- var tag = (key) => key?.[Symbol.toStringTag];
637
- var jwkMatchesOp = (alg, key, usage) => {
212
+ //#region ../../node_modules/jose/dist/webapi/lib/key.js
213
+ var tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {
214
+ const { alg } = entry;
638
215
  if (key.use !== void 0) {
639
- let expected;
640
- switch (usage) {
641
- case "sign":
642
- case "verify":
643
- expected = "sig";
644
- break;
645
- case "encrypt":
646
- case "decrypt":
647
- expected = "enc";
648
- break;
649
- }
216
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
650
217
  if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
651
218
  }
652
219
  if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
653
220
  if (Array.isArray(key.key_ops)) {
654
- let expectedKeyOp;
655
- switch (true) {
656
- case usage === "sign" || usage === "verify":
657
- case alg === "dir":
658
- case alg.includes("CBC-HS"):
659
- expectedKeyOp = usage;
660
- break;
661
- case alg.startsWith("PBES2"):
662
- expectedKeyOp = "deriveBits";
663
- break;
664
- case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
665
- if (!alg.includes("GCM") && alg.endsWith("KW")) expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
666
- else expectedKeyOp = usage;
667
- break;
668
- case usage === "encrypt" && alg.startsWith("RSA"):
669
- expectedKeyOp = "wrapKey";
670
- break;
671
- case usage === "decrypt":
672
- expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
673
- break;
674
- }
675
- if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
676
- }
677
- return true;
678
- };
679
- var symmetricTypeCheck = (alg, key, usage) => {
680
- if (key instanceof Uint8Array) return;
681
- if (isJWK(key)) {
682
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
683
- throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
221
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
222
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
684
223
  }
685
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
686
- if (key.type !== "secret") throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
687
224
  };
688
- var asymmetricTypeCheck = (alg, key, usage) => {
689
- if (isJWK(key)) switch (usage) {
690
- case "decrypt":
691
- case "sign":
692
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
693
- throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
694
- case "encrypt":
695
- case "verify":
696
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
697
- throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
698
- }
699
- if (!isKeyLike(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
700
- if (key.type === "secret") throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
701
- if (key.type === "public") switch (usage) {
702
- case "sign": throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
703
- case "decrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
704
- }
705
- if (key.type === "private") switch (usage) {
706
- case "verify": throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
707
- case "encrypt": throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
225
+ async function prepareKey(entry, key, usage) {
226
+ const { alg, secret } = entry, privateKey = usage === "decrypt" || usage === "sign";
227
+ if (secret && key instanceof Uint8Array) return key;
228
+ let normalized, keyObject;
229
+ if (isObject(key)) {
230
+ if (normalized = normalizeJwk(key), typeof normalized.kty != "string") throw invalidKeyType(alg, key, secret);
231
+ 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`);
232
+ if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct") return decode(normalized.k);
233
+ if (!Object.isFrozen(key)) {
234
+ const { key_ops } = key;
235
+ Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
236
+ }
237
+ } else {
238
+ if (!isKeyLike(key)) throw invalidKeyType(alg, key, secret);
239
+ const expectedType = secret ? "secret" : privateKey ? "private" : "public";
240
+ if (key.type !== expectedType && (secret || [
241
+ "secret",
242
+ "public",
243
+ "private"
244
+ ].includes(key.type))) throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
245
+ if (isCryptoKey(key)) return key;
246
+ if (keyObject = key, keyObject.type === "secret") return keyObject.export();
708
247
  }
248
+ cache ||= /* @__PURE__ */ new WeakMap();
249
+ const cacheKey = key;
250
+ let cached = cache.get(cacheKey);
251
+ if (cached?.[alg]) return cached[alg];
252
+ if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
253
+ const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({
254
+ crv,
255
+ asymmetricKeyType: keyObject.asymmetricKeyType
256
+ }) ?? entry.subtle;
257
+ return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
258
+ }
259
+ return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);
260
+ }
261
+ var cache;
262
+ var nist = {
263
+ __proto__: null,
264
+ prime256v1: "P-256",
265
+ secp384r1: "P-384",
266
+ secp521r1: "P-521"
709
267
  };
710
- function checkKeyType(alg, key, usage) {
711
- switch (alg.substring(0, 2)) {
712
- case "A1":
713
- case "A2":
714
- case "di":
715
- case "HS":
716
- case "PB":
717
- symmetricTypeCheck(alg, key, usage);
718
- break;
719
- default: asymmetricTypeCheck(alg, key, usage);
268
+ var isCryptoKey = (key) => {
269
+ if (key?.[Symbol.toStringTag] === "CryptoKey") return !0;
270
+ try {
271
+ return key instanceof CryptoKey;
272
+ } catch {
273
+ return !1;
720
274
  }
275
+ }, isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
276
+ function message(msg, actual, ...types) {
277
+ if (types.length > 2) {
278
+ const last = types.pop();
279
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
280
+ } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
281
+ 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;
282
+ }
283
+ function invalidKeyType(alg, actual, secret) {
284
+ const types = [
285
+ "CryptoKey",
286
+ "KeyObject",
287
+ "JSON Web Key"
288
+ ];
289
+ return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
290
+ }
291
+ var unusable = (name, prop = "algorithm.name") => /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
292
+ function checkUsage(key, usage) {
293
+ if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
294
+ }
295
+ function checkModulusLength(alg, key) {
296
+ const { modulusLength } = key.algorithm;
297
+ if (typeof modulusLength != "number" || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
298
+ }
299
+ function checkCryptoKey(key, expected, usage) {
300
+ const algorithm = key.algorithm;
301
+ if (algorithm.name !== expected.name) throw unusable(expected.name);
302
+ if (expected.hash && algorithm.hash?.name !== expected.hash) throw unusable(expected.hash, "algorithm.hash");
303
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) throw unusable(expected.namedCurve, "algorithm.namedCurve");
304
+ if (expected.length !== void 0 && algorithm.length !== expected.length) throw unusable(expected.length, "algorithm.length");
305
+ checkUsage(key, usage);
306
+ }
307
+ function snapshotJwk(jwk) {
308
+ return {
309
+ __proto__: null,
310
+ ...jwk
311
+ };
312
+ }
313
+ function normalizeJwk(jwk) {
314
+ const normalized = snapshotJwk(jwk);
315
+ if (normalized.ext !== void 0 && typeof normalized.ext != "boolean") throw new TypeError("\"ext\" (Extractable) Parameter must be a boolean");
316
+ if (normalized.key_ops !== void 0) {
317
+ const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
318
+ 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");
319
+ normalized.key_ops = keyOps;
320
+ }
321
+ return normalized;
322
+ }
323
+ async function jwkToKey(entry, jwk, extractable) {
324
+ if (!entry.kty.includes(jwk.kty)) throw new JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
325
+ const algorithm = entry.resolve?.({
326
+ kty: jwk.kty,
327
+ crv: jwk.crv
328
+ }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = {
329
+ ...jwk,
330
+ ext: extractable ?? jwk.ext
331
+ };
332
+ 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]);
333
+ }
334
+ async function rawKey(key, expected, usage, extractable = !1) {
335
+ return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
336
+ }
337
+ //#endregion
338
+ //#region ../../node_modules/jose/dist/webapi/lib/key_descriptor.js
339
+ function table(entries) {
340
+ const out = { __proto__: null };
341
+ for (const alg in entries) out[alg] = {
342
+ ...entries[alg],
343
+ alg
344
+ };
345
+ return out;
346
+ }
347
+ //#endregion
348
+ //#region ../../node_modules/jose/dist/webapi/lib/jws_algorithms.js
349
+ var sig = [["verify"], ["sign"]];
350
+ function hmac(bits) {
351
+ const subtle = {
352
+ name: "HMAC",
353
+ hash: `SHA-${bits}`
354
+ };
355
+ return {
356
+ kty: ["oct"],
357
+ secret: !0,
358
+ subtle,
359
+ signing: subtle,
360
+ usages: sig
361
+ };
362
+ }
363
+ function rsa(bits, saltLength) {
364
+ const subtle = {
365
+ name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
366
+ hash: `SHA-${bits}`
367
+ };
368
+ return {
369
+ kty: ["RSA"],
370
+ subtle,
371
+ signing: saltLength ? {
372
+ ...subtle,
373
+ saltLength
374
+ } : subtle,
375
+ usages: sig,
376
+ minRsaBits: 2048
377
+ };
378
+ }
379
+ function ecdsa(crv, bits) {
380
+ return {
381
+ kty: ["EC"],
382
+ crv,
383
+ subtle: {
384
+ name: "ECDSA",
385
+ namedCurve: crv
386
+ },
387
+ signing: {
388
+ name: "ECDSA",
389
+ hash: `SHA-${bits}`
390
+ },
391
+ usages: sig
392
+ };
393
+ }
394
+ function eddsa() {
395
+ const subtle = { name: "Ed25519" };
396
+ return {
397
+ kty: ["OKP"],
398
+ crv: "Ed25519",
399
+ subtle,
400
+ signing: subtle,
401
+ usages: sig
402
+ };
403
+ }
404
+ function mldsa(bits) {
405
+ const subtle = { name: `ML-DSA-${bits}` };
406
+ return {
407
+ kty: ["AKP"],
408
+ subtle,
409
+ signing: subtle,
410
+ usages: sig
411
+ };
412
+ }
413
+ var JWS = table({
414
+ HS256: hmac(256),
415
+ HS384: hmac(384),
416
+ HS512: hmac(512),
417
+ RS256: rsa(256),
418
+ RS384: rsa(384),
419
+ RS512: rsa(512),
420
+ PS256: rsa(256, 32),
421
+ PS384: rsa(384, 48),
422
+ PS512: rsa(512, 64),
423
+ ES256: ecdsa("P-256", 256),
424
+ ES384: ecdsa("P-384", 384),
425
+ ES512: ecdsa("P-521", 512),
426
+ EdDSA: eddsa(),
427
+ Ed25519: eddsa(),
428
+ "ML-DSA-44": mldsa(44),
429
+ "ML-DSA-65": mldsa(65),
430
+ "ML-DSA-87": mldsa(87)
431
+ });
432
+ function jwsAlgorithm(alg) {
433
+ const entry = typeof alg == "string" ? JWS[alg] : void 0;
434
+ if (!entry) throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
435
+ return entry;
721
436
  }
722
437
  //#endregion
723
- //#region node_modules/jose/dist/webapi/jws/flattened/verify.js
724
- async function flattenedVerify(jws, key, options) {
725
- if (!isObject(jws)) throw new JWSInvalid("Flattened JWS must be an object");
726
- if (jws.protected === void 0 && jws.header === void 0) throw new JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
727
- if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new JWSInvalid("JWS Protected Header incorrect type");
728
- if (jws.payload === void 0) throw new JWSInvalid("JWS Payload missing");
729
- if (typeof jws.signature !== "string") throw new JWSInvalid("JWS Signature missing or incorrect type");
730
- if (jws.header !== void 0 && !isObject(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
731
- let parsedProt = {};
732
- if (jws.protected) try {
733
- const protectedHeader = decode(jws.protected);
734
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
438
+ //#region ../../node_modules/jose/dist/webapi/lib/jws_verify.js
439
+ function prepareVerify(options) {
440
+ return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
441
+ }
442
+ function parseProtectedHeader(encodedProtected) {
443
+ return encodedProtected === void 0 ? {} : parseJoseHeader(encodedProtected, JWSInvalid, "JWS Protected Header is invalid");
444
+ }
445
+ function encodeCompactUnencodedPayload(payload) {
446
+ try {
447
+ return encode(payload);
735
448
  } catch {
736
- throw new JWSInvalid("JWS Protected Header is invalid");
449
+ throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters");
737
450
  }
738
- if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
451
+ }
452
+ async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
453
+ const { protected: encodedProtected, header, payload: inputPayload } = jws, parsedProt = parsedProtected ?? parseProtectedHeader(encodedProtected);
454
+ if (!isDisjoint(parsedProt, header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
739
455
  const joseHeader = {
740
456
  ...parsedProt,
741
- ...jws.header
742
- };
743
- const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
744
- let b64 = true;
745
- if (extensions.has("b64")) {
746
- b64 = parsedProt.b64;
747
- if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
748
- }
749
- const { alg } = joseHeader;
750
- if (typeof alg !== "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
751
- const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
752
- if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
457
+ ...header
458
+ }, b64 = validateB64(parsedProt, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], parsedProt, joseHeader)), { alg } = joseHeader;
459
+ if (typeof alg != "string" || !alg) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
460
+ if (shared[0] && !shared[0].has(alg)) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
753
461
  if (b64) {
754
- if (typeof jws.payload !== "string") throw new JWSInvalid("JWS Payload must be a string");
755
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
756
- let resolvedKey = false;
757
- if (typeof key === "function") {
758
- key = await key(parsedProt, jws);
759
- resolvedKey = true;
760
- }
761
- checkKeyType(alg, key, "verify");
762
- const data = concat(jws.protected !== void 0 ? encode(jws.protected) : new Uint8Array(), encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
763
- const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
764
- const k = await normalizeKey(key, alg);
765
- if (!await verify(alg, k, signature, data)) throw new JWSSignatureVerificationFailed();
766
- let payload;
767
- if (b64) payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
768
- else if (typeof jws.payload === "string") payload = encoder.encode(jws.payload);
769
- else payload = jws.payload;
770
- const result = { payload };
771
- if (jws.protected !== void 0) result.protectedHeader = parsedProt;
772
- if (jws.header !== void 0) result.unprotectedHeader = jws.header;
773
- if (resolvedKey) return {
462
+ if (typeof inputPayload != "string") throw new JWSInvalid("JWS Payload must be a string");
463
+ } else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
464
+ const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
465
+ let resolvedKey = !1;
466
+ typeof key == "function" && (key = await key(parsedProt, jws), resolvedKey = !0);
467
+ const entry = jwsAlgorithm(alg), data = concat(encodedProtected !== void 0 ? encode(encodedProtected) : new Uint8Array(), encode("."), 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");
468
+ entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
469
+ let verified = !1;
470
+ try {
471
+ verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, data);
472
+ } catch {}
473
+ if (!verified) throw new JWSSignatureVerificationFailed();
474
+ const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
475
+ return encodedProtected !== void 0 && (result.protectedHeader = parsedProt), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{
774
476
  ...result,
775
477
  key: k
776
- };
777
- return result;
478
+ }, b64] : [result, b64];
778
479
  }
779
- //#endregion
780
- //#region node_modules/jose/dist/webapi/jws/compact/verify.js
781
- async function compactVerify(jws, key, options) {
782
- if (jws instanceof Uint8Array) jws = decoder.decode(jws);
783
- if (typeof jws !== "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
480
+ async function verifyCompact(jws, shared, key) {
481
+ if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string") throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
784
482
  const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
785
483
  if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
786
- const verified = await flattenedVerify({
484
+ return verifySignature({
787
485
  payload,
788
486
  protected: protectedHeader,
789
487
  signature
790
- }, key, options);
791
- const result = {
792
- payload: verified.payload,
793
- protectedHeader: verified.protectedHeader
794
- };
795
- if (typeof key === "function") return {
796
- ...result,
797
- key: verified.key
798
- };
799
- return result;
488
+ }, shared, key, encodeCompactUnencodedPayload);
800
489
  }
801
490
  //#endregion
802
- //#region node_modules/jose/dist/webapi/lib/jwt_claims_set.js
803
- var epoch = (date) => Math.floor(date.getTime() / 1e3);
804
- var minute = 60;
805
- var hour = minute * 60;
806
- var day = hour * 24;
807
- var week = day * 7;
808
- var year = day * 365.25;
809
- var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
491
+ //#region ../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js
492
+ var epoch = (date) => Math.floor(date.getTime() / 1e3), multipliers = {
493
+ s: 1,
494
+ m: 60,
495
+ h: 3600,
496
+ d: 86400,
497
+ w: 604800,
498
+ y: 31557600
499
+ }, REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, checkFailed = "check_failed";
500
+ function invalidDuration() {
501
+ throw new TypeError("Invalid time period format");
502
+ }
810
503
  function secs(str) {
504
+ typeof str != "string" && invalidDuration();
811
505
  const matched = REGEX.exec(str);
812
- if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
813
- const value = parseFloat(matched[2]);
814
- const unit = matched[3].toLowerCase();
815
- let numericDate;
816
- switch (unit) {
817
- case "sec":
818
- case "secs":
819
- case "second":
820
- case "seconds":
821
- case "s":
822
- numericDate = Math.round(value);
823
- break;
824
- case "minute":
825
- case "minutes":
826
- case "min":
827
- case "mins":
828
- case "m":
829
- numericDate = Math.round(value * minute);
830
- break;
831
- case "hour":
832
- case "hours":
833
- case "hr":
834
- case "hrs":
835
- case "h":
836
- numericDate = Math.round(value * hour);
837
- break;
838
- case "day":
839
- case "days":
840
- case "d":
841
- numericDate = Math.round(value * day);
842
- break;
843
- case "week":
844
- case "weeks":
845
- case "w":
846
- numericDate = Math.round(value * week);
847
- break;
848
- default:
849
- numericDate = Math.round(value * year);
850
- break;
851
- }
852
- if (matched[1] === "-" || matched[4] === "ago") return -numericDate;
853
- return numericDate;
506
+ (!matched || matched[4] && matched[1]) && invalidDuration();
507
+ const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
508
+ return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2;
509
+ }
510
+ function validateInput(label, input) {
511
+ if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
512
+ return input;
854
513
  }
855
514
  var normalizeTyp = (value) => {
856
- if (value.includes("/")) return value.toLowerCase();
857
- return `application/${value.toLowerCase()}`;
858
- };
859
- var checkAudiencePresence = (audPayload, audOption) => {
860
- if (typeof audPayload === "string") return audOption.includes(audPayload);
861
- if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
862
- return false;
863
- };
515
+ const normalized = value.toLowerCase();
516
+ return value.includes("/") ? normalized : `application/${normalized}`;
517
+ }, checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;
518
+ function validateNumericDate(payload, claim, required = !1) {
519
+ const value = payload[claim];
520
+ if (!(value === void 0 && !required)) {
521
+ if (typeof value != "number") throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, payload, claim, "invalid");
522
+ return value;
523
+ }
524
+ }
525
+ function unexpectedClaim(payload, claim) {
526
+ throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, payload, claim, checkFailed);
527
+ }
864
528
  function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
865
529
  let payload;
866
530
  try {
867
- payload = JSON.parse(decoder.decode(encodedPayload));
531
+ payload = JSON.parse(strictDecoder.decode(encodedPayload));
868
532
  } catch {}
869
533
  if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
870
534
  const { typ } = options;
871
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", "check_failed");
872
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
873
- const presenceCheck = [...requiredClaims];
874
- if (maxTokenAge !== void 0) presenceCheck.push("iat");
875
- if (audience !== void 0) presenceCheck.push("aud");
876
- if (subject !== void 0) presenceCheck.push("sub");
877
- if (issuer !== void 0) presenceCheck.push("iss");
878
- for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
879
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new JWTClaimValidationFailed("unexpected \"iss\" claim value", payload, "iss", "check_failed");
880
- if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed("unexpected \"sub\" claim value", payload, "sub", "check_failed");
881
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new JWTClaimValidationFailed("unexpected \"aud\" claim value", payload, "aud", "check_failed");
882
- let tolerance;
883
- switch (typeof options.clockTolerance) {
884
- case "string":
885
- tolerance = secs(options.clockTolerance);
886
- break;
887
- case "number":
888
- tolerance = options.clockTolerance;
889
- break;
890
- case "undefined":
891
- tolerance = 0;
892
- break;
893
- default: throw new TypeError("Invalid clockTolerance option type");
894
- }
895
- const { currentDate } = options;
896
- const now = epoch(currentDate || /* @__PURE__ */ new Date());
897
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new JWTClaimValidationFailed("\"iat\" claim must be a number", payload, "iat", "invalid");
898
- if (payload.nbf !== void 0) {
899
- if (typeof payload.nbf !== "number") throw new JWTClaimValidationFailed("\"nbf\" claim must be a number", payload, "nbf", "invalid");
900
- if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", "check_failed");
901
- }
902
- if (payload.exp !== void 0) {
903
- if (typeof payload.exp !== "number") throw new JWTClaimValidationFailed("\"exp\" claim must be a number", payload, "exp", "invalid");
904
- if (payload.exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", "check_failed");
905
- }
906
- if (maxTokenAge) {
907
- const age = now - payload.iat;
908
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
909
- if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", "check_failed");
910
- if (age < 0 - tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", "check_failed");
535
+ if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed("unexpected \"typ\" JWT header value", payload, "typ", checkFailed);
536
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
537
+ maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
538
+ for (const claim of new Set(presenceCheck.reverse())) if (!Object.hasOwn(payload, claim)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
539
+ 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");
540
+ const { clockTolerance } = options;
541
+ let tolerance = 0;
542
+ if (typeof clockTolerance == "string") tolerance = secs(clockTolerance);
543
+ else if (clockTolerance !== void 0) {
544
+ if (typeof clockTolerance != "number") throw new TypeError("Invalid clockTolerance option type");
545
+ tolerance = clockTolerance;
546
+ }
547
+ validateInput("clockTolerance option", tolerance);
548
+ 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");
549
+ if (nbf !== void 0 && nbf > now + tolerance) throw new JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", payload, "nbf", checkFailed);
550
+ const exp = validateNumericDate(payload, "exp");
551
+ if (exp !== void 0 && exp <= now - tolerance) throw new JWTExpired("\"exp\" claim timestamp check failed", payload, "exp", checkFailed);
552
+ if (maxTokenAge !== void 0) {
553
+ const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
554
+ if (age - tolerance > max) throw new JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", payload, "iat", checkFailed);
555
+ if (age < -tolerance) throw new JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", payload, "iat", checkFailed);
911
556
  }
912
557
  return payload;
913
558
  }
914
559
  //#endregion
915
- //#region node_modules/jose/dist/webapi/jwt/verify.js
560
+ //#region ../../node_modules/jose/dist/webapi/jwt/verify.js
916
561
  async function jwtVerify(jwt, key, options) {
917
- const verified = await compactVerify(jwt, key, options);
918
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
919
- const result = {
920
- payload: validateClaimsSet(verified.protectedHeader, verified.payload, options),
921
- protectedHeader: verified.protectedHeader
922
- };
923
- if (typeof key === "function") return {
924
- ...result,
925
- key: verified.key
562
+ const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
563
+ if (!b64) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
564
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
565
+ return {
566
+ ...verified,
567
+ payload
926
568
  };
927
- return result;
928
569
  }
929
570
  //#endregion
930
- //#region node_modules/jose/dist/webapi/jwks/local.js
931
- function getKtyFromAlg(alg) {
932
- switch (typeof alg === "string" && alg.slice(0, 2)) {
933
- case "RS":
934
- case "PS": return "RSA";
935
- case "ES": return "EC";
936
- case "Ed": return "OKP";
937
- case "ML": return "AKP";
938
- default: throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
939
- }
571
+ //#region ../../node_modules/jose/dist/webapi/jwks/local.js
572
+ function isUsableJWK(jwk, entry, alg, kid) {
573
+ const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;
574
+ 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);
940
575
  }
941
- function isJWKSLike(jwks) {
942
- return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
943
- }
944
- function isJWKLike(key) {
945
- return isObject(key);
946
- }
947
- var LocalJWKSet = class {
948
- #jwks;
949
- #cached = /* @__PURE__ */ new WeakMap();
950
- constructor(jwks) {
951
- if (!isJWKSLike(jwks)) throw new JWKSInvalid("JSON Web Key Set malformed");
952
- this.#jwks = structuredClone(jwks);
953
- }
954
- jwks() {
955
- return this.#jwks;
576
+ async function importWithAlgCache(cache, jwk, entry) {
577
+ const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk), { alg } = entry;
578
+ if (cached[alg] === void 0) {
579
+ const pending = jwkToKey(entry, jwk, !0).then((key) => {
580
+ if (key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys");
581
+ return cached[alg] = key, key;
582
+ }).catch((error) => {
583
+ throw cached[alg] === pending && delete cached[alg], error;
584
+ });
585
+ cached[alg] = pending;
956
586
  }
957
- async getKey(protectedHeader, token) {
587
+ return cached[alg];
588
+ }
589
+ function createLocalJWKSet(jwks) {
590
+ let snapshot;
591
+ try {
592
+ snapshot = structuredClone(jwks);
593
+ } catch {}
594
+ if (!isJwkSet(snapshot)) throw new JWKSInvalid("JSON Web Key Set malformed");
595
+ const metadata = snapshot.keys.map((jwk) => {
596
+ const normalized = snapshotJwk(jwk);
597
+ return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;
598
+ }), cached = /* @__PURE__ */ new WeakMap();
599
+ return Object.defineProperty(async (protectedHeader, token) => {
958
600
  const { alg, kid } = {
959
601
  ...protectedHeader,
960
602
  ...token?.header
961
- };
962
- const kty = getKtyFromAlg(alg);
963
- const candidates = this.#jwks.keys.filter((jwk) => {
964
- let candidate = kty === jwk.kty;
965
- if (candidate && typeof kid === "string") candidate = kid === jwk.kid;
966
- if (candidate && (typeof jwk.alg === "string" || kty === "AKP")) candidate = alg === jwk.alg;
967
- if (candidate && typeof jwk.use === "string") candidate = jwk.use === "sig";
968
- if (candidate && Array.isArray(jwk.key_ops)) candidate = jwk.key_ops.includes("verify");
969
- if (candidate) switch (alg) {
970
- case "ES256":
971
- candidate = jwk.crv === "P-256";
972
- break;
973
- case "ES384":
974
- candidate = jwk.crv === "P-384";
975
- break;
976
- case "ES512":
977
- candidate = jwk.crv === "P-521";
978
- break;
979
- case "Ed25519":
980
- case "EdDSA":
981
- candidate = jwk.crv === "Ed25519";
982
- break;
983
- }
984
- return candidate;
985
- });
986
- const { 0: jwk, length } = candidates;
987
- if (length === 0) throw new JWKSNoMatchingKey();
603
+ }, entry = typeof alg == "string" ? JWS[alg] : void 0;
604
+ if (!entry || entry.secret) throw new JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
605
+ const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length } = candidates;
606
+ if (!length) throw new JWKSNoMatchingKey();
988
607
  if (length !== 1) {
989
608
  const error = new JWKSMultipleMatchingKeys();
990
- const _cached = this.#cached;
991
- error[Symbol.asyncIterator] = async function* () {
992
- for (const jwk of candidates) try {
993
- yield await importWithAlgCache(_cached, jwk, alg);
609
+ throw error[Symbol.asyncIterator] = async function* () {
610
+ for (const jwk2 of candidates) try {
611
+ yield await importWithAlgCache(cached, jwk2, entry);
994
612
  } catch {}
995
- };
996
- throw error;
613
+ }, error;
997
614
  }
998
- return importWithAlgCache(this.#cached, jwk, alg);
999
- }
1000
- };
1001
- async function importWithAlgCache(cache, jwk, alg) {
1002
- const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
1003
- if (cached[alg] === void 0) {
1004
- const key = await importJWK({
1005
- ...jwk,
1006
- ext: true
1007
- }, alg);
1008
- if (key instanceof Uint8Array || key.type !== "public") throw new JWKSInvalid("JSON Web Key Set members must be public keys");
1009
- cached[alg] = key;
1010
- }
1011
- return cached[alg];
1012
- }
1013
- function createLocalJWKSet(jwks) {
1014
- const set = new LocalJWKSet(jwks);
1015
- const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
1016
- Object.defineProperties(localJWKSet, { jwks: {
1017
- value: () => structuredClone(set.jwks()),
1018
- enumerable: false,
1019
- configurable: false,
1020
- writable: false
1021
- } });
1022
- return localJWKSet;
615
+ return importWithAlgCache(cached, jwk, entry);
616
+ }, "jwks", { value: () => structuredClone(snapshot) });
1023
617
  }
1024
618
  //#endregion
1025
- //#region node_modules/jose/dist/webapi/jwks/remote.js
619
+ //#region ../../node_modules/jose/dist/webapi/jwks/remote.js
1026
620
  function isCloudflareWorkers() {
1027
- return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
621
+ return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
1028
622
  }
1029
623
  var USER_AGENT;
1030
- if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.2.3`;
1031
- var customFetch = Symbol();
624
+ (typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (USER_AGENT = "jose/v6.2.12");
625
+ var customFetch = /* @__PURE__ */ Symbol();
1032
626
  async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
1033
627
  const response = await fetchImpl(url, {
1034
628
  method: "GET",
@@ -1036,8 +630,7 @@ async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
1036
630
  redirect: "manual",
1037
631
  headers
1038
632
  }).catch((err) => {
1039
- if (err.name === "TimeoutError") throw new JWKSTimeout();
1040
- throw err;
633
+ throw err.name === "TimeoutError" ? new JWKSTimeout() : err;
1041
634
  });
1042
635
  if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
1043
636
  try {
@@ -1046,121 +639,70 @@ async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
1046
639
  throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
1047
640
  }
1048
641
  }
1049
- var jwksCache = Symbol();
1050
- function isFreshJwksCache(input, cacheMaxAge) {
1051
- if (typeof input !== "object" || input === null) return false;
1052
- if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) return false;
1053
- if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) return false;
1054
- return true;
642
+ var jwksCache = /* @__PURE__ */ Symbol();
643
+ function isFreshFor(timestamp, duration) {
644
+ return Number.isFinite(timestamp) && Date.now() < timestamp + duration;
1055
645
  }
1056
- var RemoteJWKSet = class {
1057
- #url;
1058
- #timeoutDuration;
1059
- #cooldownDuration;
1060
- #cacheMaxAge;
1061
- #jwksTimestamp;
1062
- #pendingFetch;
1063
- #headers;
1064
- #customFetch;
1065
- #local;
1066
- #cache;
1067
- constructor(url, options) {
1068
- if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL");
1069
- this.#url = new URL(url.href);
1070
- this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
1071
- this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
1072
- this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
1073
- this.#headers = new Headers(options?.headers);
1074
- if (USER_AGENT && !this.#headers.has("User-Agent")) this.#headers.set("User-Agent", USER_AGENT);
1075
- if (!this.#headers.has("accept")) {
1076
- this.#headers.set("accept", "application/json");
1077
- this.#headers.append("accept", "application/jwk-set+json");
1078
- }
1079
- this.#customFetch = options?.[customFetch];
1080
- if (options?.[jwksCache] !== void 0) {
1081
- this.#cache = options?.[jwksCache];
1082
- if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
1083
- this.#jwksTimestamp = this.#cache.uat;
1084
- this.#local = createLocalJWKSet(this.#cache.jwks);
1085
- }
646
+ function validateDuration(value, fallback, option) {
647
+ if (Number.isNaN(value)) throw new TypeError(`"${option}" option must not be NaN`);
648
+ return typeof value == "number" ? value : fallback;
649
+ }
650
+ function createRemoteJWKSet(url, options) {
651
+ if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL");
652
+ const href = new URL(url.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;
653
+ if (typeof timeoutOption == "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0)) throw new TypeError("\"timeoutDuration\" option must be a non-negative integer");
654
+ const timeoutDuration = typeof timeoutOption == "number" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge"), headers = new Headers(opts.headers);
655
+ USER_AGENT && !headers.has("User-Agent") && headers.set("User-Agent", USER_AGENT), headers.has("accept") || headers.set("accept", "application/json, application/jwk-set+json");
656
+ const fetchImpl = opts[customFetch], cache = opts[jwksCache];
657
+ let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;
658
+ if (cache && typeof cache == "object") {
659
+ const { uat, jwks } = cache;
660
+ isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));
661
+ }
662
+ const reload = async () => {
663
+ if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {
664
+ const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {
665
+ const next = createLocalJWKSet(json);
666
+ if (sequence <= appliedSequence) return;
667
+ local = next;
668
+ const updatedAt = Date.now();
669
+ cache && (cache.uat = updatedAt, cache.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;
670
+ }).finally(() => {
671
+ pendingFetch === current && (pendingFetch = void 0);
672
+ });
1086
673
  }
1087
- }
1088
- pendingFetch() {
1089
- return !!this.#pendingFetch;
1090
- }
1091
- coolingDown() {
1092
- return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false;
1093
- }
1094
- fresh() {
1095
- return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false;
1096
- }
1097
- jwks() {
1098
- return this.#local?.jwks();
1099
- }
1100
- async getKey(protectedHeader, token) {
1101
- if (!this.#local || !this.fresh()) await this.reload();
674
+ await pendingFetch;
675
+ };
676
+ return Object.defineProperties(async (protectedHeader, token) => {
677
+ (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();
1102
678
  try {
1103
- return await this.#local(protectedHeader, token);
679
+ return await local(protectedHeader, token);
1104
680
  } catch (err) {
1105
- if (err instanceof JWKSNoMatchingKey) {
1106
- if (this.coolingDown() === false) {
1107
- await this.reload();
1108
- return this.#local(protectedHeader, token);
1109
- }
1110
- }
681
+ if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration)) return await reload(), local(protectedHeader, token);
1111
682
  throw err;
1112
683
  }
1113
- }
1114
- async reload() {
1115
- if (this.#pendingFetch && isCloudflareWorkers()) this.#pendingFetch = void 0;
1116
- this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json) => {
1117
- this.#local = createLocalJWKSet(json);
1118
- if (this.#cache) {
1119
- this.#cache.uat = Date.now();
1120
- this.#cache.jwks = json;
1121
- }
1122
- this.#jwksTimestamp = Date.now();
1123
- this.#pendingFetch = void 0;
1124
- }).catch((err) => {
1125
- this.#pendingFetch = void 0;
1126
- throw err;
1127
- });
1128
- await this.#pendingFetch;
1129
- }
1130
- };
1131
- function createRemoteJWKSet(url, options) {
1132
- const set = new RemoteJWKSet(url, options);
1133
- const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
1134
- Object.defineProperties(remoteJWKSet, {
684
+ }, {
1135
685
  coolingDown: {
1136
- get: () => set.coolingDown(),
1137
- enumerable: true,
1138
- configurable: false
686
+ get: () => isFreshFor(jwksTimestamp, cooldownDuration),
687
+ enumerable: !0
1139
688
  },
1140
689
  fresh: {
1141
- get: () => set.fresh(),
1142
- enumerable: true,
1143
- configurable: false
690
+ get: () => isFreshFor(jwksTimestamp, cacheMaxAge),
691
+ enumerable: !0
1144
692
  },
1145
693
  reload: {
1146
- value: () => set.reload(),
1147
- enumerable: true,
1148
- configurable: false,
1149
- writable: false
694
+ value: reload,
695
+ enumerable: !0
1150
696
  },
1151
697
  reloading: {
1152
- get: () => set.pendingFetch(),
1153
- enumerable: true,
1154
- configurable: false
698
+ get: () => !!pendingFetch,
699
+ enumerable: !0
1155
700
  },
1156
701
  jwks: {
1157
- value: () => set.jwks(),
1158
- enumerable: true,
1159
- configurable: false,
1160
- writable: false
702
+ value: () => local?.jwks(),
703
+ enumerable: !0
1161
704
  }
1162
705
  });
1163
- return remoteJWKSet;
1164
706
  }
1165
707
  //#endregion
1166
708
  //#region src/oidc/auth-oidc.addon.ts
@@ -1344,7 +886,7 @@ var AuthOidcAddon = class extends require_dist.BaseAddon {
1344
886
  type: "text",
1345
887
  key: "redirectUri",
1346
888
  label: "Redirect URI override",
1347
- description: "Optional. Default uses CAMSTACK_PUBLIC_ORIGIN + the instance id.",
889
+ description: "Optional. Default uses CAMSTACK_HUB_PUBLIC_URL + the instance id.",
1348
890
  default: ""
1349
891
  },
1350
892
  {
@@ -1438,7 +980,7 @@ var AuthOidcAddon = class extends require_dist.BaseAddon {
1438
980
  if (!inst) throw new Error(`OIDC: no provider configured with id "${providerId}"`);
1439
981
  const configured = inst.config.redirectUri?.trim();
1440
982
  if (configured) return configured;
1441
- return `${(process.env["CAMSTACK_PUBLIC_ORIGIN"] || "https://localhost:4443").replace(/\/+$/, "")}/addon/auth-oidc/${providerId}/callback`;
983
+ return `${(process.env["CAMSTACK_HUB_PUBLIC_URL"] || "https://localhost:4443").replace(/\/+$/, "")}/addon/auth-oidc/${providerId}/callback`;
1442
984
  }
1443
985
  async buildLoginUrl(providerId, state) {
1444
986
  const inst = this.instances.get(providerId);