@alien_org/auth-client 0.0.7-beta

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