kinde-testkit 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,12 +20,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
+ ActivityLog: () => ActivityLog,
23
24
  BILLING_EVENT_TYPES: () => BILLING_EVENT_TYPES,
25
+ COVERAGE_GROUPS: () => COVERAGE_GROUPS,
26
+ CoverageRecorder: () => CoverageRecorder,
24
27
  DEFAULT_AUTH_METHODS: () => DEFAULT_AUTH_METHODS,
25
28
  DEFAULT_CLIENT_ID: () => DEFAULT_CLIENT_ID,
29
+ DEFAULT_COVERAGE_DIRECTORY: () => DEFAULT_COVERAGE_DIRECTORY,
26
30
  DEFAULT_ISSUER: () => DEFAULT_ISSUER,
27
31
  DEFAULT_M2M_CLIENT_ID: () => DEFAULT_M2M_CLIENT_ID,
28
32
  DEFAULT_SCOPES: () => DEFAULT_SCOPES,
33
+ DEFAULT_SEED_FILES: () => DEFAULT_SEED_FILES,
29
34
  Directory: () => Directory,
30
35
  FailureInjector: () => FailureInjector,
31
36
  INVALID_TOKEN_KINDS: () => INVALID_TOKEN_KINDS,
@@ -34,22 +39,35 @@ __export(src_exports, {
34
39
  TestkitError: () => TestkitError,
35
40
  WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
36
41
  WebhookDispatcher: () => WebhookDispatcher,
42
+ appLoginUrl: () => appLoginUrl,
43
+ buildReport: () => buildReport,
44
+ clearCoverageDirectory: () => clearCoverageDirectory,
37
45
  createKindeOrganization: () => createKindeOrganization,
38
46
  createKindeToken: () => createKindeToken,
39
47
  createKindeUser: () => createKindeUser,
40
48
  createLocalCertificate: () => createLocalCertificate,
41
49
  createMembership: () => createMembership,
42
50
  ensureLocalCertificate: () => ensureLocalCertificate,
51
+ findSeedFile: () => findSeedFile,
52
+ formatCoverageReport: () => formatCoverageReport,
43
53
  getDefaultTestkit: () => getDefaultTestkit,
44
54
  inspectToken: () => inspectToken,
45
55
  isAuthenticated: () => isAuthenticated,
56
+ kindeTest: () => kindeTest,
57
+ loadSeedFile: () => loadSeedFile,
58
+ mergeSnapshots: () => mergeSnapshots,
46
59
  parseEnvFile: () => parseEnvFile,
47
60
  principalFromClaims: () => principalFromClaims,
61
+ readCoverageDirectory: () => readCoverageDirectory,
62
+ readSignInRequest: () => readSignInRequest,
48
63
  resetFactories: () => resetFactories,
64
+ resolveLocation: () => resolveLocation,
49
65
  resolveSeed: () => resolveSeed,
50
66
  runDoctor: () => runDoctor,
51
67
  scenario: () => scenario,
52
68
  seedScenario: () => seedScenario,
69
+ signInFailure: () => signInFailure,
70
+ signInForm: () => signInForm,
53
71
  startKindeTestkit: () => startKindeTestkit,
54
72
  toKindeRole: () => toKindeRole
55
73
  });
@@ -176,16 +194,1148 @@ function isAuthenticated(value) {
176
194
 
177
195
  // src/testkit.ts
178
196
  var import_node_crypto2 = require("crypto");
179
- var import_jose = require("jose");
197
+
198
+ // node_modules/jose/dist/webapi/lib/buffer_utils.js
199
+ var encoder = new TextEncoder();
200
+ var decoder = new TextDecoder();
201
+ var strictDecoder = new TextDecoder("utf-8", { fatal: true });
202
+ var UINT32_RANGE = 2 ** 32;
203
+ function concat(...buffers) {
204
+ const size = buffers.reduce((acc, { length: length2 }) => acc + length2, 0), buf = new Uint8Array(size);
205
+ let i = 0;
206
+ for (const buffer of buffers)
207
+ buf.set(buffer, i), i += buffer.length;
208
+ return buf;
209
+ }
210
+ var NON_ASCII = /[^\x00-\x7f]/;
211
+ function encode(string) {
212
+ if (typeof string == "string" && string.length >= 128) {
213
+ if (NON_ASCII.test(string))
214
+ throw new TypeError("non-ASCII string encountered in encode()");
215
+ return encoder.encode(string);
216
+ }
217
+ const bytes = new Uint8Array(string.length);
218
+ for (let i = 0; i < string.length; i++) {
219
+ const code = string.charCodeAt(i);
220
+ if (code > 127)
221
+ throw new TypeError("non-ASCII string encountered in encode()");
222
+ bytes[i] = code;
223
+ }
224
+ return bytes;
225
+ }
226
+ function encodeBase64(input, url = false) {
227
+ if (Uint8Array.prototype.toBase64)
228
+ return input.toBase64({ alphabet: url ? "base64url" : "base64", omitPadding: url });
229
+ const CHUNK_SIZE = 32768, arr = [];
230
+ for (let i = 0; i < input.length; i += CHUNK_SIZE)
231
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
232
+ const encoded = btoa(arr.join(""));
233
+ return url ? encoded.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") : encoded;
234
+ }
235
+ function decodeBase64(encoded, url = false) {
236
+ if (Uint8Array.fromBase64)
237
+ return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
238
+ if (url) {
239
+ if (encoded.includes("+") || encoded.includes("/"))
240
+ throw new TypeError("Invalid base64url");
241
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
242
+ }
243
+ const binary = atob(encoded), bytes = new Uint8Array(binary.length);
244
+ for (let i = 0; i < binary.length; i++)
245
+ bytes[i] = binary.charCodeAt(i);
246
+ return bytes;
247
+ }
248
+ async function digest(algorithm, data) {
249
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
250
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
251
+ }
252
+
253
+ // node_modules/jose/dist/webapi/util/errors.js
254
+ var JOSEError = class extends Error {
255
+ static code = "ERR_JOSE_GENERIC";
256
+ code = "ERR_JOSE_GENERIC";
257
+ constructor(message2, options) {
258
+ super(message2, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
259
+ }
260
+ };
261
+ var JWTClaimValidationFailed = class extends JOSEError {
262
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
263
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
264
+ claim;
265
+ reason;
266
+ payload;
267
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
268
+ super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;
269
+ }
270
+ };
271
+ var JWTExpired = class extends JOSEError {
272
+ static code = "ERR_JWT_EXPIRED";
273
+ code = "ERR_JWT_EXPIRED";
274
+ claim;
275
+ reason;
276
+ payload;
277
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
278
+ super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;
279
+ }
280
+ };
281
+ var JOSEAlgNotAllowed = class extends JOSEError {
282
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
283
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
284
+ };
285
+ var JOSENotSupported = class extends JOSEError {
286
+ static code = "ERR_JOSE_NOT_SUPPORTED";
287
+ code = "ERR_JOSE_NOT_SUPPORTED";
288
+ };
289
+ var JWSInvalid = class extends JOSEError {
290
+ static code = "ERR_JWS_INVALID";
291
+ code = "ERR_JWS_INVALID";
292
+ };
293
+ var JWTInvalid = class extends JOSEError {
294
+ static code = "ERR_JWT_INVALID";
295
+ code = "ERR_JWT_INVALID";
296
+ };
297
+ var JWKInvalid = class extends JOSEError {
298
+ static code = "ERR_JWK_INVALID";
299
+ code = "ERR_JWK_INVALID";
300
+ };
301
+ var JWKSInvalid = class extends JOSEError {
302
+ static code = "ERR_JWKS_INVALID";
303
+ code = "ERR_JWKS_INVALID";
304
+ };
305
+ var JWKSNoMatchingKey = class extends JOSEError {
306
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
307
+ code = "ERR_JWKS_NO_MATCHING_KEY";
308
+ constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
309
+ super(message2, options);
310
+ }
311
+ };
312
+ var JWKSMultipleMatchingKeys = class extends JOSEError {
313
+ [Symbol.asyncIterator] = async function* () {
314
+ };
315
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
316
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
317
+ constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
318
+ super(message2, options);
319
+ }
320
+ };
321
+ var JWKSTimeout = class extends JOSEError {
322
+ static code = "ERR_JWKS_TIMEOUT";
323
+ code = "ERR_JWKS_TIMEOUT";
324
+ constructor(message2 = "request timed out", options) {
325
+ super(message2, options);
326
+ }
327
+ };
328
+ var JWSSignatureVerificationFailed = class extends JOSEError {
329
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
330
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
331
+ constructor(message2 = "signature verification failed", options) {
332
+ super(message2, options);
333
+ }
334
+ };
335
+
336
+ // node_modules/jose/dist/webapi/util/base64url.js
337
+ var base64url_exports = {};
338
+ __export(base64url_exports, {
339
+ decode: () => decode,
340
+ encode: () => encode2
341
+ });
342
+ var invalid = "The input to be decoded is not correctly encoded.";
343
+ function decode(input) {
344
+ try {
345
+ return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true);
346
+ } catch (cause) {
347
+ throw new TypeError(invalid, { cause });
348
+ }
349
+ }
350
+ function encode2(input) {
351
+ return encodeBase64(typeof input == "string" ? encoder.encode(input) : input, true);
352
+ }
353
+
354
+ // node_modules/jose/dist/webapi/lib/validate.js
355
+ function isObject(input) {
356
+ if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]")
357
+ return false;
358
+ const prototype = Object.getPrototypeOf(input);
359
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
360
+ }
361
+ function isJwkSet(input) {
362
+ return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);
363
+ }
364
+ function isDisjoint(...headers) {
365
+ const parameters = /* @__PURE__ */ new Set();
366
+ for (const header of headers)
367
+ if (header)
368
+ for (const parameter of Object.keys(header)) {
369
+ if (parameters.has(parameter))
370
+ return false;
371
+ parameters.add(parameter);
372
+ }
373
+ return true;
374
+ }
375
+ function assertNotSet(value, name) {
376
+ if (value !== void 0)
377
+ throw new TypeError(`${name} can only be called once`);
378
+ }
379
+ function decodeBase64url(value, label, ErrorClass) {
380
+ try {
381
+ return decode(value);
382
+ } catch (cause) {
383
+ throw new ErrorClass(`Failed to base64url decode the ${label}`, { cause });
384
+ }
385
+ }
386
+ function encodeAsciiMember(value, label, ErrorClass) {
387
+ try {
388
+ return encode(value);
389
+ } catch (cause) {
390
+ throw new ErrorClass(`The ${label} is not a valid base64url string`, { cause });
391
+ }
392
+ }
393
+ function parseJoseHeader(encodedProtectedHeader, ErrorClass, message2) {
394
+ let parsed;
395
+ try {
396
+ parsed = JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)));
397
+ } catch (cause) {
398
+ throw new ErrorClass(message2, { cause });
399
+ }
400
+ if (!isObject(parsed))
401
+ throw new ErrorClass(message2);
402
+ return parsed;
403
+ }
404
+ var JWS_RECOGNIZED = { __proto__: null, b64: true };
405
+ function validateAlgorithms(option, algorithms) {
406
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string")))
407
+ throw new TypeError(`"${option}" option must be an array of strings`);
408
+ return algorithms === void 0 ? void 0 : new Set(algorithms);
409
+ }
410
+ function validateCritDuplicates(Err, protectedHeader) {
411
+ const { crit } = protectedHeader ?? {};
412
+ if (Array.isArray(crit) && new Set(crit).size !== crit.length)
413
+ throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
414
+ }
415
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
416
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)
417
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
418
+ if (!protectedHeader || protectedHeader.crit === void 0)
419
+ return [];
420
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0))
421
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
422
+ const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
423
+ for (const parameter of protectedHeader.crit) {
424
+ if (!(parameter in recognized))
425
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
426
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)
427
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
428
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))
429
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
430
+ }
431
+ return protectedHeader.crit;
432
+ }
433
+ function validateB64(protectedHeader, extensions) {
434
+ if (extensions.includes("b64")) {
435
+ const b64 = protectedHeader.b64;
436
+ if (typeof b64 != "boolean")
437
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
438
+ return b64;
439
+ }
440
+ return true;
441
+ }
442
+ function serializeJoseHeader(Err, header) {
443
+ let serialized, parsed;
444
+ try {
445
+ serialized = JSON.stringify(header), parsed = JSON.parse(serialized);
446
+ } catch (cause) {
447
+ throw new Err("JOSE Header is not valid JSON", { cause });
448
+ }
449
+ if (!isObject(parsed))
450
+ throw new Err("JOSE Header is not a JSON object");
451
+ return [parsed, serialized];
452
+ }
453
+
454
+ // node_modules/jose/dist/webapi/lib/key.js
455
+ var tag = (key) => key[Symbol.toStringTag];
456
+ var jwkMatchesOp = (entry, key, usage) => {
457
+ const { alg } = entry;
458
+ if (key.use !== void 0) {
459
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
460
+ if (key.use !== expected)
461
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
462
+ }
463
+ if (key.alg !== void 0 && key.alg !== alg)
464
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
465
+ if (Array.isArray(key.key_ops)) {
466
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
467
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))
468
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
469
+ }
470
+ };
471
+ async function prepareKey(entry, key, usage) {
472
+ const { alg, secret } = entry, requiresPrivateKey = usage === "decrypt" || usage === "sign";
473
+ if (secret && key instanceof Uint8Array)
474
+ return key;
475
+ let normalized, keyObject;
476
+ if (isObject(key)) {
477
+ if (normalized = normalizeJwk(key), typeof normalized.kty != "string")
478
+ throw invalidKeyType(alg, key, secret);
479
+ if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (requiresPrivateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0)))
480
+ throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present' : `JSON Web Key for this operation must be a ${requiresPrivateKey ? "private" : "public"} JWK`);
481
+ if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct")
482
+ return decode(normalized.k);
483
+ if (!Object.isFrozen(key)) {
484
+ const { key_ops } = key;
485
+ Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
486
+ }
487
+ } else {
488
+ if (!isKeyLike(key))
489
+ throw invalidKeyType(alg, key, secret);
490
+ const expectedType = secret ? "secret" : requiresPrivateKey ? "private" : "public";
491
+ if (key.type !== expectedType && (secret || ["secret", "public", "private"].includes(key.type)))
492
+ throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
493
+ if (isCryptoKey(key))
494
+ return key;
495
+ if (keyObject = key, keyObject.type === "secret")
496
+ return keyObject.export();
497
+ }
498
+ cache ||= /* @__PURE__ */ new WeakMap();
499
+ const cacheKey = key;
500
+ let cached = cache.get(cacheKey);
501
+ if (cached?.[alg])
502
+ return cached[alg];
503
+ if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
504
+ const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;
505
+ return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
506
+ }
507
+ return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);
508
+ }
509
+ var cache;
510
+ var nist = {
511
+ __proto__: null,
512
+ prime256v1: "P-256",
513
+ secp384r1: "P-384",
514
+ secp521r1: "P-521"
515
+ };
516
+ var isCryptoKey = (key) => {
517
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
518
+ return true;
519
+ try {
520
+ return key instanceof CryptoKey;
521
+ } catch {
522
+ return false;
523
+ }
524
+ };
525
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
526
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
527
+ function message(msg, actual, ...types) {
528
+ if (types.length > 2) {
529
+ const last = types.pop();
530
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
531
+ } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
532
+ return actual == null ? msg += ` Received ${actual}` : typeof actual == "function" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == "object" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;
533
+ }
534
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
535
+ function invalidKeyType(alg, actual, secret) {
536
+ const types = ["CryptoKey", "KeyObject", "JSON Web Key"];
537
+ return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
538
+ }
539
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
540
+ function checkUsage(key, usage) {
541
+ if (usage && !key.usages.includes(usage))
542
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
543
+ }
544
+ function checkModulusLength(alg, key) {
545
+ const { modulusLength } = key.algorithm;
546
+ if (typeof modulusLength != "number" || modulusLength < 2048)
547
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
548
+ }
549
+ function checkCryptoKey(key, expected, usage) {
550
+ const algorithm = key.algorithm;
551
+ if (algorithm.name !== expected.name)
552
+ throw unusable(expected.name);
553
+ if (expected.hash && algorithm.hash?.name !== expected.hash)
554
+ throw unusable(expected.hash, "algorithm.hash");
555
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)
556
+ throw unusable(expected.namedCurve, "algorithm.namedCurve");
557
+ if (expected.length !== void 0 && algorithm.length !== expected.length)
558
+ throw unusable(expected.length, "algorithm.length");
559
+ checkUsage(key, usage);
560
+ }
561
+ function snapshotJwk(jwk) {
562
+ return { __proto__: null, ...jwk };
563
+ }
564
+ function normalizeJwk(jwk) {
565
+ const normalized = snapshotJwk(jwk);
566
+ if (normalized.ext !== void 0 && typeof normalized.ext != "boolean")
567
+ throw new TypeError('"ext" (Extractable) Parameter must be a boolean');
568
+ if (normalized.key_ops !== void 0) {
569
+ const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
570
+ if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length)
571
+ throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');
572
+ normalized.key_ops = keyOps;
573
+ }
574
+ return normalized;
575
+ }
576
+ function validateExtractableOption(extractable) {
577
+ if (extractable !== void 0 && typeof extractable != "boolean")
578
+ throw new TypeError('"extractable" option must be a boolean');
579
+ return extractable;
580
+ }
581
+ async function jwkToKey(entry, jwk, extractable) {
582
+ if (!entry.kty.includes(jwk.kty))
583
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
584
+ const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };
585
+ return keyData.kty !== "AKP" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey("jwk", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
586
+ }
587
+ async function rawKey(key, expected, usage, extractable = false) {
588
+ return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
589
+ }
590
+
591
+ // node_modules/jose/dist/webapi/lib/key_descriptor.js
592
+ function table(entries) {
593
+ const out = { __proto__: null };
594
+ for (const alg in entries)
595
+ out[alg] = { ...entries[alg], alg };
596
+ return out;
597
+ }
598
+
599
+ // node_modules/jose/dist/webapi/lib/jwe_algorithms.js
600
+ var wrap = [
601
+ ["encrypt", "wrapKey"],
602
+ ["decrypt", "unwrapKey"]
603
+ ];
604
+ var derive = [[], ["deriveBits"]];
605
+ var none = [[], []];
606
+ function rsaes(bits) {
607
+ return {
608
+ kty: ["RSA"],
609
+ mode: "key-encryption",
610
+ subtle: { name: "RSA-OAEP", hash: `SHA-${bits}` },
611
+ usages: wrap,
612
+ ops: ["wrapKey", "unwrapKey"]
613
+ };
614
+ }
615
+ function ecdh(mode) {
616
+ return {
617
+ kty: ["EC", "OKP"],
618
+ mode,
619
+ subtle: { name: "ECDH" },
620
+ resolve: ({ kty, crv, asymmetricKeyType }) => {
621
+ if (crv === "X25519" || asymmetricKeyType === "x25519")
622
+ return { name: "X25519" };
623
+ if (kty === "OKP")
624
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
625
+ return { name: "ECDH", namedCurve: crv };
626
+ },
627
+ usages: derive,
628
+ ops: [void 0, "deriveBits"]
629
+ };
630
+ }
631
+ function aeskw(bits, gcm = false) {
632
+ return {
633
+ kty: ["oct"],
634
+ mode: "key-wrapping",
635
+ secret: true,
636
+ subtle: { name: gcm ? "AES-GCM" : "AES-KW", length: bits },
637
+ usages: none,
638
+ ops: gcm ? ["encrypt", "decrypt"] : ["wrapKey", "unwrapKey"]
639
+ };
640
+ }
641
+ function pbes2() {
642
+ return {
643
+ kty: ["oct"],
644
+ mode: "key-wrapping",
645
+ secret: true,
646
+ subtle: { name: "PBKDF2" },
647
+ usages: none,
648
+ ops: ["deriveBits", "deriveBits"]
649
+ };
650
+ }
651
+ var JWE = table({
652
+ dir: {
653
+ kty: ["oct"],
654
+ mode: "direct-encryption",
655
+ secret: true,
656
+ subtle: { name: "AES-GCM" },
657
+ usages: none,
658
+ ops: ["encrypt", "decrypt"]
659
+ },
660
+ "RSA-OAEP": rsaes(1),
661
+ "RSA-OAEP-256": rsaes(256),
662
+ "RSA-OAEP-384": rsaes(384),
663
+ "RSA-OAEP-512": rsaes(512),
664
+ "ECDH-ES": ecdh("direct-key-agreement"),
665
+ "ECDH-ES+A128KW": ecdh("key-agreement-with-key-wrapping"),
666
+ "ECDH-ES+A192KW": ecdh("key-agreement-with-key-wrapping"),
667
+ "ECDH-ES+A256KW": ecdh("key-agreement-with-key-wrapping"),
668
+ A128KW: aeskw(128),
669
+ A192KW: aeskw(192),
670
+ A256KW: aeskw(256),
671
+ A128GCMKW: aeskw(128, true),
672
+ A192GCMKW: aeskw(192, true),
673
+ A256GCMKW: aeskw(256, true),
674
+ "PBES2-HS256+A128KW": pbes2(),
675
+ "PBES2-HS384+A192KW": pbes2(),
676
+ "PBES2-HS512+A256KW": pbes2()
677
+ });
678
+ var contentOps = ["encrypt", "decrypt"];
679
+ function contentEncryption(bits, cbc = false) {
680
+ return {
681
+ kty: ["oct"],
682
+ secret: true,
683
+ subtle: { name: cbc ? "AES-CBC" : "AES-GCM", length: bits },
684
+ usages: none,
685
+ ops: contentOps,
686
+ cekBits: bits,
687
+ ivBits: cbc ? 128 : 96,
688
+ cbc
689
+ };
690
+ }
691
+ var ENC = table({
692
+ A128GCM: contentEncryption(128),
693
+ A192GCM: contentEncryption(192),
694
+ A256GCM: contentEncryption(256),
695
+ "A128CBC-HS256": contentEncryption(256, true),
696
+ "A192CBC-HS384": contentEncryption(384, true),
697
+ "A256CBC-HS512": contentEncryption(512, true)
698
+ });
699
+
700
+ // node_modules/jose/dist/webapi/lib/jws_algorithms.js
701
+ var sig = [["verify"], ["sign"]];
702
+ function hmac(bits) {
703
+ const subtle = { name: "HMAC", hash: `SHA-${bits}` };
704
+ return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
705
+ }
706
+ function rsa(bits, saltLength) {
707
+ const subtle = { name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash: `SHA-${bits}` };
708
+ return {
709
+ kty: ["RSA"],
710
+ subtle,
711
+ signing: saltLength ? { ...subtle, saltLength } : subtle,
712
+ usages: sig,
713
+ minRsaBits: 2048
714
+ };
715
+ }
716
+ function ecdsa(crv, bits) {
717
+ return {
718
+ kty: ["EC"],
719
+ crv,
720
+ subtle: { name: "ECDSA", namedCurve: crv },
721
+ signing: { name: "ECDSA", hash: `SHA-${bits}` },
722
+ usages: sig
723
+ };
724
+ }
725
+ function eddsa() {
726
+ const subtle = { name: "Ed25519" };
727
+ return {
728
+ kty: ["OKP"],
729
+ crv: "Ed25519",
730
+ subtle,
731
+ signing: subtle,
732
+ usages: sig
733
+ };
734
+ }
735
+ function mldsa(parameterSet) {
736
+ const subtle = { name: `ML-DSA-${parameterSet}` };
737
+ return {
738
+ kty: ["AKP"],
739
+ subtle,
740
+ signing: subtle,
741
+ usages: sig
742
+ };
743
+ }
744
+ var JWS = table({
745
+ HS256: hmac(256),
746
+ HS384: hmac(384),
747
+ HS512: hmac(512),
748
+ RS256: rsa(256),
749
+ RS384: rsa(384),
750
+ RS512: rsa(512),
751
+ PS256: rsa(256, 32),
752
+ PS384: rsa(384, 48),
753
+ PS512: rsa(512, 64),
754
+ ES256: ecdsa("P-256", 256),
755
+ ES384: ecdsa("P-384", 384),
756
+ ES512: ecdsa("P-521", 512),
757
+ EdDSA: eddsa(),
758
+ Ed25519: eddsa(),
759
+ "ML-DSA-44": mldsa(44),
760
+ "ML-DSA-65": mldsa(65),
761
+ "ML-DSA-87": mldsa(87)
762
+ });
763
+ function jwsAlgorithm(alg) {
764
+ const entry = typeof alg == "string" ? JWS[alg] : void 0;
765
+ if (!entry)
766
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
767
+ return entry;
768
+ }
769
+
770
+ // node_modules/jose/dist/webapi/lib/jws_verify.js
771
+ function prepareVerify(options) {
772
+ return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
773
+ }
774
+ function parseProtectedHeader(encodedProtectedHeader) {
775
+ return encodedProtectedHeader === void 0 ? {} : parseJoseHeader(encodedProtectedHeader, JWSInvalid, "JWS Protected Header is invalid");
776
+ }
777
+ function encodeCompactUnencodedPayload(payload) {
778
+ try {
779
+ return encode(payload);
780
+ } catch (cause) {
781
+ throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters", {
782
+ cause
783
+ });
784
+ }
785
+ }
786
+ async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
787
+ const { protected: encodedProtectedHeader, header, payload: inputPayload } = jws, protectedHeader = parsedProtected ?? parseProtectedHeader(encodedProtectedHeader);
788
+ if (!isDisjoint(protectedHeader, header))
789
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
790
+ const joseHeader = { ...protectedHeader, ...header }, b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], protectedHeader, joseHeader)), { alg } = joseHeader;
791
+ if (typeof alg != "string" || !alg)
792
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
793
+ if (shared[0] && !shared[0].has(alg))
794
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
795
+ if (b64) {
796
+ if (typeof inputPayload != "string")
797
+ throw new JWSInvalid("JWS Payload must be a string");
798
+ } else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array))
799
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
800
+ const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
801
+ let resolvedKey = false;
802
+ typeof key == "function" && (key = await key(protectedHeader, jws), resolvedKey = true);
803
+ const entry = jwsAlgorithm(alg), signingInput = concat(encodedProtectedHeader !== void 0 ? encode(encodedProtectedHeader) : new Uint8Array(), encode("."), typeof signingPayload == "string" ? shared[2] ??= encodeAsciiMember(signingPayload, "payload", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, "signature", JWSInvalid), verificationKey = await prepareKey(entry, key, "verify"), cryptoKey = await rawKey(verificationKey, entry.subtle, "verify");
804
+ entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
805
+ let verified = false;
806
+ try {
807
+ verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, signingInput);
808
+ } catch (cause) {
809
+ throw new JWSSignatureVerificationFailed(void 0, { cause });
810
+ }
811
+ if (!verified)
812
+ throw new JWSSignatureVerificationFailed();
813
+ const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
814
+ return encodedProtectedHeader !== void 0 && (result.protectedHeader = protectedHeader), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: verificationKey }, b64] : [result, b64];
815
+ }
816
+ async function verifyCompact(jws, shared, key) {
817
+ if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string")
818
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
819
+ const { 0: protectedHeader, 1: payload, 2: signature, length: length2 } = jws.split(".");
820
+ if (length2 !== 3)
821
+ throw new JWSInvalid("Invalid Compact JWS");
822
+ return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload);
823
+ }
824
+
825
+ // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
826
+ var epoch = (date) => Math.floor(date.getTime() / 1e3);
827
+ var multipliers = {
828
+ s: 1,
829
+ m: 60,
830
+ h: 3600,
831
+ d: 86400,
832
+ w: 604800,
833
+ y: 31557600
834
+ };
835
+ 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;
836
+ var checkFailed = "check_failed";
837
+ function invalidDuration() {
838
+ throw new TypeError("Invalid time period format");
839
+ }
840
+ function secs(str2) {
841
+ typeof str2 != "string" && invalidDuration();
842
+ const matched = REGEX.exec(str2);
843
+ (!matched || matched[4] && matched[1]) && invalidDuration();
844
+ const value = parseFloat(matched[2]), durationSeconds = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
845
+ return Number.isFinite(durationSeconds) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -durationSeconds : durationSeconds;
846
+ }
847
+ function validateInput(label, input) {
848
+ if (!Number.isFinite(input))
849
+ throw new TypeError(`Invalid ${label} input`);
850
+ return input;
851
+ }
852
+ function validateStringClaim(claim, value) {
853
+ if (typeof value != "string")
854
+ throw new TypeError(`"${claim}" claim must be a string`);
855
+ }
856
+ function validateAudienceClaim(value) {
857
+ if (typeof value != "string" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != "string")))
858
+ throw new TypeError('"aud" claim must be a string or an array of strings');
859
+ }
860
+ function numericDate(value, label) {
861
+ return typeof value == "number" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);
862
+ }
863
+ var normalizeTyp = (value) => {
864
+ const normalized = value.toLowerCase();
865
+ return value.includes("/") ? normalized : `application/${normalized}`;
866
+ };
867
+ var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false;
868
+ function validateNumericDate(claimsSet, claim, required = false) {
869
+ const value = claimsSet[claim];
870
+ if (!(value === void 0 && !required)) {
871
+ if (typeof value != "number")
872
+ throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, claimsSet, claim, "invalid");
873
+ return value;
874
+ }
875
+ }
876
+ function unexpectedClaim(claimsSet, claim) {
877
+ throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, claimsSet, claim, checkFailed);
878
+ }
879
+ function validateClaimsSet(protectedHeader, claimsSetBytes, options = {}) {
880
+ let claimsSet;
881
+ try {
882
+ claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));
883
+ } catch (cause) {
884
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object", { cause });
885
+ }
886
+ if (!isObject(claimsSet))
887
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
888
+ const { typ } = options;
889
+ if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))
890
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', claimsSet, "typ", checkFailed);
891
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
892
+ maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
893
+ for (const claim of new Set(presenceCheck.reverse()))
894
+ if (!Object.hasOwn(claimsSet, claim))
895
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claimsSet, claim, "missing");
896
+ issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(claimsSet.iss) && unexpectedClaim(claimsSet, "iss"), subject !== void 0 && claimsSet.sub !== subject && unexpectedClaim(claimsSet, "sub"), audience !== void 0 && !checkAudiencePresence(claimsSet.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(claimsSet, "aud");
897
+ const { clockTolerance } = options;
898
+ let tolerance = 0;
899
+ if (typeof clockTolerance == "string")
900
+ tolerance = secs(clockTolerance);
901
+ else if (clockTolerance !== void 0) {
902
+ if (typeof clockTolerance != "number")
903
+ throw new TypeError("Invalid clockTolerance option type");
904
+ tolerance = clockTolerance;
905
+ }
906
+ if (validateInput("clockTolerance option", tolerance), tolerance < 0)
907
+ throw new TypeError("Invalid clockTolerance option input");
908
+ const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(claimsSet, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(claimsSet, "nbf");
909
+ if (nbf !== void 0 && nbf > now + tolerance)
910
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', claimsSet, "nbf", checkFailed);
911
+ const exp = validateNumericDate(claimsSet, "exp");
912
+ if (exp !== void 0 && exp <= now - tolerance)
913
+ throw new JWTExpired('"exp" claim timestamp check failed', claimsSet, "exp", checkFailed);
914
+ if (maxTokenAge !== void 0) {
915
+ const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
916
+ if (max < 0)
917
+ throw new TypeError("Invalid maxTokenAge option input");
918
+ if (age - tolerance > max)
919
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', claimsSet, "iat", checkFailed);
920
+ if (age < -tolerance)
921
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', claimsSet, "iat", checkFailed);
922
+ }
923
+ return claimsSet;
924
+ }
925
+ var producerClaimsSets;
926
+ function producerClaimsSet(producer) {
927
+ return producerClaimsSets.get(producer);
928
+ }
929
+ function jwtClaimsSetBytes(producer) {
930
+ const claimsSet = producerClaimsSet(producer);
931
+ for (const claim of ["iat", "nbf", "exp"]) {
932
+ const value = claimsSet[claim];
933
+ if (typeof value == "number" && !Number.isFinite(value))
934
+ throw new TypeError(`"${claim}" claim must be a finite number`);
935
+ }
936
+ return encoder.encode(JSON.stringify(claimsSet));
937
+ }
938
+ var JWTClaimsBuilder = class {
939
+ constructor(claimsSet = {}) {
940
+ if (!isObject(claimsSet))
941
+ throw new TypeError("JWT Claims Set MUST be an object");
942
+ (producerClaimsSets ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(claimsSet));
943
+ }
944
+ setIssuer(value) {
945
+ return validateStringClaim("iss", value), producerClaimsSet(this).iss = value, this;
946
+ }
947
+ setSubject(value) {
948
+ return validateStringClaim("sub", value), producerClaimsSet(this).sub = value, this;
949
+ }
950
+ setAudience(value) {
951
+ return validateAudienceClaim(value), producerClaimsSet(this).aud = value, this;
952
+ }
953
+ setJti(value) {
954
+ return validateStringClaim("jti", value), producerClaimsSet(this).jti = value, this;
955
+ }
956
+ setNotBefore(value) {
957
+ return producerClaimsSet(this).nbf = numericDate(value, "setNotBefore"), this;
958
+ }
959
+ setExpirationTime(value) {
960
+ return producerClaimsSet(this).exp = numericDate(value, "setExpirationTime"), this;
961
+ }
962
+ setIssuedAt(value) {
963
+ const claimsSet = producerClaimsSet(this);
964
+ return value === void 0 ? claimsSet.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == "string" ? claimsSet.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)) : claimsSet.iat = numericDate(value, "setIssuedAt"), this;
965
+ }
966
+ };
967
+
968
+ // node_modules/jose/dist/webapi/jwt/verify.js
969
+ async function jwtVerify(jwt, key, options) {
970
+ const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
971
+ if (!b64)
972
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
973
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
974
+ return { ...verified, payload };
975
+ }
976
+
977
+ // node_modules/jose/dist/webapi/lib/jws_sign.js
978
+ async function createSignature(input, key, rejectUnencoded) {
979
+ let [payload, protectedHeader, unprotectedHeader, crit] = input, encodedProtectedHeader = "";
980
+ if (protectedHeader !== void 0) {
981
+ const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);
982
+ protectedHeader = normalized[0], encodedProtectedHeader = encode2(normalized[1]);
983
+ }
984
+ if (unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWSInvalid, unprotectedHeader)[0]), !protectedHeader && !unprotectedHeader)
985
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
986
+ if (!isDisjoint(protectedHeader, unprotectedHeader))
987
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
988
+ const joseHeader = { ...protectedHeader, ...unprotectedHeader };
989
+ validateCritDuplicates(JWSInvalid, protectedHeader);
990
+ const b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));
991
+ b64 || rejectUnencoded?.();
992
+ const { alg } = joseHeader;
993
+ if (typeof alg != "string" || !alg)
994
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
995
+ const entry = jwsAlgorithm(alg);
996
+ let encodedPayload = "", signingPayload = payload, signingInput;
997
+ if (b64) {
998
+ const encodedPayloadCache = input[4];
999
+ encodedPayloadCache ? (encodedPayload = encodedPayloadCache[0] ??= encode2(payload), signingPayload = encodedPayloadCache[1] ??= encode(encodedPayload)) : (encodedPayload = encode2(payload), signingInput = encoder.encode(`${encodedProtectedHeader}.${encodedPayload}`));
1000
+ }
1001
+ signingInput ??= concat(encode(encodedProtectedHeader), encode("."), signingPayload);
1002
+ const signingKey = await rawKey(await prepareKey(entry, key, "sign"), entry.subtle, "sign");
1003
+ entry.minRsaBits && checkModulusLength(entry.alg, signingKey);
1004
+ const jws = {
1005
+ signature: encode2(new Uint8Array(await crypto.subtle.sign(entry.signing, signingKey, signingInput))),
1006
+ payload: encodedPayload
1007
+ };
1008
+ return protectedHeader && (jws.protected = encodedProtectedHeader), unprotectedHeader && (jws.header = unprotectedHeader), [jws, b64];
1009
+ }
1010
+ async function createCompactSignature(payload, protectedHeader, crit, key, rejectUnencoded) {
1011
+ const [jws] = await createSignature([payload, protectedHeader, void 0, crit], key, rejectUnencoded);
1012
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
1013
+ }
1014
+
1015
+ // node_modules/jose/dist/webapi/jwt/sign.js
1016
+ var SignJWT_base = JWTClaimsBuilder;
1017
+ var SignJWT = class extends SignJWT_base {
1018
+ #protectedHeader;
1019
+ setProtectedHeader(protectedHeader) {
1020
+ return assertNotSet(this.#protectedHeader, "setProtectedHeader"), this.#protectedHeader = protectedHeader, this;
1021
+ }
1022
+ async sign(key, options) {
1023
+ return createCompactSignature(jwtClaimsSetBytes(this), this.#protectedHeader, options?.crit, key, () => {
1024
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1025
+ });
1026
+ }
1027
+ };
1028
+
1029
+ // node_modules/jose/dist/webapi/lib/key_algorithm.js
1030
+ var algArgument = '"alg" (Algorithm)';
1031
+ function unsupportedAlg(source = 'JWK "alg" (Algorithm) Parameter') {
1032
+ throw new JOSENotSupported(`Invalid or unsupported ${source} value`);
1033
+ }
1034
+ function keyAlgorithm(alg, source) {
1035
+ return (typeof alg == "string" ? JWS[alg] ?? JWE[alg] : void 0) ?? unsupportedAlg(source);
1036
+ }
1037
+
1038
+ // node_modules/jose/dist/webapi/key/export.js
1039
+ async function exportJWK(key) {
1040
+ if (isKeyObject(key))
1041
+ if (key.type === "secret")
1042
+ key = key.export();
1043
+ else
1044
+ return key.export({ format: "jwk" });
1045
+ if (key instanceof Uint8Array)
1046
+ return {
1047
+ kty: "oct",
1048
+ k: encode2(key)
1049
+ };
1050
+ if (!isCryptoKey(key))
1051
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
1052
+ if (!key.extractable)
1053
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
1054
+ const jwk = await crypto.subtle.exportKey("jwk", key);
1055
+ delete jwk.ext, delete jwk.key_ops, delete jwk.use, jwk.kty !== "AKP" && delete jwk.alg;
1056
+ for (const parameter of Object.keys(jwk))
1057
+ jwk[parameter] === void 0 && delete jwk[parameter];
1058
+ return jwk;
1059
+ }
1060
+
1061
+ // node_modules/jose/dist/webapi/jwk/thumbprint.js
1062
+ var check = (value, description) => {
1063
+ if (typeof value != "string" || !value)
1064
+ throw new JWKInvalid(`${description} missing or invalid`);
1065
+ };
1066
+ async function calculateJwkThumbprint(key, digestAlgorithm) {
1067
+ let jwk;
1068
+ if (isObject(key)) {
1069
+ if (jwk = snapshotJwk(key), typeof jwk.kty != "string")
1070
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
1071
+ } else if (isKeyLike(key))
1072
+ jwk = snapshotJwk(await exportJWK(key));
1073
+ else
1074
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
1075
+ if (digestAlgorithm ??= "sha256", digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512")
1076
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
1077
+ let requiredMembers;
1078
+ switch (jwk.kty) {
1079
+ case "AKP":
1080
+ check(jwk.alg, '"alg" (Algorithm) Parameter'), check(jwk.pub, '"pub" (Public key) Parameter'), requiredMembers = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
1081
+ break;
1082
+ case "EC":
1083
+ check(jwk.crv, '"crv" (Curve) Parameter'), check(jwk.x, '"x" (X Coordinate) Parameter'), check(jwk.y, '"y" (Y Coordinate) Parameter'), requiredMembers = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
1084
+ break;
1085
+ case "OKP":
1086
+ check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'), check(jwk.x, '"x" (Public Key) Parameter'), requiredMembers = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
1087
+ break;
1088
+ case "RSA":
1089
+ check(jwk.e, '"e" (Exponent) Parameter'), check(jwk.n, '"n" (Modulus) Parameter'), requiredMembers = { e: jwk.e, kty: jwk.kty, n: jwk.n };
1090
+ break;
1091
+ case "oct":
1092
+ if (typeof jwk.k != "string")
1093
+ throw new JWKInvalid('"k" (Key Value) Parameter missing or invalid');
1094
+ requiredMembers = { k: jwk.k, kty: jwk.kty };
1095
+ break;
1096
+ default:
1097
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
1098
+ }
1099
+ const thumbprintInput = encode(JSON.stringify(requiredMembers));
1100
+ return encode2(await digest(digestAlgorithm, thumbprintInput));
1101
+ }
1102
+
1103
+ // node_modules/jose/dist/webapi/jwks/local.js
1104
+ function isUsableJWK(jwk, entry, alg, kid) {
1105
+ const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;
1106
+ return (ext === void 0 || typeof ext == "boolean") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation == "string" && keyOps.indexOf(operation) === index) && keyOps.includes("verify")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == "string" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== "AKP" : alg === jwkAlg) && (use === void 0 || use === "sig") && (!entry.crv || crv === entry.crv);
1107
+ }
1108
+ async function importWithAlgCache(cache2, jwk, entry) {
1109
+ const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk), { alg } = entry;
1110
+ if (cached[alg] === void 0) {
1111
+ const pending = jwkToKey(entry, jwk, true).then((key) => {
1112
+ if (key.type !== "public")
1113
+ throw new JWKSInvalid("JSON Web Key Set members must be public keys");
1114
+ return cached[alg] = key, key;
1115
+ }).catch((error) => {
1116
+ throw cached[alg] === pending && delete cached[alg], error;
1117
+ });
1118
+ cached[alg] = pending;
1119
+ }
1120
+ return cached[alg];
1121
+ }
1122
+ function createLocalJWKSet(jwks) {
1123
+ let snapshot;
1124
+ try {
1125
+ snapshot = structuredClone(jwks);
1126
+ } catch (cause) {
1127
+ throw new JWKSInvalid("JSON Web Key Set malformed", { cause });
1128
+ }
1129
+ if (!isJwkSet(snapshot))
1130
+ throw new JWKSInvalid("JSON Web Key Set malformed");
1131
+ const metadata = snapshot.keys.map((jwk) => {
1132
+ const normalized = snapshotJwk(jwk);
1133
+ return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;
1134
+ }), cached = /* @__PURE__ */ new WeakMap();
1135
+ return Object.defineProperty(async (protectedHeader, token) => {
1136
+ const { alg, kid } = { ...protectedHeader, ...token?.header }, entry = typeof alg == "string" ? JWS[alg] : void 0;
1137
+ if (!entry || entry.secret)
1138
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
1139
+ const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length: length2 } = candidates;
1140
+ if (!length2)
1141
+ throw new JWKSNoMatchingKey();
1142
+ if (length2 !== 1) {
1143
+ const error = new JWKSMultipleMatchingKeys();
1144
+ throw error[Symbol.asyncIterator] = async function* () {
1145
+ for (const jwk2 of candidates)
1146
+ try {
1147
+ yield await importWithAlgCache(cached, jwk2, entry);
1148
+ } catch {
1149
+ }
1150
+ }, error;
1151
+ }
1152
+ return importWithAlgCache(cached, jwk, entry);
1153
+ }, "jwks", {
1154
+ value: () => structuredClone(snapshot)
1155
+ });
1156
+ }
1157
+
1158
+ // node_modules/jose/dist/webapi/jwks/remote.js
1159
+ function isCloudflareWorkers() {
1160
+ return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
1161
+ }
1162
+ var USER_AGENT;
1163
+ (typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (USER_AGENT = "jose/v6.2.17");
1164
+ var customFetch = /* @__PURE__ */ Symbol();
1165
+ async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
1166
+ const response = await fetchImpl(url, {
1167
+ method: "GET",
1168
+ signal,
1169
+ redirect: "manual",
1170
+ headers
1171
+ }).catch((err) => {
1172
+ throw err.name === "TimeoutError" ? new JWKSTimeout(void 0, { cause: err }) : err;
1173
+ });
1174
+ if (response.status !== 200)
1175
+ throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
1176
+ try {
1177
+ return await response.json();
1178
+ } catch (cause) {
1179
+ throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON", { cause });
1180
+ }
1181
+ }
1182
+ var jwksCache = /* @__PURE__ */ Symbol();
1183
+ function isFreshFor(timestamp, duration) {
1184
+ return Number.isFinite(timestamp) && Date.now() < timestamp + duration;
1185
+ }
1186
+ function validateDuration(value, fallback, option) {
1187
+ if (Number.isNaN(value))
1188
+ throw new TypeError(`"${option}" option must not be NaN`);
1189
+ if (typeof value == "number" && value < 0)
1190
+ throw new TypeError(`"${option}" option must not be negative`);
1191
+ return typeof value == "number" ? value : fallback;
1192
+ }
1193
+ function createRemoteJWKSet(url, options) {
1194
+ if (!(url instanceof URL))
1195
+ throw new TypeError("url must be an instance of URL");
1196
+ const href = new URL(url.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;
1197
+ if (typeof timeoutOption == "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0))
1198
+ throw new TypeError('"timeoutDuration" option must be a non-negative integer');
1199
+ const timeoutDuration = typeof timeoutOption == "number" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge"), headers = new Headers(opts.headers);
1200
+ USER_AGENT && !headers.has("User-Agent") && headers.set("User-Agent", USER_AGENT), headers.has("accept") || headers.set("accept", "application/json, application/jwk-set+json");
1201
+ const fetchImpl = opts[customFetch], cache2 = opts[jwksCache];
1202
+ let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;
1203
+ if (cache2 && typeof cache2 == "object") {
1204
+ const { uat, jwks } = cache2;
1205
+ isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));
1206
+ }
1207
+ const reload = async () => {
1208
+ if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {
1209
+ const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {
1210
+ const next = createLocalJWKSet(json);
1211
+ if (sequence <= appliedSequence)
1212
+ return;
1213
+ local = next;
1214
+ const updatedAt = Date.now();
1215
+ cache2 && (cache2.uat = updatedAt, cache2.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;
1216
+ }).finally(() => {
1217
+ pendingFetch === current && (pendingFetch = void 0);
1218
+ });
1219
+ }
1220
+ await pendingFetch;
1221
+ };
1222
+ return Object.defineProperties(async (protectedHeader, token) => {
1223
+ (!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();
1224
+ try {
1225
+ return await local(protectedHeader, token);
1226
+ } catch (err) {
1227
+ if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration))
1228
+ return await reload(), local(protectedHeader, token);
1229
+ throw err;
1230
+ }
1231
+ }, {
1232
+ coolingDown: {
1233
+ get: () => isFreshFor(jwksTimestamp, cooldownDuration),
1234
+ enumerable: true
1235
+ },
1236
+ fresh: {
1237
+ get: () => isFreshFor(jwksTimestamp, cacheMaxAge),
1238
+ enumerable: true
1239
+ },
1240
+ reload: {
1241
+ value: reload,
1242
+ enumerable: true
1243
+ },
1244
+ reloading: {
1245
+ get: () => !!pendingFetch,
1246
+ enumerable: true
1247
+ },
1248
+ jwks: {
1249
+ value: () => local?.jwks(),
1250
+ enumerable: true
1251
+ }
1252
+ });
1253
+ }
1254
+
1255
+ // node_modules/jose/dist/webapi/util/decode_protected_header.js
1256
+ function decodeProtectedHeader(token) {
1257
+ let encodedProtectedHeader;
1258
+ if (typeof token == "string") {
1259
+ const parts = token.split(".");
1260
+ (parts.length === 3 || parts.length === 5) && ([encodedProtectedHeader] = parts);
1261
+ } else if (typeof token == "object" && token)
1262
+ if ("protected" in token)
1263
+ encodedProtectedHeader = token.protected;
1264
+ else
1265
+ throw new TypeError("Token does not contain a Protected Header");
1266
+ const invalid3 = "Invalid Token or Protected Header formatting";
1267
+ if (typeof encodedProtectedHeader != "string" || !encodedProtectedHeader)
1268
+ throw new TypeError(invalid3);
1269
+ return parseJoseHeader(encodedProtectedHeader, TypeError, invalid3);
1270
+ }
1271
+
1272
+ // node_modules/jose/dist/webapi/util/decode_jwt.js
1273
+ function decodeJwt(jwt) {
1274
+ if (typeof jwt != "string")
1275
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
1276
+ const { 1: encodedPayload, length: length2 } = jwt.split(".");
1277
+ if (length2 === 5)
1278
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
1279
+ if (length2 !== 3)
1280
+ throw new JWTInvalid("Invalid JWT");
1281
+ if (!encodedPayload)
1282
+ throw new JWTInvalid("JWTs must contain a payload");
1283
+ let claimsSetBytes;
1284
+ try {
1285
+ claimsSetBytes = decode(encodedPayload);
1286
+ } catch (cause) {
1287
+ throw new JWTInvalid("Failed to base64url decode the payload", { cause });
1288
+ }
1289
+ let claimsSet;
1290
+ try {
1291
+ claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));
1292
+ } catch (cause) {
1293
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON", { cause });
1294
+ }
1295
+ if (!isObject(claimsSet))
1296
+ throw new JWTInvalid("Invalid JWT Claims Set");
1297
+ return claimsSet;
1298
+ }
1299
+
1300
+ // node_modules/jose/dist/webapi/key/generate_key_pair.js
1301
+ function getModulusLengthOption(options) {
1302
+ const modulusLength = options?.modulusLength ?? 2048;
1303
+ if (typeof modulusLength != "number" || !Number.isInteger(modulusLength) || modulusLength < 2048)
1304
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
1305
+ return modulusLength;
1306
+ }
1307
+ async function generateKeyPair(alg, options) {
1308
+ const extractable = validateExtractableOption(options?.extractable), entry = keyAlgorithm(alg, algArgument);
1309
+ entry.secret && unsupportedAlg(algArgument);
1310
+ let algorithm;
1311
+ if (entry.resolve) {
1312
+ const crv = options?.crv ?? "P-256";
1313
+ if (!["P-256", "P-384", "P-521", "X25519"].includes(crv))
1314
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
1315
+ algorithm = entry.resolve({ crv });
1316
+ } else {
1317
+ if (entry.crv !== void 0 && options?.crv !== void 0 && options.crv !== entry.crv)
1318
+ throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${alg} is ${entry.crv}`);
1319
+ algorithm = entry.kty[0] === "RSA" ? {
1320
+ ...entry.subtle,
1321
+ publicExponent: Uint8Array.of(1, 0, 1),
1322
+ modulusLength: getModulusLengthOption(options)
1323
+ } : entry.subtle;
1324
+ }
1325
+ return crypto.subtle.generateKey(algorithm, extractable ?? false, [
1326
+ ...entry.usages[1],
1327
+ ...entry.usages[0]
1328
+ ]);
1329
+ }
180
1330
 
181
1331
  // src/errors.ts
182
1332
  var TestkitError = class extends Error {
183
1333
  code;
184
1334
  details;
185
- constructor(code, message, details = []) {
186
- super(details.length > 0 ? `${message}
1335
+ constructor(code, message2, details = []) {
1336
+ super(details.length > 0 ? `${message2}
187
1337
 
188
- ${details.map((d) => ` - ${d}`).join("\n")}` : message);
1338
+ ${details.map((d) => ` - ${d}`).join("\n")}` : message2);
189
1339
  this.name = "TestkitError";
190
1340
  this.code = code;
191
1341
  this.details = details;
@@ -201,17 +1351,17 @@ ${this.message}`;
201
1351
  var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
202
1352
  function toSeconds(value) {
203
1353
  if (typeof value === "number") {
204
- if (!Number.isFinite(value) || value < 0) throw invalid(String(value));
1354
+ if (!Number.isFinite(value) || value < 0) throw invalid2(String(value));
205
1355
  return Math.floor(value);
206
1356
  }
207
1357
  const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
208
1358
  if (!match) {
209
1359
  if (/^\d+$/.test(value.trim())) return Number(value.trim());
210
- throw invalid(value);
1360
+ throw invalid2(value);
211
1361
  }
212
1362
  return Number(match[1]) * UNITS[match[2]];
213
1363
  }
214
- function invalid(value) {
1364
+ function invalid2(value) {
215
1365
  return new TestkitError(
216
1366
  "INVALID_DURATION",
217
1367
  `"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
@@ -239,6 +1389,20 @@ var INVALID_TOKEN_KINDS = [
239
1389
  var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
240
1390
  var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
241
1391
  var KindeTestkit = class _KindeTestkit {
1392
+ observers = [];
1393
+ /** Calls the observer for every token signed from now on. Returns a function that stops it. */
1394
+ observe(observer) {
1395
+ this.observers.push(observer);
1396
+ return () => {
1397
+ this.observers = this.observers.filter((o) => o !== observer);
1398
+ };
1399
+ }
1400
+ async signAccess(payload, invalid3, now) {
1401
+ const final = applyInvalidClaims(payload, invalid3, now);
1402
+ const token = await this.sign(final, invalid3);
1403
+ for (const observer of this.observers) observer.accessToken?.(final, invalid3, token);
1404
+ return token;
1405
+ }
242
1406
  issuer;
243
1407
  audience;
244
1408
  clientId;
@@ -270,7 +1434,7 @@ var KindeTestkit = class _KindeTestkit {
270
1434
  return toSeconds(this.accessTokenExpiresIn);
271
1435
  }
272
1436
  async verify(token) {
273
- const { payload } = await (0, import_jose.jwtVerify)(token, this.signingKey.publicKey, {
1437
+ const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
274
1438
  issuer: this.issuer,
275
1439
  algorithms: ["RS256"]
276
1440
  });
@@ -298,7 +1462,7 @@ var KindeTestkit = class _KindeTestkit {
298
1462
  if (options.organizationCode) payload.org_code = options.organizationCode;
299
1463
  if (options.featureFlags) payload.feature_flags = options.featureFlags;
300
1464
  Object.assign(payload, options.claims ?? {});
301
- return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
1465
+ return this.signAccess(payload, options.invalid, now);
302
1466
  }
303
1467
  async m2mToken(options = {}) {
304
1468
  const now = this.clock();
@@ -319,10 +1483,13 @@ var KindeTestkit = class _KindeTestkit {
319
1483
  if (options.organizationCode) payload.org_code = options.organizationCode;
320
1484
  if (options.permissions !== void 0) payload.permissions = [...options.permissions];
321
1485
  Object.assign(payload, options.claims ?? {});
322
- return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
1486
+ return this.signAccess(payload, options.invalid, now);
323
1487
  }
324
1488
  async tokenFor(scenario2, overrides = {}) {
325
- if (scenario2.kind === "unauthenticated") return null;
1489
+ if (scenario2.kind === "unauthenticated") {
1490
+ for (const observer of this.observers) observer.anonymous?.();
1491
+ return null;
1492
+ }
326
1493
  return this.token({
327
1494
  subject: scenario2.user.id,
328
1495
  organizationCode: scenario2.organization?.code ?? null,
@@ -364,7 +1531,9 @@ var KindeTestkit = class _KindeTestkit {
364
1531
  for (const key of Object.keys(payload)) {
365
1532
  if (payload[key] === null || payload[key] === void 0) delete payload[key];
366
1533
  }
367
- return this.sign(payload);
1534
+ const token = await this.sign(payload);
1535
+ for (const observer of this.observers) observer.idToken?.(payload, token);
1536
+ return token;
368
1537
  }
369
1538
  async headersFor(scenario2, overrides = {}) {
370
1539
  const token = await this.tokenFor(scenario2, overrides);
@@ -374,17 +1543,17 @@ var KindeTestkit = class _KindeTestkit {
374
1543
  if (scenario2.kind === "unauthenticated") return null;
375
1544
  return scenarioPrincipal(scenario2, this.issuer);
376
1545
  }
377
- async signPayload(payload, invalid2) {
378
- return this.sign(payload, invalid2);
1546
+ async signPayload(payload, invalid3) {
1547
+ return this.sign(payload, invalid3);
379
1548
  }
380
- async sign(payload, invalid2) {
381
- if (invalid2 === "unsigned") {
382
- const header = import_jose.base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
383
- return `${header}.${import_jose.base64url.encode(JSON.stringify(payload))}.`;
1549
+ async sign(payload, invalid3) {
1550
+ if (invalid3 === "unsigned") {
1551
+ const header = base64url_exports.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
1552
+ return `${header}.${base64url_exports.encode(JSON.stringify(payload))}.`;
384
1553
  }
385
- const key = invalid2 === "unknown-key" ? await this.stranger() : this.signingKey;
386
- const jwt = await new import_jose.SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
387
- return invalid2 === "bad-signature" ? tamperSignature(jwt) : jwt;
1554
+ const key = invalid3 === "unknown-key" ? await this.stranger() : this.signingKey;
1555
+ const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
1556
+ return invalid3 === "bad-signature" ? tamperSignature(jwt) : jwt;
388
1557
  }
389
1558
  stranger() {
390
1559
  this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
@@ -418,9 +1587,9 @@ function scenarioPrincipal(scenario2, issuer) {
418
1587
  claims: { ...scenario2.claims }
419
1588
  };
420
1589
  }
421
- function applyInvalidClaims(payload, invalid2, now) {
1590
+ function applyInvalidClaims(payload, invalid3, now) {
422
1591
  const next = { ...payload };
423
- switch (invalid2) {
1592
+ switch (invalid3) {
424
1593
  case "expired":
425
1594
  next.iat = now - 7200;
426
1595
  next.exp = now - 3600;
@@ -450,16 +1619,16 @@ function applyInvalidClaims(payload, invalid2, now) {
450
1619
  return next;
451
1620
  }
452
1621
  async function createSigningKey(prefix) {
453
- const { privateKey, publicKey } = await (0, import_jose.generateKeyPair)("RS256");
454
- const jwk = await (0, import_jose.exportJWK)(publicKey);
455
- const kid = `${prefix}-${(await (0, import_jose.calculateJwkThumbprint)(jwk)).slice(0, 16)}`;
1622
+ const { privateKey, publicKey } = await generateKeyPair("RS256");
1623
+ const jwk = await exportJWK(publicKey);
1624
+ const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
456
1625
  return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
457
1626
  }
458
1627
  function tamperSignature(jwt) {
459
1628
  const [header, payload, signature] = jwt.split(".");
460
- const bytes = import_jose.base64url.decode(signature);
1629
+ const bytes = base64url_exports.decode(signature);
461
1630
  bytes[0] = (bytes[0] ?? 0) ^ 255;
462
- return `${header}.${payload}.${import_jose.base64url.encode(bytes)}`;
1631
+ return `${header}.${payload}.${base64url_exports.encode(bytes)}`;
463
1632
  }
464
1633
  function toArray(value) {
465
1634
  if (value === void 0) return [];
@@ -578,8 +1747,8 @@ function readTlv(buf, offset) {
578
1747
  }
579
1748
  return { start: offset + header, end: offset + header + len };
580
1749
  }
581
- function tlv(tag, content) {
582
- return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
1750
+ function tlv(tag2, content) {
1751
+ return Buffer.concat([Buffer.from([tag2]), length(content.length), content]);
583
1752
  }
584
1753
  function length(n) {
585
1754
  if (n < 128) return Buffer.from([n]);
@@ -668,8 +1837,8 @@ function renderSignIn(options) {
668
1837
  const value = escapeHtml(user.email ?? user.id);
669
1838
  const hasName = Boolean(user.givenName || user.familyName);
670
1839
  const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
671
- const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
672
- return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag}</span></button>`;
1840
+ const tag2 = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
1841
+ return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag2}</span></button>`;
673
1842
  }).join("");
674
1843
  const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
675
1844
  return layout(
@@ -686,8 +1855,8 @@ function renderOrganizationPicker(options) {
686
1855
  `<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}"><div class="list" style="margin-top:20px">${choices}</div></form>`
687
1856
  );
688
1857
  }
689
- function renderMessage(title, message) {
690
- return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
1858
+ function renderMessage(title, message2) {
1859
+ return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message2)}</p>`);
691
1860
  }
692
1861
 
693
1862
  // src/seed.ts
@@ -1014,16 +2183,18 @@ var OAuthError = class extends Error {
1014
2183
  error;
1015
2184
  };
1016
2185
  var AuthorizationServer = class {
1017
- constructor(testkit, seed, emit = () => void 0, directory) {
2186
+ constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
1018
2187
  this.testkit = testkit;
1019
2188
  this.seed = seed;
1020
2189
  this.emit = emit;
1021
2190
  this.directory = directory;
2191
+ this.observe = observe;
1022
2192
  }
1023
2193
  testkit;
1024
2194
  seed;
1025
2195
  emit;
1026
2196
  directory;
2197
+ observe;
1027
2198
  codes = /* @__PURE__ */ new Map();
1028
2199
  refreshTokens = /* @__PURE__ */ new Map();
1029
2200
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -1060,6 +2231,7 @@ var AuthorizationServer = class {
1060
2231
  return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
1061
2232
  }
1062
2233
  if (params.get("prompt") === "none") {
2234
+ this.observe("session.silent");
1063
2235
  return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
1064
2236
  }
1065
2237
  sendHtml(
@@ -1073,15 +2245,15 @@ var AuthorizationServer = class {
1073
2245
  })
1074
2246
  );
1075
2247
  }
1076
- login(res, form) {
2248
+ login(res, form2) {
1077
2249
  let request;
1078
2250
  try {
1079
- request = decodeRequest(form.request ?? "");
2251
+ request = decodeRequest(form2.request ?? "");
1080
2252
  } catch {
1081
2253
  return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
1082
2254
  }
1083
2255
  const encoded = encodeRequest(request);
1084
- const ref = (form.user || form.email || "").trim();
2256
+ const ref = (form2.user || form2.email || "").trim();
1085
2257
  if (!ref) {
1086
2258
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
1087
2259
  }
@@ -1090,6 +2262,7 @@ var AuthorizationServer = class {
1090
2262
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
1091
2263
  }
1092
2264
  if (this.directory?.isSuspended(user.id)) {
2265
+ this.observe("identity.suspended");
1093
2266
  return sendHtml(
1094
2267
  res,
1095
2268
  403,
@@ -1102,10 +2275,11 @@ var AuthorizationServer = class {
1102
2275
  );
1103
2276
  }
1104
2277
  const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
1105
- const wanted = request.orgCode ?? form.org ?? null;
2278
+ const wanted = request.orgCode ?? form2.org ?? null;
1106
2279
  let organizationCode = null;
1107
2280
  if (wanted) {
1108
2281
  if (!memberships.some((m) => m.organizationCode === wanted)) {
2282
+ this.observe("organization.non-member");
1109
2283
  return sendHtml(
1110
2284
  res,
1111
2285
  403,
@@ -1160,18 +2334,20 @@ var AuthorizationServer = class {
1160
2334
  if (request.state !== null) target.searchParams.set("state", request.state);
1161
2335
  redirect(res, target.toString());
1162
2336
  }
1163
- async token(req, res, form) {
2337
+ async token(req, res, form2) {
1164
2338
  try {
1165
- const clientId = clientIdFrom(req, form);
1166
- const grantType = form.grant_type;
2339
+ const clientId = clientIdFrom(req, form2);
2340
+ const grantType = form2.grant_type;
1167
2341
  if (grantType === "client_credentials") {
1168
- return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
2342
+ return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
1169
2343
  }
1170
2344
  let grant;
1171
2345
  if (grantType === "authorization_code") {
1172
- grant = this.redeemCode(form, clientId);
2346
+ grant = this.redeemCode(form2, clientId);
2347
+ this.observe("session.sign-in");
1173
2348
  } else if (grantType === "refresh_token") {
1174
- grant = this.redeemRefreshToken(form, clientId);
2349
+ grant = this.redeemRefreshToken(form2, clientId);
2350
+ this.observe("session.refresh");
1175
2351
  } else {
1176
2352
  throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
1177
2353
  }
@@ -1183,14 +2359,14 @@ var AuthorizationServer = class {
1183
2359
  throw error;
1184
2360
  }
1185
2361
  }
1186
- async clientCredentials(clientId, clientSecret, form) {
2362
+ async clientCredentials(clientId, clientSecret, form2) {
1187
2363
  const app = this.seed.applications.find((a) => a.clientId === clientId);
1188
2364
  if (app?.clientSecret && app.clientSecret !== clientSecret) {
1189
2365
  throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
1190
2366
  }
1191
- const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
2367
+ const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
1192
2368
  const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
1193
- const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
2369
+ const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
1194
2370
  return {
1195
2371
  access_token: await this.testkit.m2mToken({
1196
2372
  clientId,
@@ -1210,8 +2386,8 @@ var AuthorizationServer = class {
1210
2386
  this.refreshTokens.clear();
1211
2387
  this.signedUpUsers.clear();
1212
2388
  }
1213
- redeemCode(form, clientId) {
1214
- const code = form.code ?? "";
2389
+ redeemCode(form2, clientId) {
2390
+ const code = form2.code ?? "";
1215
2391
  const pending = this.codes.get(code);
1216
2392
  this.codes.delete(code);
1217
2393
  if (!pending || pending.expiresAt < Date.now()) {
@@ -1220,11 +2396,11 @@ var AuthorizationServer = class {
1220
2396
  if (pending.clientId !== clientId) {
1221
2397
  throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
1222
2398
  }
1223
- if (form.redirect_uri !== pending.redirectUri) {
2399
+ if (form2.redirect_uri !== pending.redirectUri) {
1224
2400
  throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
1225
2401
  }
1226
2402
  if (pending.codeChallenge) {
1227
- const verifier = form.code_verifier ?? "";
2403
+ const verifier = form2.code_verifier ?? "";
1228
2404
  const expected = pending.codeChallengeMethod === "plain" ? verifier : (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
1229
2405
  if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
1230
2406
  throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
@@ -1232,8 +2408,8 @@ var AuthorizationServer = class {
1232
2408
  }
1233
2409
  return pending;
1234
2410
  }
1235
- redeemRefreshToken(form, clientId) {
1236
- const token = form.refresh_token ?? "";
2411
+ redeemRefreshToken(form2, clientId) {
2412
+ const token = form2.refresh_token ?? "";
1237
2413
  const grant = this.refreshTokens.get(token);
1238
2414
  this.refreshTokens.delete(token);
1239
2415
  if (!grant) {
@@ -1307,11 +2483,13 @@ var AuthorizationServer = class {
1307
2483
  phone: null
1308
2484
  });
1309
2485
  }
1310
- revoke(res, form) {
1311
- if (form.token) this.refreshTokens.delete(form.token);
2486
+ revoke(res, form2) {
2487
+ if (form2.token) this.refreshTokens.delete(form2.token);
2488
+ this.observe("session.revoke");
1312
2489
  sendJson(res, 200, {});
1313
2490
  }
1314
2491
  logout(res, params) {
2492
+ this.observe("session.sign-out");
1315
2493
  const target = params.get("redirect");
1316
2494
  if (target && isHttpUrl(target)) return redirect(res, target);
1317
2495
  sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
@@ -1323,6 +2501,7 @@ var AuthorizationServer = class {
1323
2501
  const user = createKindeUser({ email: ref.toLowerCase() });
1324
2502
  if (!this.signedUpUsers.has(user.id)) {
1325
2503
  this.signedUpUsers.set(user.id, user);
2504
+ this.observe("identity.unseeded");
1326
2505
  if (this.directory) this.seed.users.push(user);
1327
2506
  this.emit("user.created", user);
1328
2507
  }
@@ -1376,24 +2555,24 @@ function decodeRequest(value) {
1376
2555
  }
1377
2556
  return request;
1378
2557
  }
1379
- function clientIdFrom(req, form) {
2558
+ function clientIdFrom(req, form2) {
1380
2559
  const header = req.headers.authorization ?? "";
1381
2560
  if (header.startsWith("Basic ")) {
1382
2561
  const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
1383
2562
  const id = decodeURIComponent(decoded.split(":")[0] ?? "");
1384
2563
  if (id) return id;
1385
2564
  }
1386
- if (form.client_id) return form.client_id;
2565
+ if (form2.client_id) return form2.client_id;
1387
2566
  throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
1388
2567
  }
1389
- function clientSecretFrom(req, form) {
2568
+ function clientSecretFrom(req, form2) {
1390
2569
  const header = req.headers.authorization ?? "";
1391
2570
  if (header.startsWith("Basic ")) {
1392
2571
  const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
1393
2572
  const index = decoded.indexOf(":");
1394
2573
  if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
1395
2574
  }
1396
- return form.client_secret ?? null;
2575
+ return form2.client_secret ?? null;
1397
2576
  }
1398
2577
  function redirectWithError(res, request, error, description) {
1399
2578
  const target = new URL(request.redirectUri);
@@ -1553,8 +2732,8 @@ function sendPage(res, url, field, items, extra) {
1553
2732
  metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
1554
2733
  });
1555
2734
  }
1556
- function errors(code, message) {
1557
- return { errors: [{ code, message }] };
2735
+ function errors(code, message2) {
2736
+ return { errors: [{ code, message: message2 }] };
1558
2737
  }
1559
2738
  function sendJson2(res, status, body) {
1560
2739
  res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
@@ -1580,6 +2759,22 @@ var Directory = class {
1580
2759
  this.userMeta.clear();
1581
2760
  this.orgMeta.clear();
1582
2761
  }
2762
+ /** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
2763
+ load(next) {
2764
+ for (const key of Object.keys(next)) {
2765
+ const current = this.seed[key];
2766
+ if (Array.isArray(current)) {
2767
+ current.splice(0, current.length, ...next[key]);
2768
+ } else {
2769
+ const record = current;
2770
+ for (const name of Object.keys(record)) delete record[name];
2771
+ Object.assign(record, next[key]);
2772
+ }
2773
+ }
2774
+ this.snapshot = JSON.stringify(this.seed);
2775
+ this.userMeta.clear();
2776
+ this.orgMeta.clear();
2777
+ }
1583
2778
  user(id) {
1584
2779
  return this.seed.users.find((user) => user.id === id);
1585
2780
  }
@@ -2099,11 +3294,11 @@ function paginate(items, query) {
2099
3294
  const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
2100
3295
  return { items: page, nextToken: next };
2101
3296
  }
2102
- function errors2(code, message) {
2103
- return { errors: [{ code, message }] };
3297
+ function errors2(code, message2) {
3298
+ return { errors: [{ code, message: message2 }] };
2104
3299
  }
2105
- function notFound(code, message) {
2106
- return [404, errors2(code, message)];
3300
+ function notFound(code, message2) {
3301
+ return [404, errors2(code, message2)];
2107
3302
  }
2108
3303
  function str(value) {
2109
3304
  return typeof value === "string" ? value : null;
@@ -2246,6 +3441,8 @@ var WebhookDispatcher = class {
2246
3441
  nextEndpoint = 1;
2247
3442
  retryDelaysMs;
2248
3443
  timeoutMs;
3444
+ /** Set by the server to record coverage. */
3445
+ observe = () => void 0;
2249
3446
  addEndpoint(input) {
2250
3447
  if (!isHttpUrl2(input.url)) {
2251
3448
  throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
@@ -2257,6 +3454,14 @@ var WebhookDispatcher = class {
2257
3454
  this.endpoints.push(endpoint);
2258
3455
  return { ...endpoint };
2259
3456
  }
3457
+ /** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
3458
+ replaceSeededEndpoints(endpoints) {
3459
+ const seeded = new Set(this.seededEndpoints.map((e) => e.id));
3460
+ this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
3461
+ const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
3462
+ const ids = new Set(added.map((e) => e.id));
3463
+ this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
3464
+ }
2260
3465
  removeEndpoint(id) {
2261
3466
  const before = this.endpoints.length;
2262
3467
  this.endpoints = this.endpoints.filter((e) => e.id !== id);
@@ -2307,6 +3512,9 @@ var WebhookDispatcher = class {
2307
3512
  `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
2308
3513
  );
2309
3514
  }
3515
+ if (copies > 1) this.observe("webhook.duplicate");
3516
+ if (options.invalid === "stale") this.observe("webhook.stale");
3517
+ else if (options.invalid) this.observe("webhook.forged");
2310
3518
  if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
2311
3519
  const signed = await this.testkit.signPayload(
2312
3520
  event,
@@ -2316,7 +3524,11 @@ var WebhookDispatcher = class {
2316
3524
  const webhookId = `wh_${(0, import_node_crypto6.randomBytes)(12).toString("hex")}`;
2317
3525
  return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
2318
3526
  });
2319
- return Promise.all(jobs);
3527
+ const deliveries = await Promise.all(jobs);
3528
+ if (!options.invalid) {
3529
+ for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
3530
+ }
3531
+ return deliveries;
2320
3532
  }
2321
3533
  async deliver(url, webhookId, body, event, copy) {
2322
3534
  const delivery = {
@@ -2465,7 +3677,511 @@ function isHttpUrl2(value) {
2465
3677
  }
2466
3678
  }
2467
3679
  function sleep(ms) {
2468
- return new Promise((resolve2) => setTimeout(resolve2, ms));
3680
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
3681
+ }
3682
+
3683
+ // src/activity.ts
3684
+ var LIMIT = 200;
3685
+ var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
3686
+ var ActivityLog = class {
3687
+ requestLog = [];
3688
+ tokenLog = [];
3689
+ request(entry) {
3690
+ const query = new URLSearchParams(entry.query);
3691
+ for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
3692
+ const search = query.toString();
3693
+ push(this.requestLog, {
3694
+ at: (/* @__PURE__ */ new Date()).toISOString(),
3695
+ method: entry.method,
3696
+ path: search ? `${entry.path}?${search}` : entry.path,
3697
+ status: entry.status,
3698
+ durationMs: entry.durationMs,
3699
+ injected: entry.injected
3700
+ });
3701
+ }
3702
+ token(kind, claims, invalid3, token) {
3703
+ const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
3704
+ push(this.tokenLog, {
3705
+ at: (/* @__PURE__ */ new Date()).toISOString(),
3706
+ kind,
3707
+ subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
3708
+ organization: typeof claims.org_code === "string" ? claims.org_code : null,
3709
+ permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
3710
+ roles,
3711
+ invalid: invalid3 ?? null,
3712
+ expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
3713
+ claims,
3714
+ token
3715
+ });
3716
+ }
3717
+ requests() {
3718
+ return [...this.requestLog];
3719
+ }
3720
+ tokens() {
3721
+ return [...this.tokenLog];
3722
+ }
3723
+ reset() {
3724
+ this.requestLog = [];
3725
+ this.tokenLog = [];
3726
+ }
3727
+ };
3728
+ function push(list, entry) {
3729
+ list.push(entry);
3730
+ if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
3731
+ }
3732
+
3733
+ // src/coverage.ts
3734
+ var import_node_fs2 = require("fs");
3735
+ var import_node_path2 = require("path");
3736
+ var COVERAGE_GROUPS = [
3737
+ {
3738
+ name: "Identity",
3739
+ items: [
3740
+ { id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
3741
+ { id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
3742
+ { id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
3743
+ { id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
3744
+ { id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
3745
+ { id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
3746
+ ]
3747
+ },
3748
+ {
3749
+ name: "Organizations",
3750
+ items: [
3751
+ { id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
3752
+ { id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
3753
+ { id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
3754
+ { id: "organization.non-member", label: "Non-member refused", hint: "Ask for a token or sign-in for an organization the user does not belong to." },
3755
+ { id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
3756
+ ]
3757
+ },
3758
+ {
3759
+ name: "Permissions",
3760
+ items: [
3761
+ { id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
3762
+ { id: "permission.different-sets", label: "Different permissions in one organization", hint: "Mint tokens for two users in one organization with different permissions, such as an admin and a viewer." },
3763
+ { id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
3764
+ { id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
3765
+ { id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
3766
+ ]
3767
+ },
3768
+ {
3769
+ name: "Token validation",
3770
+ items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
3771
+ (kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
3772
+ )
3773
+ },
3774
+ {
3775
+ name: "Sessions",
3776
+ items: [
3777
+ { id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
3778
+ { id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
3779
+ { id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
3780
+ { id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
3781
+ { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
3782
+ ]
3783
+ },
3784
+ {
3785
+ name: "Machine-to-machine",
3786
+ items: [
3787
+ { id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
3788
+ { id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
3789
+ { id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
3790
+ { id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
3791
+ ]
3792
+ },
3793
+ {
3794
+ name: "Kinde APIs",
3795
+ items: [
3796
+ { id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
3797
+ { id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
3798
+ { id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
3799
+ { id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
3800
+ ]
3801
+ },
3802
+ {
3803
+ name: "Webhooks",
3804
+ items: [
3805
+ { id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
3806
+ { id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
3807
+ { id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
3808
+ { id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
3809
+ { id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
3810
+ ]
3811
+ },
3812
+ {
3813
+ name: "Outages",
3814
+ items: [
3815
+ { id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
3816
+ { id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
3817
+ { id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
3818
+ { id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
3819
+ ]
3820
+ }
3821
+ ];
3822
+ var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
3823
+ function tokenLabel(kind) {
3824
+ return {
3825
+ expired: "Expired token",
3826
+ "future-iat": "Token issued in the future",
3827
+ "wrong-issuer": "Wrong issuer",
3828
+ "wrong-audience": "Wrong audience",
3829
+ "bad-signature": "Tampered signature",
3830
+ "unknown-key": "Unknown signing key",
3831
+ unsigned: "Unsigned token",
3832
+ "missing-subject": "No subject"
3833
+ }[kind];
3834
+ }
3835
+ var CoverageRecorder = class {
3836
+ hits = /* @__PURE__ */ new Map();
3837
+ userOrganizations = /* @__PURE__ */ new Map();
3838
+ organizationUsers = /* @__PURE__ */ new Map();
3839
+ organizationPermissionSets = /* @__PURE__ */ new Map();
3840
+ hit(id) {
3841
+ if (!ALL_IDS.has(id)) return;
3842
+ this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
3843
+ }
3844
+ /** Called for every access token the testkit signs. */
3845
+ observeAccessToken(payload, invalid3) {
3846
+ if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
3847
+ this.hit("m2m.token");
3848
+ if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
3849
+ if (typeof payload.org_code === "string") this.hit("m2m.organization");
3850
+ if (invalid3) this.hit("m2m.invalid");
3851
+ return;
3852
+ }
3853
+ if (invalid3 === "missing-organization") return this.hit("organization.missing");
3854
+ if (invalid3 === "missing-permissions") return this.hit("permission.none");
3855
+ if (invalid3) return this.hit(`token.${invalid3}`);
3856
+ const subject = typeof payload.sub === "string" ? payload.sub : null;
3857
+ const organization = typeof payload.org_code === "string" ? payload.org_code : null;
3858
+ const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
3859
+ if (subject) this.hit("identity.user");
3860
+ if (!organization) this.hit("identity.no-organization");
3861
+ if (permissions.length > 0) this.hit("permission.granted");
3862
+ else this.hit("permission.none");
3863
+ if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
3864
+ if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
3865
+ if (!organization) return;
3866
+ this.hit("organization.token");
3867
+ if (subject) {
3868
+ const organizations = add(this.userOrganizations, subject, organization);
3869
+ if (organizations.size > 1) this.hit("organization.two-for-one-user");
3870
+ add(this.organizationUsers, organization, subject);
3871
+ const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
3872
+ const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
3873
+ if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
3874
+ }
3875
+ const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
3876
+ if (sets.size > 1) this.hit("permission.different-sets");
3877
+ }
3878
+ report() {
3879
+ return buildReport(Object.fromEntries(this.hits));
3880
+ }
3881
+ snapshot() {
3882
+ return { version: 1, hits: Object.fromEntries(this.hits) };
3883
+ }
3884
+ reset() {
3885
+ this.hits.clear();
3886
+ this.userOrganizations.clear();
3887
+ this.organizationUsers.clear();
3888
+ this.organizationPermissionSets.clear();
3889
+ }
3890
+ /** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
3891
+ write(directory = DEFAULT_COVERAGE_DIRECTORY) {
3892
+ const folder = (0, import_node_path2.resolve)(directory);
3893
+ (0, import_node_fs2.mkdirSync)(folder, { recursive: true });
3894
+ const file = (0, import_node_path2.join)(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
3895
+ (0, import_node_fs2.writeFileSync)(file, `${JSON.stringify(this.snapshot())}
3896
+ `);
3897
+ return file;
3898
+ }
3899
+ };
3900
+ var DEFAULT_COVERAGE_DIRECTORY = (0, import_node_path2.join)(".kinde-testkit", "coverage");
3901
+ function add(map, key, value) {
3902
+ let set2 = map.get(key);
3903
+ if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
3904
+ set2.add(value);
3905
+ return set2;
3906
+ }
3907
+ function buildReport(hits) {
3908
+ const groups = COVERAGE_GROUPS.map((group) => {
3909
+ const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
3910
+ return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
3911
+ });
3912
+ return {
3913
+ covered: groups.reduce((sum, g) => sum + g.covered, 0),
3914
+ total: groups.reduce((sum, g) => sum + g.total, 0),
3915
+ groups
3916
+ };
3917
+ }
3918
+ function mergeSnapshots(snapshots) {
3919
+ const hits = {};
3920
+ for (const snapshot of snapshots) {
3921
+ for (const [id, count] of Object.entries(snapshot.hits ?? {})) hits[id] = (hits[id] ?? 0) + count;
3922
+ }
3923
+ return hits;
3924
+ }
3925
+ function readCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
3926
+ const folder = (0, import_node_path2.resolve)(directory);
3927
+ let names = [];
3928
+ try {
3929
+ names = (0, import_node_fs2.readdirSync)(folder).filter((name) => name.endsWith(".json"));
3930
+ } catch {
3931
+ }
3932
+ const snapshots = names.map((name) => JSON.parse((0, import_node_fs2.readFileSync)((0, import_node_path2.join)(folder, name), "utf8")));
3933
+ return { files: names.length, report: buildReport(mergeSnapshots(snapshots)) };
3934
+ }
3935
+ function clearCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
3936
+ (0, import_node_fs2.rmSync)((0, import_node_path2.resolve)(directory), { recursive: true, force: true });
3937
+ }
3938
+ function formatCoverageReport(report, options = {}) {
3939
+ const width = Math.max(...report.groups.map((g) => g.name.length)) + 3;
3940
+ const lines = ["Kinde authentication coverage", ""];
3941
+ for (const group of report.groups) {
3942
+ lines.push(`${group.name.padEnd(width)}${String(group.covered).padStart(2)}/${group.total}`);
3943
+ }
3944
+ lines.push("", `Overall: ${report.covered}/${report.total}`);
3945
+ if (options.missing !== false) {
3946
+ const missing = report.groups.flatMap((g) => g.items.filter((i) => !i.covered).map((i) => ({ group: g.name, ...i })));
3947
+ if (missing.length > 0) {
3948
+ lines.push("", "Not covered:");
3949
+ for (const item of missing) lines.push(` ${item.group}: ${item.label}. ${item.hint}`);
3950
+ }
3951
+ }
3952
+ return lines.join("\n");
3953
+ }
3954
+
3955
+ // src/dashboard.ts
3956
+ var STYLE2 = `
3957
+ :root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--ok:#1d7a46;--bad:#b42318;--soft:#f0f0ec}
3958
+ @media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--ok:#5cc78a;--bad:#f0817a;--soft:#232327}}
3959
+ *{box-sizing:border-box}
3960
+ body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
3961
+ header{position:sticky;top:0;z-index:1;display:flex;flex-wrap:wrap;gap:16px;align-items:center;justify-content:space-between;padding:14px 28px;background:var(--card);border-bottom:1px solid var(--line)}
3962
+ header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
3963
+ header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
3964
+ nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
3965
+ nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
3966
+ main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
3967
+ section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
3968
+ h2{margin:0 0 4px;font-size:16px;font-weight:600}
3969
+ .sub{margin:0 0 14px;color:var(--muted);font-size:13px}
3970
+ table{width:100%;border-collapse:collapse;font-size:13px}
3971
+ th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
3972
+ td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
3973
+ tr:last-child td{border-bottom:0}
3974
+ code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
3975
+ .chips{display:flex;flex-wrap:wrap;gap:4px}
3976
+ .chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
3977
+ .ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
3978
+ .empty{color:var(--muted);font-size:13px;margin:0}
3979
+ .row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
3980
+ label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
3981
+ input,select{height:32px;padding:0 8px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:13px ui-sans-serif,system-ui,sans-serif}
3982
+ input[type=checkbox]{height:auto}
3983
+ button{height:32px;padding:0 12px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:500 13px ui-sans-serif,system-ui,sans-serif;cursor:pointer}
3984
+ button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
3985
+ button:hover{border-color:var(--muted)}
3986
+ details summary{cursor:pointer;color:var(--muted)}
3987
+ pre{margin:8px 0 0;padding:10px;background:var(--soft);border-radius:6px;overflow:auto;max-height:320px;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-all}
3988
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
3989
+ .group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
3990
+ .group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
3991
+ .notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
3992
+ .split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
3993
+ `;
3994
+ function renderDashboard(data) {
3995
+ const e = escapeHtml;
3996
+ const { seed } = data;
3997
+ const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
3998
+ const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
3999
+ const users = seed.users.length ? table2(
4000
+ ["User", "ID", "Organizations", "Sign-ins", "Status"],
4001
+ seed.users.map((user) => [
4002
+ e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
4003
+ `<code>${e(user.id)}</code>`,
4004
+ chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
4005
+ String(data.signIns(user.id)),
4006
+ data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
4007
+ ])
4008
+ ) : empty("No users yet. Seed some, or sign in with any email.");
4009
+ const organizations = seed.organizations.length ? table2(
4010
+ ["Organization", "Code", "Members"],
4011
+ seed.organizations.map((org) => [
4012
+ e(org.name),
4013
+ `<code>${e(org.code)}</code>`,
4014
+ String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
4015
+ ])
4016
+ ) : empty("No organizations.");
4017
+ const memberships = seed.memberships.length ? table2(
4018
+ ["User", "Organization", "Roles", "Permissions in the token"],
4019
+ seed.memberships.map((m) => [
4020
+ e(userLabel(m.userId)),
4021
+ e(orgName(m.organizationCode)),
4022
+ chips(m.roles),
4023
+ chips(effectivePermissions(seed, m))
4024
+ ])
4025
+ ) : empty("No memberships.");
4026
+ const applications = seed.applications.length ? table2(
4027
+ ["Client ID", "Organization", "Scopes"],
4028
+ seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
4029
+ ) : "";
4030
+ const tokens = data.tokens.length ? table2(
4031
+ ["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
4032
+ [...data.tokens].reverse().slice(0, 50).map((t) => [
4033
+ time(t.at),
4034
+ t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
4035
+ `<code>${e(t.subject ?? "none")}</code>`,
4036
+ e(t.organization ?? "none"),
4037
+ chips(t.permissions),
4038
+ `<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
4039
+ ])
4040
+ ) : empty("No tokens issued yet.");
4041
+ const requests = data.requests.length ? table2(
4042
+ ["Time", "Request", "Status", "Time taken"],
4043
+ [...data.requests].reverse().slice(0, 100).map((r) => [
4044
+ time(r.at),
4045
+ `<code>${e(r.method)} ${e(r.path)}</code>`,
4046
+ `<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
4047
+ `${r.durationMs} ms`
4048
+ ])
4049
+ ) : empty("No requests yet.");
4050
+ const deliveries = data.deliveries.length ? table2(
4051
+ ["Event", "Endpoint", "Copy", "Result"],
4052
+ [...data.deliveries].reverse().slice(0, 50).map((d) => [
4053
+ `<code>${e(d.type)}</code>`,
4054
+ `<code>${e(d.url)}</code>`,
4055
+ String(d.copy),
4056
+ d.delivered ? `<span class="ok">Delivered</span>` : `<span class="bad">${e(d.attempts.map((a) => a.status === null ? a.error ?? "error" : String(a.status)).join(", ") || "Not sent")}</span>`
4057
+ ])
4058
+ ) : empty("No webhooks sent yet.");
4059
+ const endpoints = data.endpoints.length ? `<p class="sub">Endpoints: ${data.endpoints.map((x) => `<code>${e(x.url)}</code>`).join(", ")}</p>` : `<p class="sub">No webhook endpoints. Add one in the seed, with <code>start --webhook</code> or <code>addEndpoint()</code>.</p>`;
4060
+ const webhookForm = data.endpoints.length ? form(
4061
+ "/dashboard/webhooks",
4062
+ `<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
4063
+ <label>User<select name="user"><option value="">First seeded user</option>${seed.users.map((u) => `<option value="${e(u.id)}">${e(u.email ?? u.id)}</option>`).join("")}</select></label>
4064
+ <label>Variant<select name="invalid"><option value="">Valid</option><option>bad-signature</option><option>unknown-key</option><option>unsigned</option><option>stale</option></select></label>
4065
+ <label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
4066
+ <button class="primary">Send</button>`
4067
+ ) : "";
4068
+ const failures = data.failures.length ? table2(
4069
+ ["Path", "Method", "Effect", "Remaining", "Hits", ""],
4070
+ data.failures.map((f) => [
4071
+ `<code>${e(f.path)}</code>`,
4072
+ e(f.method ?? "any"),
4073
+ e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
4074
+ f.remaining === null ? "Until removed" : String(f.remaining),
4075
+ String(f.hits),
4076
+ form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
4077
+ ])
4078
+ ) : empty("No failure rules.");
4079
+ const coverage = `<div class="grid">${data.coverage.groups.map(
4080
+ (g) => `<div><div class="group"><span>${e(g.name)}</span><span class="${g.covered === g.total ? "ok" : "muted"}">${g.covered}/${g.total}</span></div><ul>${g.items.map((i) => `<li title="${e(i.hint)}"><span class="${i.covered ? "ok" : "muted"}">${i.covered ? "\u2713" : "\u25CB"}</span> ${e(i.label)}</li>`).join("")}</ul></div>`
4081
+ ).join("")}</div>`;
4082
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4083
+ ${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
4084
+ <title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
4085
+ <header>
4086
+ <div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
4087
+ <nav><a href="#users">Users</a><a href="#tokens">Tokens</a><a href="#requests">Requests</a><a href="#webhooks">Webhooks</a><a href="#failures">Failures</a><a href="#coverage">Coverage</a></nav>
4088
+ <div class="row">
4089
+ <a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
4090
+ ${form("/dashboard/reset", `<button>Reset state</button>`)}
4091
+ </div>
4092
+ </header>
4093
+ <main>
4094
+ ${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
4095
+ <section id="users"><h2>Users</h2><p class="sub">Seeded users, users created through the Management API, and emails that signed in.</p>${users}</section>
4096
+ <div class="split">
4097
+ <section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
4098
+ <section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
4099
+ </div>
4100
+ ${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
4101
+ <section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
4102
+ <section id="requests"><h2>Requests</h2><p class="sub">The latest 100 requests your app and tests made. Codes, secrets and refresh tokens are hidden.</p>${requests}</section>
4103
+ <section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
4104
+ <section id="failures"><h2>Failures</h2><p class="sub">Make an endpoint fail, slow down or hang. Applies to Kinde endpoints, not <code>/testkit</code> or this page.</p>
4105
+ ${form(
4106
+ "/dashboard/failures",
4107
+ `<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
4108
+ <label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
4109
+ <label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
4110
+ <label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
4111
+ <label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
4112
+ <label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
4113
+ <button class="primary">Add rule</button>`
4114
+ )}
4115
+ <div style="margin-top:14px">${failures}</div>
4116
+ ${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
4117
+ </section>
4118
+ <section id="coverage"><h2>Coverage: ${data.coverage.covered}/${data.coverage.total}</h2><p class="sub">Authentication scenarios the testkit produced since it started or was reset. Hover an item to see how to cover it.</p>${coverage}
4119
+ <div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
4120
+ </main></body></html>`;
4121
+ }
4122
+ function table2(headers, rows) {
4123
+ return `<table><thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
4124
+ }
4125
+ function chips(values) {
4126
+ if (values.length === 0) return `<span class="muted">none</span>`;
4127
+ return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
4128
+ }
4129
+ function empty(text) {
4130
+ return `<p class="empty">${escapeHtml(text)}</p>`;
4131
+ }
4132
+ function time(iso) {
4133
+ return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
4134
+ }
4135
+ function form(action, body) {
4136
+ return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
4137
+ }
4138
+
4139
+ // src/seed-file.ts
4140
+ var import_node_fs3 = require("fs");
4141
+ var import_node_path3 = require("path");
4142
+ var import_node_url = require("url");
4143
+ var import_yaml = require("yaml");
4144
+ var DEFAULT_SEED_FILES = [
4145
+ "kinde-testkit.json",
4146
+ "kinde-testkit.yaml",
4147
+ "kinde-testkit.yml",
4148
+ "kinde-testkit.ts",
4149
+ "kinde-testkit.mts",
4150
+ "kinde-testkit.js",
4151
+ "kinde-testkit.mjs"
4152
+ ];
4153
+ function findSeedFile(directory = ".") {
4154
+ return DEFAULT_SEED_FILES.map((name) => (0, import_node_path3.resolve)(directory, name)).find((path) => (0, import_node_fs3.existsSync)(path));
4155
+ }
4156
+ async function loadSeedFile(path) {
4157
+ const file = (0, import_node_path3.resolve)(path);
4158
+ const extension = (0, import_node_path3.extname)(file).toLowerCase();
4159
+ let value;
4160
+ try {
4161
+ if (extension === ".yaml" || extension === ".yml") {
4162
+ value = (0, import_yaml.parse)((0, import_node_fs3.readFileSync)(file, "utf8"));
4163
+ } else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
4164
+ const module2 = await import((0, import_node_url.pathToFileURL)(file).href);
4165
+ value = module2.seed ?? module2.default;
4166
+ if (value && typeof value === "object" && "default" in value && !("users" in value)) {
4167
+ value = value.default;
4168
+ }
4169
+ } else {
4170
+ value = JSON.parse((0, import_node_fs3.readFileSync)(file, "utf8"));
4171
+ }
4172
+ } catch (error) {
4173
+ const message2 = error instanceof Error ? error.message : String(error);
4174
+ const details = [message2];
4175
+ if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message2)) {
4176
+ details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
4177
+ }
4178
+ throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
4179
+ }
4180
+ if (value === null || value === void 0) value = {};
4181
+ if (typeof value !== "object" || Array.isArray(value)) {
4182
+ throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
4183
+ }
4184
+ return value;
2469
4185
  }
2470
4186
 
2471
4187
  // src/server.ts
@@ -2480,30 +4196,49 @@ async function startKindeTestkit(options = {}) {
2480
4196
  `kinde-testkit will not listen on ${host}. It signs tokens for any identity, so it stays on localhost unless you pass --allow-public (allowPublic: true in code).`
2481
4197
  );
2482
4198
  }
2483
- const seed = resolveSeed(options.seed ?? {});
4199
+ const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
4200
+ const seed = resolveSeed(seedInput);
2484
4201
  const failures = new FailureInjector();
2485
4202
  let ready;
2486
- const testkitReady = new Promise((resolve2) => ready = resolve2);
4203
+ const testkitReady = new Promise((resolve4) => ready = resolve4);
2487
4204
  const listener = (req, res) => {
2488
4205
  testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
2489
4206
  };
2490
4207
  const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
2491
4208
  const server = certificate ? (0, import_node_https.createServer)({ cert: certificate.cert, key: certificate.key }, listener) : (0, import_node_http.createServer)(listener);
2492
- await new Promise((resolve2, reject) => {
4209
+ await new Promise((resolve4, reject) => {
2493
4210
  server.once("error", reject);
2494
- server.listen(options.port ?? 4400, host, () => resolve2());
4211
+ server.listen(options.port ?? 4400, host, () => resolve4());
2495
4212
  });
2496
4213
  const { port } = server.address();
2497
- const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
4214
+ const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
2498
4215
  const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
2499
4216
  const testkit = await KindeTestkit.create({
2500
- issuer: options.issuer ?? options.seed?.issuer ?? url,
2501
- audience: options.audience ?? options.seed?.audience,
2502
- clientId: options.clientId ?? options.seed?.clientId
4217
+ issuer: options.issuer ?? seedInput.issuer ?? url,
4218
+ audience: options.audience ?? seedInput.audience,
4219
+ clientId: options.clientId ?? seedInput.clientId
2503
4220
  });
4221
+ const coverage = new CoverageRecorder();
4222
+ const activity = new ActivityLog();
4223
+ testkit.observe({
4224
+ accessToken(payload, invalid3, token) {
4225
+ coverage.observeAccessToken(payload, invalid3);
4226
+ const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
4227
+ activity.token(m2m ? "m2m" : "access", payload, invalid3, token);
4228
+ },
4229
+ idToken(payload, token) {
4230
+ coverage.hit("identity.id-token");
4231
+ activity.token("id", payload, void 0, token);
4232
+ },
4233
+ anonymous() {
4234
+ coverage.hit("identity.anonymous");
4235
+ }
4236
+ });
4237
+ const observe = (id) => coverage.hit(id);
2504
4238
  const directory = new Directory(seed);
2505
4239
  const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
2506
- const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
4240
+ webhooks.observe = observe;
4241
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
2507
4242
  const management = new ManagementApi(testkit, directory, webhooks);
2508
4243
  const account = new AccountApi(testkit, directory);
2509
4244
  const reset = () => {
@@ -2512,7 +4247,23 @@ async function startKindeTestkit(options = {}) {
2512
4247
  webhooks.reset();
2513
4248
  directory.restore();
2514
4249
  };
2515
- ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
4250
+ const loadSeed = (input) => {
4251
+ const next = resolveSeed(input);
4252
+ directory.load(next);
4253
+ webhooks.replaceSeededEndpoints(next.webhooks);
4254
+ reset();
4255
+ };
4256
+ let closed = false;
4257
+ const close = () => new Promise((resolve4, reject) => {
4258
+ if (closed) return resolve4();
4259
+ closed = true;
4260
+ if (options.coverage) {
4261
+ coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
4262
+ }
4263
+ server.closeAllConnections();
4264
+ server.close((error) => error ? reject(error) : resolve4());
4265
+ });
4266
+ ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
2516
4267
  return {
2517
4268
  url,
2518
4269
  issuer: testkit.issuer,
@@ -2524,23 +4275,37 @@ async function startKindeTestkit(options = {}) {
2524
4275
  webhooks,
2525
4276
  directory,
2526
4277
  certificatePath: certificate?.certPath ?? null,
4278
+ coverage,
4279
+ activity,
4280
+ loadSeed,
2527
4281
  reset,
2528
- close: () => new Promise((resolve2, reject) => {
2529
- server.closeAllConnections();
2530
- server.close((error) => error ? reject(error) : resolve2());
2531
- })
4282
+ close
2532
4283
  };
2533
4284
  }
2534
4285
  async function handle(req, res, context) {
2535
- const { testkit, auth, seed, failures, webhooks } = context;
4286
+ const { testkit, auth, seed, failures, webhooks, coverage } = context;
2536
4287
  const url = new URL(req.url ?? "/", "http://localhost");
2537
4288
  const { pathname } = url;
2538
4289
  const method = req.method ?? "GET";
2539
- if (!pathname.startsWith("/testkit/")) {
4290
+ const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
4291
+ let injected = false;
4292
+ if (!internal && pathname !== "/favicon.ico") {
4293
+ const started = Date.now();
4294
+ res.once("close", () => {
4295
+ context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
4296
+ });
4297
+ }
4298
+ if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
4299
+ if (!internal) {
2540
4300
  const failure = failures.take(method, pathname);
2541
4301
  if (failure) {
4302
+ injected = true;
4303
+ if (failure.hang) coverage.hit("outage.timeout");
4304
+ else if (failure.status === 429) coverage.hit("outage.rate-limit");
4305
+ else if (failure.status !== null) coverage.hit("outage.error");
4306
+ if (failure.delayMs > 0) coverage.hit("outage.slow");
2542
4307
  if (failure.hang) return;
2543
- if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
4308
+ if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
2544
4309
  if (failure.status !== null) {
2545
4310
  const headers = {};
2546
4311
  if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
@@ -2549,8 +4314,15 @@ async function handle(req, res, context) {
2549
4314
  }
2550
4315
  }
2551
4316
  if (await auth.handle(req, res, url, () => readForm(req))) return;
2552
- if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
2553
- if (await context.account.handle(req, res, url)) return;
4317
+ if (await context.management.handle(req, res, url, async () => await readJson(req))) {
4318
+ if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
4319
+ else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
4320
+ return;
4321
+ }
4322
+ if (await context.account.handle(req, res, url)) {
4323
+ if (res.statusCode < 400) coverage.hit("api.account");
4324
+ return;
4325
+ }
2554
4326
  if (method === "GET" && pathname === "/testkit/portal") {
2555
4327
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2556
4328
  res.end(
@@ -2607,11 +4379,119 @@ async function handle(req, res, context) {
2607
4379
  }
2608
4380
  if (method === "POST" && pathname === "/testkit/token") {
2609
4381
  const body = await readJson(req);
2610
- const accessToken = await issueToken(testkit, seed, body);
4382
+ let accessToken;
4383
+ try {
4384
+ accessToken = await issueToken(testkit, seed, body);
4385
+ } catch (error) {
4386
+ if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
4387
+ throw error;
4388
+ }
2611
4389
  return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
2612
4390
  }
4391
+ if (method === "GET" && pathname === "/testkit/coverage") {
4392
+ return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
4393
+ }
4394
+ if (method === "DELETE" && pathname === "/testkit/coverage") {
4395
+ coverage.reset();
4396
+ return sendJson4(res, 200, { ok: true });
4397
+ }
4398
+ if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
4399
+ if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
4400
+ if (method === "POST" && pathname === "/testkit/seed") {
4401
+ const body = await readJson(req);
4402
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
4403
+ throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
4404
+ }
4405
+ context.loadSeed(body);
4406
+ return sendJson4(res, 200, {
4407
+ ok: true,
4408
+ users: seed.users.length,
4409
+ organizations: seed.organizations.length,
4410
+ memberships: seed.memberships.length
4411
+ });
4412
+ }
4413
+ if (method === "POST" && pathname === "/testkit/stop") {
4414
+ sendJson4(res, 200, { ok: true });
4415
+ res.once("finish", () => void context.close().catch(() => void 0));
4416
+ return;
4417
+ }
2613
4418
  return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
2614
4419
  }
4420
+ async function dashboard(req, res, url, context) {
4421
+ const method = req.method ?? "GET";
4422
+ const { pathname } = url;
4423
+ if (method === "GET" && pathname === "/dashboard") {
4424
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
4425
+ res.end(
4426
+ renderDashboard({
4427
+ issuer: context.testkit.issuer,
4428
+ seed: context.seed,
4429
+ suspended: (id) => context.directory.isSuspended(id),
4430
+ signIns: (id) => {
4431
+ const user = context.directory.user(id);
4432
+ return user ? context.directory.meta(user).totalSignIns : 0;
4433
+ },
4434
+ tokens: context.activity.tokens(),
4435
+ requests: context.activity.requests(),
4436
+ deliveries: context.webhooks.deliveries(),
4437
+ endpoints: context.webhooks.listEndpoints(),
4438
+ failures: context.failures.list(),
4439
+ coverage: context.coverage.report(),
4440
+ webhookTypes: WEBHOOK_EVENT_TYPES,
4441
+ live: url.searchParams.has("live"),
4442
+ notice: url.searchParams.get("notice")
4443
+ })
4444
+ );
4445
+ return;
4446
+ }
4447
+ if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
4448
+ const origin = req.headers.origin;
4449
+ if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
4450
+ return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
4451
+ }
4452
+ const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
4453
+ let notice = "Done.";
4454
+ try {
4455
+ if (pathname === "/dashboard/reset") {
4456
+ context.reset();
4457
+ notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
4458
+ } else if (pathname === "/dashboard/coverage/reset") {
4459
+ context.coverage.reset();
4460
+ notice = "Cleared coverage.";
4461
+ } else if (pathname === "/dashboard/failures/clear") {
4462
+ context.failures.clear();
4463
+ notice = "Removed every failure rule.";
4464
+ } else if (pathname === "/dashboard/failures") {
4465
+ const rule = { path: form2.path ?? "" };
4466
+ if (form2.method) rule.method = form2.method;
4467
+ if (form2.status) rule.status = Number(form2.status);
4468
+ if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
4469
+ if (form2.times) rule.times = Number(form2.times);
4470
+ if (form2.hang) rule.hang = true;
4471
+ const added = context.failures.add(rule);
4472
+ notice = `Added ${added.id} for ${added.path}.`;
4473
+ } else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
4474
+ const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
4475
+ notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
4476
+ } else if (pathname === "/dashboard/webhooks") {
4477
+ const deliveries = await context.webhooks.send({
4478
+ type: form2.type ?? "",
4479
+ user: form2.user || void 0,
4480
+ invalid: form2.invalid || void 0,
4481
+ duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
4482
+ });
4483
+ const delivered = deliveries.filter((d) => d.delivered).length;
4484
+ notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
4485
+ } else {
4486
+ return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
4487
+ }
4488
+ } catch (error) {
4489
+ notice = error.message.replace(/\s+/g, " ").trim();
4490
+ }
4491
+ const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
4492
+ res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
4493
+ res.end();
4494
+ }
2615
4495
  function discovery(testkit) {
2616
4496
  const base = testkit.issuer;
2617
4497
  return {
@@ -2637,9 +4517,9 @@ async function issueToken(testkit, seed, body) {
2637
4517
  throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
2638
4518
  }
2639
4519
  const input = body;
2640
- const invalid2 = optionalString(input, "invalid");
2641
- if (invalid2 !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid2)) {
2642
- throw new TestkitError("INVALID_REQUEST", `"${invalid2}" is not a known invalid token kind.`, [
4520
+ const invalid3 = optionalString(input, "invalid");
4521
+ if (invalid3 !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid3)) {
4522
+ throw new TestkitError("INVALID_REQUEST", `"${invalid3}" is not a known invalid token kind.`, [
2643
4523
  `Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
2644
4524
  ]);
2645
4525
  }
@@ -2656,7 +4536,7 @@ async function issueToken(testkit, seed, body) {
2656
4536
  audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
2657
4537
  permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
2658
4538
  expiresIn,
2659
- invalid: invalid2
4539
+ invalid: invalid3
2660
4540
  });
2661
4541
  }
2662
4542
  const permissions = optionalStrings(input, "permissions");
@@ -2671,7 +4551,7 @@ async function issueToken(testkit, seed, body) {
2671
4551
  if (roles) scenario2.roles = roles;
2672
4552
  return await testkit.tokenFor(scenario2, {
2673
4553
  expiresIn,
2674
- invalid: invalid2,
4554
+ invalid: invalid3,
2675
4555
  featureFlags: featureFlagsFor(seed, scenario2.organization?.code ?? null)
2676
4556
  });
2677
4557
  }
@@ -2682,7 +4562,7 @@ async function issueToken(testkit, seed, body) {
2682
4562
  roles,
2683
4563
  scopes: optionalStrings(input, "scopes"),
2684
4564
  expiresIn,
2685
- invalid: invalid2
4565
+ invalid: invalid3
2686
4566
  };
2687
4567
  if (typeof input.claims === "object" && input.claims !== null) {
2688
4568
  options.claims = input.claims;
@@ -2762,7 +4642,6 @@ function sendError(res, error) {
2762
4642
  }
2763
4643
 
2764
4644
  // src/inspect.ts
2765
- var import_jose2 = require("jose");
2766
4645
  async function inspectToken(token, options = {}) {
2767
4646
  const checks = [];
2768
4647
  const trimmed = token.trim();
@@ -2773,8 +4652,8 @@ async function inspectToken(token, options = {}) {
2773
4652
  return { kind: "unknown", header, payload, checks };
2774
4653
  }
2775
4654
  try {
2776
- header = (0, import_jose2.decodeProtectedHeader)(trimmed);
2777
- payload = (0, import_jose2.decodeJwt)(trimmed);
4655
+ header = decodeProtectedHeader(trimmed);
4656
+ payload = decodeJwt(trimmed);
2778
4657
  } catch {
2779
4658
  checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
2780
4659
  return { kind: "unknown", header, payload, checks };
@@ -2804,7 +4683,7 @@ async function inspectToken(token, options = {}) {
2804
4683
  checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
2805
4684
  }
2806
4685
  try {
2807
- await (0, import_jose2.jwtVerify)(trimmed, (0, import_jose2.createRemoteJWKSet)(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
4686
+ await jwtVerify(trimmed, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
2808
4687
  checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
2809
4688
  } catch (error) {
2810
4689
  const code = error.code ?? "";
@@ -2919,7 +4798,7 @@ async function runDoctor(options) {
2919
4798
  } else {
2920
4799
  checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
2921
4800
  }
2922
- return { url, checks, ok: checks.every((check) => check.status !== "fail") };
4801
+ return { url, checks, ok: checks.every((check2) => check2.status !== "fail") };
2923
4802
  }
2924
4803
  function parseEnvFile(text) {
2925
4804
  const values = {};
@@ -2936,14 +4815,65 @@ function parseEnvFile(text) {
2936
4815
  }
2937
4816
  return values;
2938
4817
  }
4818
+
4819
+ // src/handle.ts
4820
+ async function kindeTest(options) {
4821
+ const testkit = options.testkit ?? await getDefaultTestkit();
4822
+ const token = await testkit.tokenFor(options.scenario, options.token);
4823
+ const headers = token ? { authorization: `Bearer ${token}` } : {};
4824
+ return {
4825
+ token,
4826
+ headers,
4827
+ principal: testkit.principalFor(options.scenario),
4828
+ request: { headers }
4829
+ };
4830
+ }
4831
+
4832
+ // src/sign-in-flow.ts
4833
+ function appLoginUrl(loginPath, options) {
4834
+ const params = new URLSearchParams({ login_hint: options.user });
4835
+ if (options.org) params.set("org_code", options.org);
4836
+ return `${loginPath}${loginPath.includes("?") ? "&" : "?"}${params}`;
4837
+ }
4838
+ function readSignInRequest(html) {
4839
+ const match = /name="request" value="([^"]+)"/.exec(html);
4840
+ if (!match) {
4841
+ throw new Error("The page is not the kinde-testkit sign-in page. Check that the app's KINDE_ISSUER_URL points at the testkit.");
4842
+ }
4843
+ return decodeEntities(match[1]);
4844
+ }
4845
+ function signInForm(request, options) {
4846
+ const form2 = { request, email: options.user };
4847
+ if (options.org) form2.org = options.org;
4848
+ return form2;
4849
+ }
4850
+ function signInFailure(status, html, options) {
4851
+ if (status === 200 && html.includes("Choose an organization")) {
4852
+ return new Error(`${options.user} belongs to more than one organization. Pass one with { org: "org_..." }.`);
4853
+ }
4854
+ const alert = /role="alert"[^>]*>([\s\S]*?)<\//.exec(html)?.[1];
4855
+ const text = alert ? decodeEntities(alert.replace(/<[^>]+>/g, "")).trim() : `the sign-in page answered ${status}`;
4856
+ return new Error(`kinde-testkit refused the sign-in: ${text}`);
4857
+ }
4858
+ function resolveLocation(location, from) {
4859
+ return new URL(location, from).toString();
4860
+ }
4861
+ function decodeEntities(value) {
4862
+ return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
4863
+ }
2939
4864
  // Annotate the CommonJS export names for ESM import in node:
2940
4865
  0 && (module.exports = {
4866
+ ActivityLog,
2941
4867
  BILLING_EVENT_TYPES,
4868
+ COVERAGE_GROUPS,
4869
+ CoverageRecorder,
2942
4870
  DEFAULT_AUTH_METHODS,
2943
4871
  DEFAULT_CLIENT_ID,
4872
+ DEFAULT_COVERAGE_DIRECTORY,
2944
4873
  DEFAULT_ISSUER,
2945
4874
  DEFAULT_M2M_CLIENT_ID,
2946
4875
  DEFAULT_SCOPES,
4876
+ DEFAULT_SEED_FILES,
2947
4877
  Directory,
2948
4878
  FailureInjector,
2949
4879
  INVALID_TOKEN_KINDS,
@@ -2952,22 +4882,35 @@ function parseEnvFile(text) {
2952
4882
  TestkitError,
2953
4883
  WEBHOOK_EVENT_TYPES,
2954
4884
  WebhookDispatcher,
4885
+ appLoginUrl,
4886
+ buildReport,
4887
+ clearCoverageDirectory,
2955
4888
  createKindeOrganization,
2956
4889
  createKindeToken,
2957
4890
  createKindeUser,
2958
4891
  createLocalCertificate,
2959
4892
  createMembership,
2960
4893
  ensureLocalCertificate,
4894
+ findSeedFile,
4895
+ formatCoverageReport,
2961
4896
  getDefaultTestkit,
2962
4897
  inspectToken,
2963
4898
  isAuthenticated,
4899
+ kindeTest,
4900
+ loadSeedFile,
4901
+ mergeSnapshots,
2964
4902
  parseEnvFile,
2965
4903
  principalFromClaims,
4904
+ readCoverageDirectory,
4905
+ readSignInRequest,
2966
4906
  resetFactories,
4907
+ resolveLocation,
2967
4908
  resolveSeed,
2968
4909
  runDoctor,
2969
4910
  scenario,
2970
4911
  seedScenario,
4912
+ signInFailure,
4913
+ signInForm,
2971
4914
  startKindeTestkit,
2972
4915
  toKindeRole
2973
4916
  });