@camstack/addon-auth 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1577 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ const require_chunk = require("../chunk-Cek0wNdY.js");
6
+ const require_dist = require("../dist-CXCR7sEk.js");
7
+ let node_crypto = require("node:crypto");
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();
12
+ function concat(...buffers) {
13
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
14
+ const buf = new Uint8Array(size);
15
+ let i = 0;
16
+ for (const buffer of buffers) {
17
+ buf.set(buffer, i);
18
+ i += buffer.length;
19
+ }
20
+ return buf;
21
+ }
22
+ function encode(string) {
23
+ const bytes = new Uint8Array(string.length);
24
+ for (let i = 0; i < string.length; i++) {
25
+ const code = string.charCodeAt(i);
26
+ if (code > 127) throw new TypeError("non-ASCII string encountered in encode()");
27
+ bytes[i] = code;
28
+ }
29
+ return bytes;
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);
37
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
38
+ return bytes;
39
+ }
40
+ //#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
135
+ var JOSEError = class extends Error {
136
+ static code = "ERR_JOSE_GENERIC";
137
+ code = "ERR_JOSE_GENERIC";
138
+ constructor(message, options) {
139
+ super(message, options);
140
+ this.name = this.constructor.name;
141
+ Error.captureStackTrace?.(this, this.constructor);
142
+ }
143
+ };
144
+ var JWTClaimValidationFailed = class extends JOSEError {
145
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
146
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
147
+ claim;
148
+ reason;
149
+ payload;
150
+ constructor(message, payload, claim = "unspecified", reason = "unspecified") {
151
+ super(message, { cause: {
152
+ claim,
153
+ reason,
154
+ payload
155
+ } });
156
+ this.claim = claim;
157
+ this.reason = reason;
158
+ this.payload = payload;
159
+ }
160
+ };
161
+ var JWTExpired = class extends JOSEError {
162
+ static code = "ERR_JWT_EXPIRED";
163
+ code = "ERR_JWT_EXPIRED";
164
+ claim;
165
+ reason;
166
+ payload;
167
+ constructor(message, payload, claim = "unspecified", reason = "unspecified") {
168
+ super(message, { cause: {
169
+ claim,
170
+ reason,
171
+ payload
172
+ } });
173
+ this.claim = claim;
174
+ this.reason = reason;
175
+ this.payload = payload;
176
+ }
177
+ };
178
+ var JOSEAlgNotAllowed = class extends JOSEError {
179
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
180
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
181
+ };
182
+ var JOSENotSupported = class extends JOSEError {
183
+ static code = "ERR_JOSE_NOT_SUPPORTED";
184
+ code = "ERR_JOSE_NOT_SUPPORTED";
185
+ };
186
+ var JWSInvalid = class extends JOSEError {
187
+ static code = "ERR_JWS_INVALID";
188
+ code = "ERR_JWS_INVALID";
189
+ };
190
+ var JWTInvalid = class extends JOSEError {
191
+ static code = "ERR_JWT_INVALID";
192
+ code = "ERR_JWT_INVALID";
193
+ };
194
+ var JWKSInvalid = class extends JOSEError {
195
+ static code = "ERR_JWKS_INVALID";
196
+ code = "ERR_JWKS_INVALID";
197
+ };
198
+ var JWKSNoMatchingKey = class extends JOSEError {
199
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
200
+ code = "ERR_JWKS_NO_MATCHING_KEY";
201
+ constructor(message = "no applicable key found in the JSON Web Key Set", options) {
202
+ super(message, options);
203
+ }
204
+ };
205
+ var JWKSMultipleMatchingKeys = class extends JOSEError {
206
+ [Symbol.asyncIterator];
207
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
208
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
209
+ constructor(message = "multiple matching keys found in the JSON Web Key Set", options) {
210
+ super(message, options);
211
+ }
212
+ };
213
+ var JWKSTimeout = class extends JOSEError {
214
+ static code = "ERR_JWKS_TIMEOUT";
215
+ code = "ERR_JWKS_TIMEOUT";
216
+ constructor(message = "request timed out", options) {
217
+ super(message, options);
218
+ }
219
+ };
220
+ var JWSSignatureVerificationFailed = class extends JOSEError {
221
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
222
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
223
+ constructor(message = "signature verification failed", options) {
224
+ super(message, options);
225
+ }
226
+ };
227
+ //#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) {
242
+ try {
243
+ return decode(value);
244
+ } catch {
245
+ throw new ErrorClass(`Failed to base64url decode the ${label}`);
246
+ }
247
+ }
248
+ //#endregion
249
+ //#region node_modules/jose/dist/webapi/lib/type_checks.js
250
+ var isObjectLike = (value) => typeof value === "object" && value !== null;
251
+ 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;
274
+ }
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
+ }
286
+ }
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`);
322
+ }
323
+ }
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]);
331
+ }
332
+ checkSigCryptoKey(key, alg, usage);
333
+ return key;
334
+ }
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);
339
+ try {
340
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
341
+ } catch {
342
+ return false;
343
+ }
344
+ }
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");
442
+ }
443
+ return {
444
+ algorithm,
445
+ keyUsages
446
+ };
447
+ }
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;
558
+ };
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
+ }
610
+ }
611
+ //#endregion
612
+ //#region node_modules/jose/dist/webapi/lib/validate_crit.js
613
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
614
+ 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;
620
+ 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`);
624
+ }
625
+ return new Set(protectedHeader.crit);
626
+ }
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);
633
+ }
634
+ //#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) => {
638
+ 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
+ }
650
+ if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
651
+ }
652
+ if (key.alg !== void 0 && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
653
+ 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`);
684
+ }
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
+ };
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"`);
708
+ }
709
+ };
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);
720
+ }
721
+ }
722
+ //#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));
735
+ } catch {
736
+ throw new JWSInvalid("JWS Protected Header is invalid");
737
+ }
738
+ if (!isDisjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
739
+ const joseHeader = {
740
+ ...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");
753
+ 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 {
774
+ ...result,
775
+ key: k
776
+ };
777
+ return result;
778
+ }
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");
784
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
785
+ if (length !== 3) throw new JWSInvalid("Invalid Compact JWS");
786
+ const verified = await flattenedVerify({
787
+ payload,
788
+ protected: protectedHeader,
789
+ 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;
800
+ }
801
+ //#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;
810
+ function secs(str) {
811
+ 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;
854
+ }
855
+ 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
+ };
864
+ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
865
+ let payload;
866
+ try {
867
+ payload = JSON.parse(decoder.decode(encodedPayload));
868
+ } catch {}
869
+ if (!isObject(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
870
+ 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");
911
+ }
912
+ return payload;
913
+ }
914
+ //#endregion
915
+ //#region node_modules/jose/dist/webapi/jwt/verify.js
916
+ 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
926
+ };
927
+ return result;
928
+ }
929
+ //#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
+ }
940
+ }
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;
956
+ }
957
+ async getKey(protectedHeader, token) {
958
+ const { alg, kid } = {
959
+ ...protectedHeader,
960
+ ...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();
988
+ if (length !== 1) {
989
+ 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);
994
+ } catch {}
995
+ };
996
+ throw error;
997
+ }
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;
1023
+ }
1024
+ //#endregion
1025
+ //#region node_modules/jose/dist/webapi/jwks/remote.js
1026
+ function isCloudflareWorkers() {
1027
+ return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
1028
+ }
1029
+ var USER_AGENT;
1030
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT = `jose/v6.2.3`;
1031
+ var customFetch = Symbol();
1032
+ async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
1033
+ const response = await fetchImpl(url, {
1034
+ method: "GET",
1035
+ signal,
1036
+ redirect: "manual",
1037
+ headers
1038
+ }).catch((err) => {
1039
+ if (err.name === "TimeoutError") throw new JWKSTimeout();
1040
+ throw err;
1041
+ });
1042
+ if (response.status !== 200) throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
1043
+ try {
1044
+ return await response.json();
1045
+ } catch {
1046
+ throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
1047
+ }
1048
+ }
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;
1055
+ }
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
+ }
1086
+ }
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();
1102
+ try {
1103
+ return await this.#local(protectedHeader, token);
1104
+ } catch (err) {
1105
+ if (err instanceof JWKSNoMatchingKey) {
1106
+ if (this.coolingDown() === false) {
1107
+ await this.reload();
1108
+ return this.#local(protectedHeader, token);
1109
+ }
1110
+ }
1111
+ throw err;
1112
+ }
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, {
1135
+ coolingDown: {
1136
+ get: () => set.coolingDown(),
1137
+ enumerable: true,
1138
+ configurable: false
1139
+ },
1140
+ fresh: {
1141
+ get: () => set.fresh(),
1142
+ enumerable: true,
1143
+ configurable: false
1144
+ },
1145
+ reload: {
1146
+ value: () => set.reload(),
1147
+ enumerable: true,
1148
+ configurable: false,
1149
+ writable: false
1150
+ },
1151
+ reloading: {
1152
+ get: () => set.pendingFetch(),
1153
+ enumerable: true,
1154
+ configurable: false
1155
+ },
1156
+ jwks: {
1157
+ value: () => set.jwks(),
1158
+ enumerable: true,
1159
+ configurable: false,
1160
+ writable: false
1161
+ }
1162
+ });
1163
+ return remoteJWKSet;
1164
+ }
1165
+ //#endregion
1166
+ //#region src/oidc/auth-oidc.addon.ts
1167
+ /**
1168
+ * Generic OpenID Connect (OIDC) authentication provider.
1169
+ *
1170
+ * Multi-provider: ONE addon installation can serve N IdPs (Google AND
1171
+ * Microsoft AND custom). The configuration is a `providers` array,
1172
+ * each entry produces a discrete `/<providerId>/start` route.
1173
+ *
1174
+ * Capabilities registered:
1175
+ * - `auth-provider` (collection, ONE entry) — the actual flow goes
1176
+ * through the routes below; the cap methods (validateCredentials /
1177
+ * handleCallback / getLoginUrl / validateToken) are stubs for the
1178
+ * redirect-flow case.
1179
+ * - `addon-routes` (collection) — `/<providerId>/start` and
1180
+ * `/<providerId>/callback` per configured provider. The handler
1181
+ * reads `:providerId` from the route params, picks the matching
1182
+ * config entry, and runs the OIDC flow against THAT IdP.
1183
+ *
1184
+ * Each provider entry independently performs:
1185
+ * - PKCE S256 + nonce
1186
+ * - id_token signature verification via `jose.jwtVerify` against the
1187
+ * IdP's JWKS (issuer + audience + exp + nbf enforced)
1188
+ * - Replay defense: nonce claim must match the value sent at /start
1189
+ *
1190
+ * The bridge token minted at /callback flows back to /api/auth/sso/finish
1191
+ * — the hub verifies it with the same `jwtSecret` and only then mints
1192
+ * the user session JWT.
1193
+ *
1194
+ * TODO (next session):
1195
+ * - RP-initiated logout (`end_session_endpoint` 302 with id_token_hint).
1196
+ * - Groups → scope mapping via id_token `groups` claim.
1197
+ * - Refresh token rotation (offline_access).
1198
+ * - Persist state + nonce + PKCE across restart (multi-replica).
1199
+ */
1200
+ var DEFAULT_PROVIDER = {
1201
+ id: "default",
1202
+ displayName: "OpenID Connect",
1203
+ icon: "shield-check",
1204
+ issuerUrl: "",
1205
+ clientId: "",
1206
+ clientSecret: "",
1207
+ redirectUri: "",
1208
+ scopes: "openid profile email",
1209
+ usernameClaim: "preferred_username",
1210
+ defaultRole: "viewer"
1211
+ };
1212
+ var DEFAULT_CONFIG = { providers: [] };
1213
+ var STATE_TTL_MS = 5 * 6e4;
1214
+ var AuthOidcAddon = class extends require_dist.BaseAddon {
1215
+ /** Per-provider runtime state, keyed by `provider.id`. */
1216
+ instances = /* @__PURE__ */ new Map();
1217
+ /** Pending OAuth states across ALL providers. The pending entry
1218
+ * carries `providerId` so the /callback handler picks the right config. */
1219
+ pendingStates = /* @__PURE__ */ new Map();
1220
+ constructor() {
1221
+ super({ ...DEFAULT_CONFIG });
1222
+ }
1223
+ async onInitialize() {
1224
+ this.rebuildInstances();
1225
+ const authProvider = {
1226
+ validateCredentials: async () => null,
1227
+ validateToken: async ({ token }) => this.validateLocalSessionToken(token),
1228
+ getLoginUrl: async ({ state }) => {
1229
+ const first = this.firstInstance();
1230
+ if (!first) throw new Error("OIDC: no providers configured");
1231
+ return this.buildLoginUrl(first.config.id, state);
1232
+ },
1233
+ handleCallback: async (params) => {
1234
+ const code = params["code"];
1235
+ const state = params["state"];
1236
+ if (!code || !state) throw new Error("Missing code or state in OIDC callback");
1237
+ return this.handleCallback(code, state);
1238
+ }
1239
+ };
1240
+ const routes = [{
1241
+ method: "GET",
1242
+ path: "/:providerId/start",
1243
+ access: "public",
1244
+ description: "Begin OIDC redirect login flow for a configured provider",
1245
+ handler: async (req, reply) => this.handleStart(req, reply)
1246
+ }, {
1247
+ method: "GET",
1248
+ path: "/:providerId/callback",
1249
+ access: "public",
1250
+ description: "OIDC redirect callback for a configured provider",
1251
+ handler: async (req, reply) => this.handleCallbackRoute(req, reply)
1252
+ }];
1253
+ const routeProvider = {
1254
+ id: "auth-oidc",
1255
+ getRoutes: () => routes
1256
+ };
1257
+ this.ctx.logger.info("OIDC auth provider initialized", { meta: { providers: [...this.instances.keys()] } });
1258
+ return [{
1259
+ capability: require_dist.authProviderCapability,
1260
+ provider: authProvider
1261
+ }, {
1262
+ capability: require_dist.addonRoutesCapability,
1263
+ provider: routeProvider
1264
+ }];
1265
+ }
1266
+ globalSettingsSchema() {
1267
+ return this.schema({ sections: [{
1268
+ id: "oidc",
1269
+ title: "OIDC Providers",
1270
+ description: "Configure one or more IdPs (Google, Microsoft, Okta, Keycloak, …). Each entry produces an independent login button. The redirect URI shown on the IdP-side must include the provider id in the path: `<origin>/addon/auth-oidc/<id>/callback`.",
1271
+ columns: 1,
1272
+ fields: [this.field({
1273
+ type: "editable-array",
1274
+ key: "providers",
1275
+ label: "Providers",
1276
+ description: "Each row is a distinct OIDC IdP. Click + to add.",
1277
+ default: [],
1278
+ itemFields: [
1279
+ {
1280
+ type: "text",
1281
+ key: "id",
1282
+ label: "Instance id",
1283
+ description: "URL-friendly slug — appears in the redirect URI as /addon/auth-oidc/<id>/callback. Stable; renaming breaks any IdP-side registrations.",
1284
+ default: ""
1285
+ },
1286
+ {
1287
+ type: "text",
1288
+ key: "displayName",
1289
+ label: "Display name",
1290
+ description: "Shown on the login button.",
1291
+ default: "OpenID Connect"
1292
+ },
1293
+ {
1294
+ type: "text",
1295
+ key: "icon",
1296
+ label: "Icon",
1297
+ description: "lucide-react icon name (default: shield-check).",
1298
+ default: "shield-check"
1299
+ },
1300
+ {
1301
+ type: "text",
1302
+ key: "issuerUrl",
1303
+ label: "Issuer URL",
1304
+ description: "IdP base URL — discovery doc lives at <issuer>/.well-known/openid-configuration.",
1305
+ default: ""
1306
+ },
1307
+ {
1308
+ type: "text",
1309
+ key: "clientId",
1310
+ label: "Client ID",
1311
+ default: ""
1312
+ },
1313
+ {
1314
+ type: "text",
1315
+ key: "clientSecret",
1316
+ label: "Client Secret",
1317
+ default: ""
1318
+ },
1319
+ {
1320
+ type: "text",
1321
+ key: "redirectUri",
1322
+ label: "Redirect URI override",
1323
+ description: "Optional. Default uses CAMSTACK_PUBLIC_ORIGIN + the instance id.",
1324
+ default: ""
1325
+ },
1326
+ {
1327
+ type: "text",
1328
+ key: "scopes",
1329
+ label: "Scopes",
1330
+ description: "Space-separated.",
1331
+ default: "openid profile email"
1332
+ },
1333
+ {
1334
+ type: "select",
1335
+ key: "usernameClaim",
1336
+ label: "Username claim",
1337
+ default: "preferred_username",
1338
+ options: [
1339
+ {
1340
+ value: "preferred_username",
1341
+ label: "preferred_username"
1342
+ },
1343
+ {
1344
+ value: "email",
1345
+ label: "email"
1346
+ },
1347
+ {
1348
+ value: "sub",
1349
+ label: "sub (user id)"
1350
+ }
1351
+ ]
1352
+ },
1353
+ {
1354
+ type: "select",
1355
+ key: "defaultRole",
1356
+ label: "Default role",
1357
+ description: "Role assigned to first-time SSO users.",
1358
+ default: "viewer",
1359
+ options: [{
1360
+ value: "viewer",
1361
+ label: "Viewer"
1362
+ }, {
1363
+ value: "admin",
1364
+ label: "Admin"
1365
+ }]
1366
+ }
1367
+ ]
1368
+ })]
1369
+ }] });
1370
+ }
1371
+ rebuildInstances() {
1372
+ this.instances.clear();
1373
+ const providers = this.config.providers ?? [];
1374
+ for (const raw of providers) {
1375
+ const merged = {
1376
+ ...DEFAULT_PROVIDER,
1377
+ ...raw
1378
+ };
1379
+ if (!merged.id || !merged.id.trim()) continue;
1380
+ this.instances.set(merged.id, {
1381
+ config: merged,
1382
+ discovery: null,
1383
+ discoveryFetchedAt: 0,
1384
+ jwks: null,
1385
+ jwksUri: null
1386
+ });
1387
+ }
1388
+ }
1389
+ firstInstance() {
1390
+ const first = this.instances.values().next();
1391
+ return first.done ? null : first.value;
1392
+ }
1393
+ async getDiscovery(providerId) {
1394
+ const inst = this.instances.get(providerId);
1395
+ if (!inst) throw new Error(`OIDC: no provider configured with id "${providerId}"`);
1396
+ if (inst.discovery && Date.now() - inst.discoveryFetchedAt < 60 * 6e4) return inst.discovery;
1397
+ const issuer = inst.config.issuerUrl?.replace(/\/+$/, "");
1398
+ if (!issuer) throw new Error(`OIDC provider "${providerId}": issuerUrl not configured`);
1399
+ const url = `${issuer}/.well-known/openid-configuration`;
1400
+ const res = await fetch(url);
1401
+ if (!res.ok) throw new Error(`OIDC discovery failed: ${res.status} ${res.statusText}`);
1402
+ const doc = await res.json();
1403
+ if (!doc.authorization_endpoint || !doc.token_endpoint) throw new Error("OIDC discovery response missing required endpoints");
1404
+ inst.discovery = doc;
1405
+ inst.discoveryFetchedAt = Date.now();
1406
+ if (doc.jwks_uri && doc.jwks_uri !== inst.jwksUri) {
1407
+ inst.jwks = createRemoteJWKSet(new URL(doc.jwks_uri));
1408
+ inst.jwksUri = doc.jwks_uri;
1409
+ }
1410
+ return doc;
1411
+ }
1412
+ buildRedirectUri(providerId) {
1413
+ const inst = this.instances.get(providerId);
1414
+ if (!inst) throw new Error(`OIDC: no provider configured with id "${providerId}"`);
1415
+ const configured = inst.config.redirectUri?.trim();
1416
+ if (configured) return configured;
1417
+ return `${(process.env["CAMSTACK_PUBLIC_ORIGIN"] || "https://localhost:4443").replace(/\/+$/, "")}/addon/auth-oidc/${providerId}/callback`;
1418
+ }
1419
+ async buildLoginUrl(providerId, state) {
1420
+ const inst = this.instances.get(providerId);
1421
+ if (!inst) throw new Error(`OIDC: no provider configured with id "${providerId}"`);
1422
+ const doc = await this.getDiscovery(providerId);
1423
+ const codeVerifier = node_crypto.randomBytes(32).toString("base64url");
1424
+ const codeChallenge = node_crypto.createHash("sha256").update(codeVerifier).digest("base64url");
1425
+ const nonce = node_crypto.randomBytes(16).toString("base64url");
1426
+ this.pruneExpiredStates();
1427
+ this.pendingStates.set(state, {
1428
+ codeVerifier,
1429
+ nonce,
1430
+ providerId,
1431
+ createdAt: Date.now()
1432
+ });
1433
+ const params = new URLSearchParams({
1434
+ response_type: "code",
1435
+ client_id: inst.config.clientId,
1436
+ redirect_uri: this.buildRedirectUri(providerId),
1437
+ scope: inst.config.scopes || DEFAULT_PROVIDER.scopes,
1438
+ state,
1439
+ nonce,
1440
+ code_challenge: codeChallenge,
1441
+ code_challenge_method: "S256"
1442
+ });
1443
+ return `${doc.authorization_endpoint}?${params.toString()}`;
1444
+ }
1445
+ pruneExpiredStates() {
1446
+ const now = Date.now();
1447
+ for (const [k, v] of this.pendingStates.entries()) if (now - v.createdAt > STATE_TTL_MS) this.pendingStates.delete(k);
1448
+ }
1449
+ async handleCallback(code, state) {
1450
+ const pending = this.pendingStates.get(state);
1451
+ if (!pending) throw new Error("Unknown or expired OIDC state — login session timed out, please retry");
1452
+ this.pendingStates.delete(state);
1453
+ const providerId = pending.providerId;
1454
+ const inst = this.instances.get(providerId);
1455
+ if (!inst) throw new Error(`OIDC: provider "${providerId}" no longer configured`);
1456
+ const doc = await this.getDiscovery(providerId);
1457
+ const tokenRes = await fetch(doc.token_endpoint, {
1458
+ method: "POST",
1459
+ headers: {
1460
+ "Content-Type": "application/x-www-form-urlencoded",
1461
+ Accept: "application/json"
1462
+ },
1463
+ body: new URLSearchParams({
1464
+ grant_type: "authorization_code",
1465
+ code,
1466
+ redirect_uri: this.buildRedirectUri(providerId),
1467
+ client_id: inst.config.clientId,
1468
+ client_secret: inst.config.clientSecret,
1469
+ code_verifier: pending.codeVerifier
1470
+ })
1471
+ });
1472
+ if (!tokenRes.ok) {
1473
+ const text = await tokenRes.text().catch(() => "");
1474
+ throw new Error(`OIDC token exchange failed: ${tokenRes.status} ${tokenRes.statusText} — ${text.slice(0, 200)}`);
1475
+ }
1476
+ const tokens = await tokenRes.json();
1477
+ if (!tokens.id_token) throw new Error("OIDC token response missing id_token");
1478
+ if (!inst.jwks) throw new Error("OIDC discovery doc missing jwks_uri — cannot verify id_token signature");
1479
+ let payload;
1480
+ try {
1481
+ payload = (await jwtVerify(tokens.id_token, inst.jwks, {
1482
+ issuer: doc.issuer,
1483
+ audience: inst.config.clientId
1484
+ })).payload;
1485
+ } catch (err) {
1486
+ throw new Error(`OIDC id_token verification failed: ${require_dist.errMsg(err)}`, { cause: err });
1487
+ }
1488
+ if (typeof payload["nonce"] !== "string" || payload["nonce"] !== pending.nonce) throw new Error("OIDC id_token nonce mismatch — possible replay attack");
1489
+ const sub = typeof payload.sub === "string" ? payload.sub : null;
1490
+ if (!sub) throw new Error("OIDC callback: id_token missing required `sub` claim");
1491
+ const emailClaim = typeof payload["email"] === "string" ? payload["email"] : void 0;
1492
+ const preferredClaim = typeof payload["preferred_username"] === "string" ? payload["preferred_username"] : void 0;
1493
+ const nameClaim = typeof payload["name"] === "string" ? payload["name"] : void 0;
1494
+ const usernameClaim = inst.config.usernameClaim;
1495
+ const username = usernameClaim === "preferred_username" && preferredClaim || usernameClaim === "email" && emailClaim || sub;
1496
+ return {
1497
+ userId: `oidc:${providerId}:${sub}`,
1498
+ username: String(username),
1499
+ ...emailClaim ? { email: emailClaim } : {},
1500
+ ...nameClaim ? { displayName: nameClaim } : {},
1501
+ isAdmin: inst.config.defaultRole === "admin"
1502
+ };
1503
+ }
1504
+ validateLocalSessionToken(_token) {
1505
+ return null;
1506
+ }
1507
+ async handleStart(req, reply) {
1508
+ const providerId = req.params["providerId"] ?? "";
1509
+ if (!this.instances.has(providerId)) {
1510
+ reply.code(404);
1511
+ reply.send({ error: `Unknown OIDC provider: ${providerId}` });
1512
+ return;
1513
+ }
1514
+ const state = node_crypto.randomBytes(16).toString("base64url");
1515
+ try {
1516
+ const url = await this.buildLoginUrl(providerId, state);
1517
+ reply.code(302);
1518
+ reply.header("Location", url);
1519
+ reply.send("");
1520
+ } catch (err) {
1521
+ reply.code(500);
1522
+ reply.send({
1523
+ error: "OIDC start failed",
1524
+ message: require_dist.errMsg(err)
1525
+ });
1526
+ }
1527
+ }
1528
+ async handleCallbackRoute(req, reply) {
1529
+ const providerId = req.params["providerId"] ?? "";
1530
+ if (!this.instances.has(providerId)) {
1531
+ reply.code(404);
1532
+ reply.send({ error: `Unknown OIDC provider: ${providerId}` });
1533
+ return;
1534
+ }
1535
+ const query = req.query;
1536
+ const code = query["code"];
1537
+ const state = query["state"];
1538
+ const errorParam = query["error"];
1539
+ if (errorParam) {
1540
+ reply.code(400);
1541
+ reply.send({
1542
+ error: "OIDC error",
1543
+ detail: errorParam,
1544
+ description: query["error_description"]
1545
+ });
1546
+ return;
1547
+ }
1548
+ if (!code || !state) {
1549
+ reply.code(400);
1550
+ reply.send({ error: "Missing code or state" });
1551
+ return;
1552
+ }
1553
+ try {
1554
+ const result = await this.handleCallback(code, state);
1555
+ const { token: bridgeToken } = await this.ctx.api.ssoBridge.signBridgeToken.query({ claims: {
1556
+ userId: result.userId,
1557
+ username: result.username,
1558
+ isAdmin: result.isAdmin,
1559
+ provider: `auth-oidc/${providerId}`,
1560
+ ...result.email ? { email: result.email } : {},
1561
+ ...result.displayName ? { displayName: result.displayName } : {}
1562
+ } });
1563
+ reply.code(302);
1564
+ reply.header("Location", `/api/auth/sso/finish?bridge=${encodeURIComponent(bridgeToken)}`);
1565
+ reply.send("");
1566
+ } catch (err) {
1567
+ reply.code(500);
1568
+ reply.send({
1569
+ error: "OIDC callback failed",
1570
+ message: require_dist.errMsg(err)
1571
+ });
1572
+ }
1573
+ }
1574
+ };
1575
+ //#endregion
1576
+ exports.AuthOidcAddon = AuthOidcAddon;
1577
+ exports.default = AuthOidcAddon;