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.
@@ -0,0 +1,4249 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/cypress.ts
21
+ var cypress_exports = {};
22
+ __export(cypress_exports, {
23
+ setupKindeTestkit: () => setupKindeTestkit
24
+ });
25
+ module.exports = __toCommonJS(cypress_exports);
26
+
27
+ // src/server.ts
28
+ var import_node_http = require("http");
29
+ var import_node_https = require("https");
30
+
31
+ // src/certificate.ts
32
+ var import_node_crypto = require("crypto");
33
+ var import_node_fs = require("fs");
34
+ var import_node_path = require("path");
35
+ var CERT_FILE = "localhost-cert.pem";
36
+ var KEY_FILE = "localhost-key.pem";
37
+ var VALID_DAYS = 825;
38
+ function ensureLocalCertificate(directory = ".kinde-testkit") {
39
+ const dir = (0, import_node_path.resolve)(directory);
40
+ const certPath = (0, import_node_path.join)(dir, CERT_FILE);
41
+ const keyPath = (0, import_node_path.join)(dir, KEY_FILE);
42
+ if ((0, import_node_fs.existsSync)(certPath) && (0, import_node_fs.existsSync)(keyPath)) {
43
+ const cert2 = (0, import_node_fs.readFileSync)(certPath, "utf8");
44
+ const key2 = (0, import_node_fs.readFileSync)(keyPath, "utf8");
45
+ try {
46
+ if (new Date(new import_node_crypto.X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
47
+ return { cert: cert2, key: key2, certPath, keyPath, created: false };
48
+ }
49
+ } catch {
50
+ }
51
+ }
52
+ const { cert, key } = createLocalCertificate();
53
+ (0, import_node_fs.mkdirSync)(dir, { recursive: true });
54
+ (0, import_node_fs.writeFileSync)(certPath, cert);
55
+ (0, import_node_fs.writeFileSync)(keyPath, key, { mode: 384 });
56
+ (0, import_node_fs.writeFileSync)((0, import_node_path.join)(dir, ".gitignore"), "*\n");
57
+ return { cert, key, certPath, keyPath, created: true };
58
+ }
59
+ function createLocalCertificate() {
60
+ const { publicKey, privateKey } = (0, import_node_crypto.generateKeyPairSync)("rsa", { modulusLength: 2048 });
61
+ const spki = publicKey.export({ type: "spki", format: "der" });
62
+ const keyId = (0, import_node_crypto.createHash)("sha1").update(subjectPublicKeyBits(spki)).digest();
63
+ const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
64
+ const now = Date.now();
65
+ const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
66
+ const serial = (0, import_node_crypto.randomBytes)(16);
67
+ serial[0] &= 127;
68
+ const extensions = seq(
69
+ seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
70
+ seq(oid("2.5.29.14"), octets(octets(keyId))),
71
+ seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
72
+ seq(
73
+ oid("2.5.29.17"),
74
+ octets(
75
+ seq(
76
+ tlv(130, Buffer.from("localhost")),
77
+ tlv(135, Buffer.from([127, 0, 0, 1])),
78
+ tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
79
+ )
80
+ )
81
+ )
82
+ );
83
+ const tbs = seq(
84
+ tlv(160, integer(Buffer.from([2]))),
85
+ integer(serial),
86
+ algorithm,
87
+ name,
88
+ seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
89
+ name,
90
+ spki,
91
+ tlv(163, extensions)
92
+ );
93
+ const signature = (0, import_node_crypto.sign)("sha256", tbs, privateKey);
94
+ const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
95
+ return {
96
+ cert: pem("CERTIFICATE", der),
97
+ key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
98
+ };
99
+ }
100
+ function subjectPublicKeyBits(spki) {
101
+ const outer = readTlv(spki, 0);
102
+ const algorithm = readTlv(spki, outer.start);
103
+ const bits = readTlv(spki, algorithm.end);
104
+ return spki.subarray(bits.start + 1, bits.end);
105
+ }
106
+ function readTlv(buf, offset) {
107
+ let len = buf[offset + 1];
108
+ let header = 2;
109
+ if (len & 128) {
110
+ const n = len & 127;
111
+ len = 0;
112
+ for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
113
+ header += n;
114
+ }
115
+ return { start: offset + header, end: offset + header + len };
116
+ }
117
+ function tlv(tag2, content) {
118
+ return Buffer.concat([Buffer.from([tag2]), length(content.length), content]);
119
+ }
120
+ function length(n) {
121
+ if (n < 128) return Buffer.from([n]);
122
+ const bytes = [];
123
+ while (n > 0) {
124
+ bytes.unshift(n & 255);
125
+ n >>= 8;
126
+ }
127
+ return Buffer.from([128 | bytes.length, ...bytes]);
128
+ }
129
+ function seq(...items) {
130
+ return tlv(48, Buffer.concat(items));
131
+ }
132
+ function set(...items) {
133
+ return tlv(49, Buffer.concat(items));
134
+ }
135
+ function octets(content) {
136
+ return tlv(4, content);
137
+ }
138
+ function integer(bytes) {
139
+ return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
140
+ }
141
+ function oid(dotted) {
142
+ const parts = dotted.split(".").map(Number);
143
+ const bytes = [parts[0] * 40 + parts[1]];
144
+ for (const part of parts.slice(2)) {
145
+ const chunk = [part & 127];
146
+ let value = part >> 7;
147
+ while (value > 0) {
148
+ chunk.unshift(value & 127 | 128);
149
+ value >>= 7;
150
+ }
151
+ bytes.push(...chunk);
152
+ }
153
+ return tlv(6, Buffer.from(bytes));
154
+ }
155
+ function utcTime(date) {
156
+ const iso = date.toISOString();
157
+ const value = `${iso.slice(2, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`;
158
+ return tlv(23, Buffer.from(value));
159
+ }
160
+ function pem(label, der) {
161
+ const body = der.toString("base64").match(/.{1,64}/g).join("\n");
162
+ return `-----BEGIN ${label}-----
163
+ ${body}
164
+ -----END ${label}-----
165
+ `;
166
+ }
167
+
168
+ // src/errors.ts
169
+ var TestkitError = class extends Error {
170
+ code;
171
+ details;
172
+ constructor(code, message2, details = []) {
173
+ super(details.length > 0 ? `${message2}
174
+
175
+ ${details.map((d) => ` - ${d}`).join("\n")}` : message2);
176
+ this.name = "TestkitError";
177
+ this.code = code;
178
+ this.details = details;
179
+ }
180
+ toString() {
181
+ return `${this.code}
182
+
183
+ ${this.message}`;
184
+ }
185
+ };
186
+
187
+ // src/testkit.ts
188
+ var import_node_crypto3 = require("crypto");
189
+
190
+ // node_modules/jose/dist/webapi/lib/buffer_utils.js
191
+ var encoder = new TextEncoder();
192
+ var decoder = new TextDecoder();
193
+ var strictDecoder = new TextDecoder("utf-8", { fatal: true });
194
+ var UINT32_RANGE = 2 ** 32;
195
+ function concat(...buffers) {
196
+ const size = buffers.reduce((acc, { length: length2 }) => acc + length2, 0), buf = new Uint8Array(size);
197
+ let i = 0;
198
+ for (const buffer of buffers)
199
+ buf.set(buffer, i), i += buffer.length;
200
+ return buf;
201
+ }
202
+ var NON_ASCII = /[^\x00-\x7f]/;
203
+ function encode(string) {
204
+ if (typeof string == "string" && string.length >= 128) {
205
+ if (NON_ASCII.test(string))
206
+ throw new TypeError("non-ASCII string encountered in encode()");
207
+ return encoder.encode(string);
208
+ }
209
+ const bytes = new Uint8Array(string.length);
210
+ for (let i = 0; i < string.length; i++) {
211
+ const code = string.charCodeAt(i);
212
+ if (code > 127)
213
+ throw new TypeError("non-ASCII string encountered in encode()");
214
+ bytes[i] = code;
215
+ }
216
+ return bytes;
217
+ }
218
+ function encodeBase64(input, url = false) {
219
+ if (Uint8Array.prototype.toBase64)
220
+ return input.toBase64({ alphabet: url ? "base64url" : "base64", omitPadding: url });
221
+ const CHUNK_SIZE = 32768, arr = [];
222
+ for (let i = 0; i < input.length; i += CHUNK_SIZE)
223
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
224
+ const encoded = btoa(arr.join(""));
225
+ return url ? encoded.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") : encoded;
226
+ }
227
+ function decodeBase64(encoded, url = false) {
228
+ if (Uint8Array.fromBase64)
229
+ return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
230
+ if (url) {
231
+ if (encoded.includes("+") || encoded.includes("/"))
232
+ throw new TypeError("Invalid base64url");
233
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
234
+ }
235
+ const binary = atob(encoded), bytes = new Uint8Array(binary.length);
236
+ for (let i = 0; i < binary.length; i++)
237
+ bytes[i] = binary.charCodeAt(i);
238
+ return bytes;
239
+ }
240
+ async function digest(algorithm, data) {
241
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
242
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
243
+ }
244
+
245
+ // node_modules/jose/dist/webapi/util/errors.js
246
+ var JOSEError = class extends Error {
247
+ static code = "ERR_JOSE_GENERIC";
248
+ code = "ERR_JOSE_GENERIC";
249
+ constructor(message2, options) {
250
+ super(message2, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
251
+ }
252
+ };
253
+ var JWTClaimValidationFailed = class extends JOSEError {
254
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
255
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
256
+ claim;
257
+ reason;
258
+ payload;
259
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
260
+ super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;
261
+ }
262
+ };
263
+ var JWTExpired = class extends JOSEError {
264
+ static code = "ERR_JWT_EXPIRED";
265
+ code = "ERR_JWT_EXPIRED";
266
+ claim;
267
+ reason;
268
+ payload;
269
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
270
+ super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;
271
+ }
272
+ };
273
+ var JOSEAlgNotAllowed = class extends JOSEError {
274
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
275
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
276
+ };
277
+ var JOSENotSupported = class extends JOSEError {
278
+ static code = "ERR_JOSE_NOT_SUPPORTED";
279
+ code = "ERR_JOSE_NOT_SUPPORTED";
280
+ };
281
+ var JWSInvalid = class extends JOSEError {
282
+ static code = "ERR_JWS_INVALID";
283
+ code = "ERR_JWS_INVALID";
284
+ };
285
+ var JWTInvalid = class extends JOSEError {
286
+ static code = "ERR_JWT_INVALID";
287
+ code = "ERR_JWT_INVALID";
288
+ };
289
+ var JWKInvalid = class extends JOSEError {
290
+ static code = "ERR_JWK_INVALID";
291
+ code = "ERR_JWK_INVALID";
292
+ };
293
+ var JWSSignatureVerificationFailed = class extends JOSEError {
294
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
295
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
296
+ constructor(message2 = "signature verification failed", options) {
297
+ super(message2, options);
298
+ }
299
+ };
300
+
301
+ // node_modules/jose/dist/webapi/util/base64url.js
302
+ var base64url_exports = {};
303
+ __export(base64url_exports, {
304
+ decode: () => decode,
305
+ encode: () => encode2
306
+ });
307
+ var invalid = "The input to be decoded is not correctly encoded.";
308
+ function decode(input) {
309
+ try {
310
+ return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true);
311
+ } catch (cause) {
312
+ throw new TypeError(invalid, { cause });
313
+ }
314
+ }
315
+ function encode2(input) {
316
+ return encodeBase64(typeof input == "string" ? encoder.encode(input) : input, true);
317
+ }
318
+
319
+ // node_modules/jose/dist/webapi/lib/validate.js
320
+ function isObject(input) {
321
+ if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]")
322
+ return false;
323
+ const prototype = Object.getPrototypeOf(input);
324
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
325
+ }
326
+ function isDisjoint(...headers) {
327
+ const parameters = /* @__PURE__ */ new Set();
328
+ for (const header of headers)
329
+ if (header)
330
+ for (const parameter of Object.keys(header)) {
331
+ if (parameters.has(parameter))
332
+ return false;
333
+ parameters.add(parameter);
334
+ }
335
+ return true;
336
+ }
337
+ function assertNotSet(value, name) {
338
+ if (value !== void 0)
339
+ throw new TypeError(`${name} can only be called once`);
340
+ }
341
+ function decodeBase64url(value, label, ErrorClass) {
342
+ try {
343
+ return decode(value);
344
+ } catch (cause) {
345
+ throw new ErrorClass(`Failed to base64url decode the ${label}`, { cause });
346
+ }
347
+ }
348
+ function encodeAsciiMember(value, label, ErrorClass) {
349
+ try {
350
+ return encode(value);
351
+ } catch (cause) {
352
+ throw new ErrorClass(`The ${label} is not a valid base64url string`, { cause });
353
+ }
354
+ }
355
+ function parseJoseHeader(encodedProtectedHeader, ErrorClass, message2) {
356
+ let parsed;
357
+ try {
358
+ parsed = JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)));
359
+ } catch (cause) {
360
+ throw new ErrorClass(message2, { cause });
361
+ }
362
+ if (!isObject(parsed))
363
+ throw new ErrorClass(message2);
364
+ return parsed;
365
+ }
366
+ var JWS_RECOGNIZED = { __proto__: null, b64: true };
367
+ function validateAlgorithms(option, algorithms) {
368
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string")))
369
+ throw new TypeError(`"${option}" option must be an array of strings`);
370
+ return algorithms === void 0 ? void 0 : new Set(algorithms);
371
+ }
372
+ function validateCritDuplicates(Err, protectedHeader) {
373
+ const { crit } = protectedHeader ?? {};
374
+ if (Array.isArray(crit) && new Set(crit).size !== crit.length)
375
+ throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
376
+ }
377
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
378
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)
379
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
380
+ if (!protectedHeader || protectedHeader.crit === void 0)
381
+ return [];
382
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0))
383
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
384
+ const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
385
+ for (const parameter of protectedHeader.crit) {
386
+ if (!(parameter in recognized))
387
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
388
+ if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)
389
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
390
+ if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))
391
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
392
+ }
393
+ return protectedHeader.crit;
394
+ }
395
+ function validateB64(protectedHeader, extensions) {
396
+ if (extensions.includes("b64")) {
397
+ const b64 = protectedHeader.b64;
398
+ if (typeof b64 != "boolean")
399
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
400
+ return b64;
401
+ }
402
+ return true;
403
+ }
404
+ function serializeJoseHeader(Err, header) {
405
+ let serialized, parsed;
406
+ try {
407
+ serialized = JSON.stringify(header), parsed = JSON.parse(serialized);
408
+ } catch (cause) {
409
+ throw new Err("JOSE Header is not valid JSON", { cause });
410
+ }
411
+ if (!isObject(parsed))
412
+ throw new Err("JOSE Header is not a JSON object");
413
+ return [parsed, serialized];
414
+ }
415
+
416
+ // node_modules/jose/dist/webapi/lib/key.js
417
+ var tag = (key) => key[Symbol.toStringTag];
418
+ var jwkMatchesOp = (entry, key, usage) => {
419
+ const { alg } = entry;
420
+ if (key.use !== void 0) {
421
+ const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
422
+ if (key.use !== expected)
423
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
424
+ }
425
+ if (key.alg !== void 0 && key.alg !== alg)
426
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
427
+ if (Array.isArray(key.key_ops)) {
428
+ const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
429
+ if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))
430
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
431
+ }
432
+ };
433
+ async function prepareKey(entry, key, usage) {
434
+ const { alg, secret } = entry, requiresPrivateKey = usage === "decrypt" || usage === "sign";
435
+ if (secret && key instanceof Uint8Array)
436
+ return key;
437
+ let normalized, keyObject;
438
+ if (isObject(key)) {
439
+ if (normalized = normalizeJwk(key), typeof normalized.kty != "string")
440
+ throw invalidKeyType(alg, key, secret);
441
+ 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)))
442
+ 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`);
443
+ if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct")
444
+ return decode(normalized.k);
445
+ if (!Object.isFrozen(key)) {
446
+ const { key_ops } = key;
447
+ Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
448
+ }
449
+ } else {
450
+ if (!isKeyLike(key))
451
+ throw invalidKeyType(alg, key, secret);
452
+ const expectedType = secret ? "secret" : requiresPrivateKey ? "private" : "public";
453
+ if (key.type !== expectedType && (secret || ["secret", "public", "private"].includes(key.type)))
454
+ throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
455
+ if (isCryptoKey(key))
456
+ return key;
457
+ if (keyObject = key, keyObject.type === "secret")
458
+ return keyObject.export();
459
+ }
460
+ cache ||= /* @__PURE__ */ new WeakMap();
461
+ const cacheKey = key;
462
+ let cached = cache.get(cacheKey);
463
+ if (cached?.[alg])
464
+ return cached[alg];
465
+ if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
466
+ const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;
467
+ return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
468
+ }
469
+ return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);
470
+ }
471
+ var cache;
472
+ var nist = {
473
+ __proto__: null,
474
+ prime256v1: "P-256",
475
+ secp384r1: "P-384",
476
+ secp521r1: "P-521"
477
+ };
478
+ var isCryptoKey = (key) => {
479
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
480
+ return true;
481
+ try {
482
+ return key instanceof CryptoKey;
483
+ } catch {
484
+ return false;
485
+ }
486
+ };
487
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
488
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
489
+ function message(msg, actual, ...types) {
490
+ if (types.length > 2) {
491
+ const last = types.pop();
492
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
493
+ } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
494
+ 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;
495
+ }
496
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
497
+ function invalidKeyType(alg, actual, secret) {
498
+ const types = ["CryptoKey", "KeyObject", "JSON Web Key"];
499
+ return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
500
+ }
501
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
502
+ function checkUsage(key, usage) {
503
+ if (usage && !key.usages.includes(usage))
504
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
505
+ }
506
+ function checkModulusLength(alg, key) {
507
+ const { modulusLength } = key.algorithm;
508
+ if (typeof modulusLength != "number" || modulusLength < 2048)
509
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
510
+ }
511
+ function checkCryptoKey(key, expected, usage) {
512
+ const algorithm = key.algorithm;
513
+ if (algorithm.name !== expected.name)
514
+ throw unusable(expected.name);
515
+ if (expected.hash && algorithm.hash?.name !== expected.hash)
516
+ throw unusable(expected.hash, "algorithm.hash");
517
+ if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)
518
+ throw unusable(expected.namedCurve, "algorithm.namedCurve");
519
+ if (expected.length !== void 0 && algorithm.length !== expected.length)
520
+ throw unusable(expected.length, "algorithm.length");
521
+ checkUsage(key, usage);
522
+ }
523
+ function snapshotJwk(jwk) {
524
+ return { __proto__: null, ...jwk };
525
+ }
526
+ function normalizeJwk(jwk) {
527
+ const normalized = snapshotJwk(jwk);
528
+ if (normalized.ext !== void 0 && typeof normalized.ext != "boolean")
529
+ throw new TypeError('"ext" (Extractable) Parameter must be a boolean');
530
+ if (normalized.key_ops !== void 0) {
531
+ const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
532
+ if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length)
533
+ throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');
534
+ normalized.key_ops = keyOps;
535
+ }
536
+ return normalized;
537
+ }
538
+ function validateExtractableOption(extractable) {
539
+ if (extractable !== void 0 && typeof extractable != "boolean")
540
+ throw new TypeError('"extractable" option must be a boolean');
541
+ return extractable;
542
+ }
543
+ async function jwkToKey(entry, jwk, extractable) {
544
+ if (!entry.kty.includes(jwk.kty))
545
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
546
+ const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };
547
+ 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]);
548
+ }
549
+ async function rawKey(key, expected, usage, extractable = false) {
550
+ return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
551
+ }
552
+
553
+ // node_modules/jose/dist/webapi/lib/key_descriptor.js
554
+ function table(entries) {
555
+ const out = { __proto__: null };
556
+ for (const alg in entries)
557
+ out[alg] = { ...entries[alg], alg };
558
+ return out;
559
+ }
560
+
561
+ // node_modules/jose/dist/webapi/lib/jwe_algorithms.js
562
+ var wrap = [
563
+ ["encrypt", "wrapKey"],
564
+ ["decrypt", "unwrapKey"]
565
+ ];
566
+ var derive = [[], ["deriveBits"]];
567
+ var none = [[], []];
568
+ function rsaes(bits) {
569
+ return {
570
+ kty: ["RSA"],
571
+ mode: "key-encryption",
572
+ subtle: { name: "RSA-OAEP", hash: `SHA-${bits}` },
573
+ usages: wrap,
574
+ ops: ["wrapKey", "unwrapKey"]
575
+ };
576
+ }
577
+ function ecdh(mode) {
578
+ return {
579
+ kty: ["EC", "OKP"],
580
+ mode,
581
+ subtle: { name: "ECDH" },
582
+ resolve: ({ kty, crv, asymmetricKeyType }) => {
583
+ if (crv === "X25519" || asymmetricKeyType === "x25519")
584
+ return { name: "X25519" };
585
+ if (kty === "OKP")
586
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
587
+ return { name: "ECDH", namedCurve: crv };
588
+ },
589
+ usages: derive,
590
+ ops: [void 0, "deriveBits"]
591
+ };
592
+ }
593
+ function aeskw(bits, gcm = false) {
594
+ return {
595
+ kty: ["oct"],
596
+ mode: "key-wrapping",
597
+ secret: true,
598
+ subtle: { name: gcm ? "AES-GCM" : "AES-KW", length: bits },
599
+ usages: none,
600
+ ops: gcm ? ["encrypt", "decrypt"] : ["wrapKey", "unwrapKey"]
601
+ };
602
+ }
603
+ function pbes2() {
604
+ return {
605
+ kty: ["oct"],
606
+ mode: "key-wrapping",
607
+ secret: true,
608
+ subtle: { name: "PBKDF2" },
609
+ usages: none,
610
+ ops: ["deriveBits", "deriveBits"]
611
+ };
612
+ }
613
+ var JWE = table({
614
+ dir: {
615
+ kty: ["oct"],
616
+ mode: "direct-encryption",
617
+ secret: true,
618
+ subtle: { name: "AES-GCM" },
619
+ usages: none,
620
+ ops: ["encrypt", "decrypt"]
621
+ },
622
+ "RSA-OAEP": rsaes(1),
623
+ "RSA-OAEP-256": rsaes(256),
624
+ "RSA-OAEP-384": rsaes(384),
625
+ "RSA-OAEP-512": rsaes(512),
626
+ "ECDH-ES": ecdh("direct-key-agreement"),
627
+ "ECDH-ES+A128KW": ecdh("key-agreement-with-key-wrapping"),
628
+ "ECDH-ES+A192KW": ecdh("key-agreement-with-key-wrapping"),
629
+ "ECDH-ES+A256KW": ecdh("key-agreement-with-key-wrapping"),
630
+ A128KW: aeskw(128),
631
+ A192KW: aeskw(192),
632
+ A256KW: aeskw(256),
633
+ A128GCMKW: aeskw(128, true),
634
+ A192GCMKW: aeskw(192, true),
635
+ A256GCMKW: aeskw(256, true),
636
+ "PBES2-HS256+A128KW": pbes2(),
637
+ "PBES2-HS384+A192KW": pbes2(),
638
+ "PBES2-HS512+A256KW": pbes2()
639
+ });
640
+ var contentOps = ["encrypt", "decrypt"];
641
+ function contentEncryption(bits, cbc = false) {
642
+ return {
643
+ kty: ["oct"],
644
+ secret: true,
645
+ subtle: { name: cbc ? "AES-CBC" : "AES-GCM", length: bits },
646
+ usages: none,
647
+ ops: contentOps,
648
+ cekBits: bits,
649
+ ivBits: cbc ? 128 : 96,
650
+ cbc
651
+ };
652
+ }
653
+ var ENC = table({
654
+ A128GCM: contentEncryption(128),
655
+ A192GCM: contentEncryption(192),
656
+ A256GCM: contentEncryption(256),
657
+ "A128CBC-HS256": contentEncryption(256, true),
658
+ "A192CBC-HS384": contentEncryption(384, true),
659
+ "A256CBC-HS512": contentEncryption(512, true)
660
+ });
661
+
662
+ // node_modules/jose/dist/webapi/lib/jws_algorithms.js
663
+ var sig = [["verify"], ["sign"]];
664
+ function hmac(bits) {
665
+ const subtle = { name: "HMAC", hash: `SHA-${bits}` };
666
+ return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
667
+ }
668
+ function rsa(bits, saltLength) {
669
+ const subtle = { name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash: `SHA-${bits}` };
670
+ return {
671
+ kty: ["RSA"],
672
+ subtle,
673
+ signing: saltLength ? { ...subtle, saltLength } : subtle,
674
+ usages: sig,
675
+ minRsaBits: 2048
676
+ };
677
+ }
678
+ function ecdsa(crv, bits) {
679
+ return {
680
+ kty: ["EC"],
681
+ crv,
682
+ subtle: { name: "ECDSA", namedCurve: crv },
683
+ signing: { name: "ECDSA", hash: `SHA-${bits}` },
684
+ usages: sig
685
+ };
686
+ }
687
+ function eddsa() {
688
+ const subtle = { name: "Ed25519" };
689
+ return {
690
+ kty: ["OKP"],
691
+ crv: "Ed25519",
692
+ subtle,
693
+ signing: subtle,
694
+ usages: sig
695
+ };
696
+ }
697
+ function mldsa(parameterSet) {
698
+ const subtle = { name: `ML-DSA-${parameterSet}` };
699
+ return {
700
+ kty: ["AKP"],
701
+ subtle,
702
+ signing: subtle,
703
+ usages: sig
704
+ };
705
+ }
706
+ var JWS = table({
707
+ HS256: hmac(256),
708
+ HS384: hmac(384),
709
+ HS512: hmac(512),
710
+ RS256: rsa(256),
711
+ RS384: rsa(384),
712
+ RS512: rsa(512),
713
+ PS256: rsa(256, 32),
714
+ PS384: rsa(384, 48),
715
+ PS512: rsa(512, 64),
716
+ ES256: ecdsa("P-256", 256),
717
+ ES384: ecdsa("P-384", 384),
718
+ ES512: ecdsa("P-521", 512),
719
+ EdDSA: eddsa(),
720
+ Ed25519: eddsa(),
721
+ "ML-DSA-44": mldsa(44),
722
+ "ML-DSA-65": mldsa(65),
723
+ "ML-DSA-87": mldsa(87)
724
+ });
725
+ function jwsAlgorithm(alg) {
726
+ const entry = typeof alg == "string" ? JWS[alg] : void 0;
727
+ if (!entry)
728
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
729
+ return entry;
730
+ }
731
+
732
+ // node_modules/jose/dist/webapi/lib/jws_verify.js
733
+ function prepareVerify(options) {
734
+ return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
735
+ }
736
+ function parseProtectedHeader(encodedProtectedHeader) {
737
+ return encodedProtectedHeader === void 0 ? {} : parseJoseHeader(encodedProtectedHeader, JWSInvalid, "JWS Protected Header is invalid");
738
+ }
739
+ function encodeCompactUnencodedPayload(payload) {
740
+ try {
741
+ return encode(payload);
742
+ } catch (cause) {
743
+ throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters", {
744
+ cause
745
+ });
746
+ }
747
+ }
748
+ async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
749
+ const { protected: encodedProtectedHeader, header, payload: inputPayload } = jws, protectedHeader = parsedProtected ?? parseProtectedHeader(encodedProtectedHeader);
750
+ if (!isDisjoint(protectedHeader, header))
751
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
752
+ const joseHeader = { ...protectedHeader, ...header }, b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], protectedHeader, joseHeader)), { alg } = joseHeader;
753
+ if (typeof alg != "string" || !alg)
754
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
755
+ if (shared[0] && !shared[0].has(alg))
756
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
757
+ if (b64) {
758
+ if (typeof inputPayload != "string")
759
+ throw new JWSInvalid("JWS Payload must be a string");
760
+ } else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array))
761
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
762
+ const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
763
+ let resolvedKey = false;
764
+ typeof key == "function" && (key = await key(protectedHeader, jws), resolvedKey = true);
765
+ 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");
766
+ entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
767
+ let verified = false;
768
+ try {
769
+ verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, signingInput);
770
+ } catch (cause) {
771
+ throw new JWSSignatureVerificationFailed(void 0, { cause });
772
+ }
773
+ if (!verified)
774
+ throw new JWSSignatureVerificationFailed();
775
+ const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
776
+ return encodedProtectedHeader !== void 0 && (result.protectedHeader = protectedHeader), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: verificationKey }, b64] : [result, b64];
777
+ }
778
+ async function verifyCompact(jws, shared, key) {
779
+ if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string")
780
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
781
+ const { 0: protectedHeader, 1: payload, 2: signature, length: length2 } = jws.split(".");
782
+ if (length2 !== 3)
783
+ throw new JWSInvalid("Invalid Compact JWS");
784
+ return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload);
785
+ }
786
+
787
+ // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
788
+ var epoch = (date) => Math.floor(date.getTime() / 1e3);
789
+ var multipliers = {
790
+ s: 1,
791
+ m: 60,
792
+ h: 3600,
793
+ d: 86400,
794
+ w: 604800,
795
+ y: 31557600
796
+ };
797
+ 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;
798
+ var checkFailed = "check_failed";
799
+ function invalidDuration() {
800
+ throw new TypeError("Invalid time period format");
801
+ }
802
+ function secs(str2) {
803
+ typeof str2 != "string" && invalidDuration();
804
+ const matched = REGEX.exec(str2);
805
+ (!matched || matched[4] && matched[1]) && invalidDuration();
806
+ const value = parseFloat(matched[2]), durationSeconds = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
807
+ return Number.isFinite(durationSeconds) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -durationSeconds : durationSeconds;
808
+ }
809
+ function validateInput(label, input) {
810
+ if (!Number.isFinite(input))
811
+ throw new TypeError(`Invalid ${label} input`);
812
+ return input;
813
+ }
814
+ function validateStringClaim(claim, value) {
815
+ if (typeof value != "string")
816
+ throw new TypeError(`"${claim}" claim must be a string`);
817
+ }
818
+ function validateAudienceClaim(value) {
819
+ if (typeof value != "string" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != "string")))
820
+ throw new TypeError('"aud" claim must be a string or an array of strings');
821
+ }
822
+ function numericDate(value, label) {
823
+ return typeof value == "number" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);
824
+ }
825
+ var normalizeTyp = (value) => {
826
+ const normalized = value.toLowerCase();
827
+ return value.includes("/") ? normalized : `application/${normalized}`;
828
+ };
829
+ var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false;
830
+ function validateNumericDate(claimsSet, claim, required = false) {
831
+ const value = claimsSet[claim];
832
+ if (!(value === void 0 && !required)) {
833
+ if (typeof value != "number")
834
+ throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, claimsSet, claim, "invalid");
835
+ return value;
836
+ }
837
+ }
838
+ function unexpectedClaim(claimsSet, claim) {
839
+ throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, claimsSet, claim, checkFailed);
840
+ }
841
+ function validateClaimsSet(protectedHeader, claimsSetBytes, options = {}) {
842
+ let claimsSet;
843
+ try {
844
+ claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));
845
+ } catch (cause) {
846
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object", { cause });
847
+ }
848
+ if (!isObject(claimsSet))
849
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
850
+ const { typ } = options;
851
+ if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))
852
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', claimsSet, "typ", checkFailed);
853
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
854
+ maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
855
+ for (const claim of new Set(presenceCheck.reverse()))
856
+ if (!Object.hasOwn(claimsSet, claim))
857
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claimsSet, claim, "missing");
858
+ 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");
859
+ const { clockTolerance } = options;
860
+ let tolerance = 0;
861
+ if (typeof clockTolerance == "string")
862
+ tolerance = secs(clockTolerance);
863
+ else if (clockTolerance !== void 0) {
864
+ if (typeof clockTolerance != "number")
865
+ throw new TypeError("Invalid clockTolerance option type");
866
+ tolerance = clockTolerance;
867
+ }
868
+ if (validateInput("clockTolerance option", tolerance), tolerance < 0)
869
+ throw new TypeError("Invalid clockTolerance option input");
870
+ 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");
871
+ if (nbf !== void 0 && nbf > now + tolerance)
872
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', claimsSet, "nbf", checkFailed);
873
+ const exp = validateNumericDate(claimsSet, "exp");
874
+ if (exp !== void 0 && exp <= now - tolerance)
875
+ throw new JWTExpired('"exp" claim timestamp check failed', claimsSet, "exp", checkFailed);
876
+ if (maxTokenAge !== void 0) {
877
+ const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
878
+ if (max < 0)
879
+ throw new TypeError("Invalid maxTokenAge option input");
880
+ if (age - tolerance > max)
881
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', claimsSet, "iat", checkFailed);
882
+ if (age < -tolerance)
883
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', claimsSet, "iat", checkFailed);
884
+ }
885
+ return claimsSet;
886
+ }
887
+ var producerClaimsSets;
888
+ function producerClaimsSet(producer) {
889
+ return producerClaimsSets.get(producer);
890
+ }
891
+ function jwtClaimsSetBytes(producer) {
892
+ const claimsSet = producerClaimsSet(producer);
893
+ for (const claim of ["iat", "nbf", "exp"]) {
894
+ const value = claimsSet[claim];
895
+ if (typeof value == "number" && !Number.isFinite(value))
896
+ throw new TypeError(`"${claim}" claim must be a finite number`);
897
+ }
898
+ return encoder.encode(JSON.stringify(claimsSet));
899
+ }
900
+ var JWTClaimsBuilder = class {
901
+ constructor(claimsSet = {}) {
902
+ if (!isObject(claimsSet))
903
+ throw new TypeError("JWT Claims Set MUST be an object");
904
+ (producerClaimsSets ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(claimsSet));
905
+ }
906
+ setIssuer(value) {
907
+ return validateStringClaim("iss", value), producerClaimsSet(this).iss = value, this;
908
+ }
909
+ setSubject(value) {
910
+ return validateStringClaim("sub", value), producerClaimsSet(this).sub = value, this;
911
+ }
912
+ setAudience(value) {
913
+ return validateAudienceClaim(value), producerClaimsSet(this).aud = value, this;
914
+ }
915
+ setJti(value) {
916
+ return validateStringClaim("jti", value), producerClaimsSet(this).jti = value, this;
917
+ }
918
+ setNotBefore(value) {
919
+ return producerClaimsSet(this).nbf = numericDate(value, "setNotBefore"), this;
920
+ }
921
+ setExpirationTime(value) {
922
+ return producerClaimsSet(this).exp = numericDate(value, "setExpirationTime"), this;
923
+ }
924
+ setIssuedAt(value) {
925
+ const claimsSet = producerClaimsSet(this);
926
+ 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;
927
+ }
928
+ };
929
+
930
+ // node_modules/jose/dist/webapi/jwt/verify.js
931
+ async function jwtVerify(jwt, key, options) {
932
+ const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
933
+ if (!b64)
934
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
935
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
936
+ return { ...verified, payload };
937
+ }
938
+
939
+ // node_modules/jose/dist/webapi/lib/jws_sign.js
940
+ async function createSignature(input, key, rejectUnencoded) {
941
+ let [payload, protectedHeader, unprotectedHeader, crit] = input, encodedProtectedHeader = "";
942
+ if (protectedHeader !== void 0) {
943
+ const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);
944
+ protectedHeader = normalized[0], encodedProtectedHeader = encode2(normalized[1]);
945
+ }
946
+ if (unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWSInvalid, unprotectedHeader)[0]), !protectedHeader && !unprotectedHeader)
947
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
948
+ if (!isDisjoint(protectedHeader, unprotectedHeader))
949
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
950
+ const joseHeader = { ...protectedHeader, ...unprotectedHeader };
951
+ validateCritDuplicates(JWSInvalid, protectedHeader);
952
+ const b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));
953
+ b64 || rejectUnencoded?.();
954
+ const { alg } = joseHeader;
955
+ if (typeof alg != "string" || !alg)
956
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
957
+ const entry = jwsAlgorithm(alg);
958
+ let encodedPayload = "", signingPayload = payload, signingInput;
959
+ if (b64) {
960
+ const encodedPayloadCache = input[4];
961
+ encodedPayloadCache ? (encodedPayload = encodedPayloadCache[0] ??= encode2(payload), signingPayload = encodedPayloadCache[1] ??= encode(encodedPayload)) : (encodedPayload = encode2(payload), signingInput = encoder.encode(`${encodedProtectedHeader}.${encodedPayload}`));
962
+ }
963
+ signingInput ??= concat(encode(encodedProtectedHeader), encode("."), signingPayload);
964
+ const signingKey = await rawKey(await prepareKey(entry, key, "sign"), entry.subtle, "sign");
965
+ entry.minRsaBits && checkModulusLength(entry.alg, signingKey);
966
+ const jws = {
967
+ signature: encode2(new Uint8Array(await crypto.subtle.sign(entry.signing, signingKey, signingInput))),
968
+ payload: encodedPayload
969
+ };
970
+ return protectedHeader && (jws.protected = encodedProtectedHeader), unprotectedHeader && (jws.header = unprotectedHeader), [jws, b64];
971
+ }
972
+ async function createCompactSignature(payload, protectedHeader, crit, key, rejectUnencoded) {
973
+ const [jws] = await createSignature([payload, protectedHeader, void 0, crit], key, rejectUnencoded);
974
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
975
+ }
976
+
977
+ // node_modules/jose/dist/webapi/jwt/sign.js
978
+ var SignJWT_base = JWTClaimsBuilder;
979
+ var SignJWT = class extends SignJWT_base {
980
+ #protectedHeader;
981
+ setProtectedHeader(protectedHeader) {
982
+ return assertNotSet(this.#protectedHeader, "setProtectedHeader"), this.#protectedHeader = protectedHeader, this;
983
+ }
984
+ async sign(key, options) {
985
+ return createCompactSignature(jwtClaimsSetBytes(this), this.#protectedHeader, options?.crit, key, () => {
986
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
987
+ });
988
+ }
989
+ };
990
+
991
+ // node_modules/jose/dist/webapi/lib/key_algorithm.js
992
+ var algArgument = '"alg" (Algorithm)';
993
+ function unsupportedAlg(source = 'JWK "alg" (Algorithm) Parameter') {
994
+ throw new JOSENotSupported(`Invalid or unsupported ${source} value`);
995
+ }
996
+ function keyAlgorithm(alg, source) {
997
+ return (typeof alg == "string" ? JWS[alg] ?? JWE[alg] : void 0) ?? unsupportedAlg(source);
998
+ }
999
+
1000
+ // node_modules/jose/dist/webapi/key/export.js
1001
+ async function exportJWK(key) {
1002
+ if (isKeyObject(key))
1003
+ if (key.type === "secret")
1004
+ key = key.export();
1005
+ else
1006
+ return key.export({ format: "jwk" });
1007
+ if (key instanceof Uint8Array)
1008
+ return {
1009
+ kty: "oct",
1010
+ k: encode2(key)
1011
+ };
1012
+ if (!isCryptoKey(key))
1013
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
1014
+ if (!key.extractable)
1015
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
1016
+ const jwk = await crypto.subtle.exportKey("jwk", key);
1017
+ delete jwk.ext, delete jwk.key_ops, delete jwk.use, jwk.kty !== "AKP" && delete jwk.alg;
1018
+ for (const parameter of Object.keys(jwk))
1019
+ jwk[parameter] === void 0 && delete jwk[parameter];
1020
+ return jwk;
1021
+ }
1022
+
1023
+ // node_modules/jose/dist/webapi/jwk/thumbprint.js
1024
+ var check = (value, description) => {
1025
+ if (typeof value != "string" || !value)
1026
+ throw new JWKInvalid(`${description} missing or invalid`);
1027
+ };
1028
+ async function calculateJwkThumbprint(key, digestAlgorithm) {
1029
+ let jwk;
1030
+ if (isObject(key)) {
1031
+ if (jwk = snapshotJwk(key), typeof jwk.kty != "string")
1032
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
1033
+ } else if (isKeyLike(key))
1034
+ jwk = snapshotJwk(await exportJWK(key));
1035
+ else
1036
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
1037
+ if (digestAlgorithm ??= "sha256", digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512")
1038
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
1039
+ let requiredMembers;
1040
+ switch (jwk.kty) {
1041
+ case "AKP":
1042
+ check(jwk.alg, '"alg" (Algorithm) Parameter'), check(jwk.pub, '"pub" (Public key) Parameter'), requiredMembers = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
1043
+ break;
1044
+ case "EC":
1045
+ 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 };
1046
+ break;
1047
+ case "OKP":
1048
+ 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 };
1049
+ break;
1050
+ case "RSA":
1051
+ check(jwk.e, '"e" (Exponent) Parameter'), check(jwk.n, '"n" (Modulus) Parameter'), requiredMembers = { e: jwk.e, kty: jwk.kty, n: jwk.n };
1052
+ break;
1053
+ case "oct":
1054
+ if (typeof jwk.k != "string")
1055
+ throw new JWKInvalid('"k" (Key Value) Parameter missing or invalid');
1056
+ requiredMembers = { k: jwk.k, kty: jwk.kty };
1057
+ break;
1058
+ default:
1059
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
1060
+ }
1061
+ const thumbprintInput = encode(JSON.stringify(requiredMembers));
1062
+ return encode2(await digest(digestAlgorithm, thumbprintInput));
1063
+ }
1064
+
1065
+ // node_modules/jose/dist/webapi/key/generate_key_pair.js
1066
+ function getModulusLengthOption(options) {
1067
+ const modulusLength = options?.modulusLength ?? 2048;
1068
+ if (typeof modulusLength != "number" || !Number.isInteger(modulusLength) || modulusLength < 2048)
1069
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
1070
+ return modulusLength;
1071
+ }
1072
+ async function generateKeyPair(alg, options) {
1073
+ const extractable = validateExtractableOption(options?.extractable), entry = keyAlgorithm(alg, algArgument);
1074
+ entry.secret && unsupportedAlg(algArgument);
1075
+ let algorithm;
1076
+ if (entry.resolve) {
1077
+ const crv = options?.crv ?? "P-256";
1078
+ if (!["P-256", "P-384", "P-521", "X25519"].includes(crv))
1079
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
1080
+ algorithm = entry.resolve({ crv });
1081
+ } else {
1082
+ if (entry.crv !== void 0 && options?.crv !== void 0 && options.crv !== entry.crv)
1083
+ throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${alg} is ${entry.crv}`);
1084
+ algorithm = entry.kty[0] === "RSA" ? {
1085
+ ...entry.subtle,
1086
+ publicExponent: Uint8Array.of(1, 0, 1),
1087
+ modulusLength: getModulusLengthOption(options)
1088
+ } : entry.subtle;
1089
+ }
1090
+ return crypto.subtle.generateKey(algorithm, extractable ?? false, [
1091
+ ...entry.usages[1],
1092
+ ...entry.usages[0]
1093
+ ]);
1094
+ }
1095
+
1096
+ // src/ids.ts
1097
+ var import_node_crypto2 = require("crypto");
1098
+ var counters = /* @__PURE__ */ new Map();
1099
+ function stableId(prefix, seed) {
1100
+ return `${prefix}_${(0, import_node_crypto2.createHash)("sha256").update(seed).digest("hex").slice(0, 16)}`;
1101
+ }
1102
+ function nextSequence(prefix) {
1103
+ const next = (counters.get(prefix) ?? 0) + 1;
1104
+ counters.set(prefix, next);
1105
+ return next;
1106
+ }
1107
+ function slug(value) {
1108
+ return value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
1109
+ }
1110
+ function titleCase(value) {
1111
+ return value.replace(/^org_/, "").split(/[_\-\s]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
1112
+ }
1113
+
1114
+ // src/factories.ts
1115
+ function createKindeUser(options = {}) {
1116
+ const email = options.email === void 0 ? `user-${nextSequence("user")}@example.test` : options.email;
1117
+ const id = options.id ?? (email ? stableId("kp", email) : `kp_test_${nextSequence("kp")}`);
1118
+ return {
1119
+ id,
1120
+ email,
1121
+ emailVerified: options.emailVerified ?? email !== null,
1122
+ givenName: options.givenName === void 0 ? null : options.givenName,
1123
+ familyName: options.familyName === void 0 ? null : options.familyName,
1124
+ picture: options.picture === void 0 ? null : options.picture,
1125
+ claims: { ...options.claims ?? {} }
1126
+ };
1127
+ }
1128
+ function createKindeOrganization(options = {}) {
1129
+ const code = options.code ?? (options.name ? `org_${slug(options.name)}` : `org_test_${nextSequence("org")}`);
1130
+ return {
1131
+ code,
1132
+ name: options.name ?? titleCase(code),
1133
+ metadata: { ...options.metadata ?? {} }
1134
+ };
1135
+ }
1136
+ function createMembership(options) {
1137
+ return {
1138
+ userId: options.userId,
1139
+ organizationCode: options.organizationCode,
1140
+ roles: unique(options.roles ?? []),
1141
+ permissions: unique(options.permissions ?? [])
1142
+ };
1143
+ }
1144
+ function toKindeRole(role) {
1145
+ if (typeof role !== "string") return role;
1146
+ return { id: stableId("role", role), key: role, name: titleCase(role) };
1147
+ }
1148
+ function unique(values) {
1149
+ return [...new Set(values)];
1150
+ }
1151
+
1152
+ // src/duration.ts
1153
+ var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
1154
+ function toSeconds(value) {
1155
+ if (typeof value === "number") {
1156
+ if (!Number.isFinite(value) || value < 0) throw invalid2(String(value));
1157
+ return Math.floor(value);
1158
+ }
1159
+ const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
1160
+ if (!match) {
1161
+ if (/^\d+$/.test(value.trim())) return Number(value.trim());
1162
+ throw invalid2(value);
1163
+ }
1164
+ return Number(match[1]) * UNITS[match[2]];
1165
+ }
1166
+ function invalid2(value) {
1167
+ return new TestkitError(
1168
+ "INVALID_DURATION",
1169
+ `"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
1170
+ );
1171
+ }
1172
+
1173
+ // src/testkit.ts
1174
+ var DEFAULT_ISSUER = "http://localhost:4400";
1175
+ var DEFAULT_CLIENT_ID = "kinde_testkit_client";
1176
+ var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
1177
+ var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
1178
+ var DEFAULT_AUTH_METHODS = ["email"];
1179
+ var INVALID_TOKEN_KINDS = [
1180
+ "expired",
1181
+ "wrong-issuer",
1182
+ "wrong-audience",
1183
+ "missing-subject",
1184
+ "missing-organization",
1185
+ "missing-permissions",
1186
+ "future-iat",
1187
+ "bad-signature",
1188
+ "unknown-key",
1189
+ "unsigned"
1190
+ ];
1191
+ var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
1192
+ var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
1193
+ var KindeTestkit = class _KindeTestkit {
1194
+ observers = [];
1195
+ /** Calls the observer for every token signed from now on. Returns a function that stops it. */
1196
+ observe(observer) {
1197
+ this.observers.push(observer);
1198
+ return () => {
1199
+ this.observers = this.observers.filter((o) => o !== observer);
1200
+ };
1201
+ }
1202
+ async signAccess(payload, invalid3, now) {
1203
+ const final = applyInvalidClaims(payload, invalid3, now);
1204
+ const token = await this.sign(final, invalid3);
1205
+ for (const observer of this.observers) observer.accessToken?.(final, invalid3, token);
1206
+ return token;
1207
+ }
1208
+ issuer;
1209
+ audience;
1210
+ clientId;
1211
+ accessTokenExpiresIn;
1212
+ idTokenExpiresIn;
1213
+ clock;
1214
+ signingKey;
1215
+ strangerKey = null;
1216
+ static async create(options = {}) {
1217
+ return new _KindeTestkit(options, await createSigningKey("kinde-testkit"));
1218
+ }
1219
+ constructor(options, signingKey) {
1220
+ this.issuer = trimSlash(options.issuer ?? DEFAULT_ISSUER);
1221
+ this.audience = toArray(options.audience);
1222
+ this.clientId = options.clientId ?? DEFAULT_CLIENT_ID;
1223
+ this.accessTokenExpiresIn = options.accessTokenExpiresIn ?? "24h";
1224
+ this.idTokenExpiresIn = options.idTokenExpiresIn ?? "1h";
1225
+ this.clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
1226
+ this.signingKey = signingKey;
1227
+ warnIfRealKindeDomain(this.issuer);
1228
+ }
1229
+ get jwksUri() {
1230
+ return `${this.issuer}/.well-known/jwks`;
1231
+ }
1232
+ get keyId() {
1233
+ return this.signingKey.kid;
1234
+ }
1235
+ get accessTokenLifetime() {
1236
+ return toSeconds(this.accessTokenExpiresIn);
1237
+ }
1238
+ async verify(token) {
1239
+ const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
1240
+ issuer: this.issuer,
1241
+ algorithms: ["RS256"]
1242
+ });
1243
+ return payload;
1244
+ }
1245
+ jwks() {
1246
+ return { keys: [{ ...this.signingKey.publicJwk }] };
1247
+ }
1248
+ async token(options = {}) {
1249
+ const now = this.clock();
1250
+ const payload = {
1251
+ amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
1252
+ aud: [...options.audience ?? this.audience],
1253
+ auth_time: options.authTime ?? now,
1254
+ azp: options.clientId ?? this.clientId,
1255
+ exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
1256
+ iat: now,
1257
+ iss: this.issuer,
1258
+ jti: (0, import_node_crypto3.randomUUID)(),
1259
+ scp: [...options.scopes ?? DEFAULT_SCOPES],
1260
+ sub: options.subject ?? stableId("kp", "default-test-user")
1261
+ };
1262
+ if (options.permissions !== void 0) payload.permissions = [...options.permissions];
1263
+ if (options.roles !== void 0) payload.roles = options.roles.map(toKindeRole);
1264
+ if (options.organizationCode) payload.org_code = options.organizationCode;
1265
+ if (options.featureFlags) payload.feature_flags = options.featureFlags;
1266
+ Object.assign(payload, options.claims ?? {});
1267
+ return this.signAccess(payload, options.invalid, now);
1268
+ }
1269
+ async m2mToken(options = {}) {
1270
+ const now = this.clock();
1271
+ const requested = [...options.scopes ?? []];
1272
+ const granted = [...options.grantedScopes ?? requested];
1273
+ const payload = {
1274
+ aud: [...options.audience ?? this.audience],
1275
+ azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
1276
+ exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
1277
+ gty: ["client_credentials"],
1278
+ iat: now,
1279
+ iss: this.issuer,
1280
+ jti: (0, import_node_crypto3.randomUUID)(),
1281
+ scope: granted.join(" "),
1282
+ scp: requested,
1283
+ v: "2"
1284
+ };
1285
+ if (options.organizationCode) payload.org_code = options.organizationCode;
1286
+ if (options.permissions !== void 0) payload.permissions = [...options.permissions];
1287
+ Object.assign(payload, options.claims ?? {});
1288
+ return this.signAccess(payload, options.invalid, now);
1289
+ }
1290
+ async tokenFor(scenario, overrides = {}) {
1291
+ if (scenario.kind === "unauthenticated") {
1292
+ for (const observer of this.observers) observer.anonymous?.();
1293
+ return null;
1294
+ }
1295
+ return this.token({
1296
+ subject: scenario.user.id,
1297
+ organizationCode: scenario.organization?.code ?? null,
1298
+ roles: scenario.roles.length > 0 ? scenario.roles : void 0,
1299
+ permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
1300
+ ...overrides,
1301
+ claims: { ...scenario.claims, ...overrides.claims ?? {} }
1302
+ });
1303
+ }
1304
+ async idTokenFor(scenario, options = {}) {
1305
+ if (scenario.kind === "unauthenticated") return null;
1306
+ const { user, organization } = scenario;
1307
+ const now = this.clock();
1308
+ const authTime = options.authTime ?? now;
1309
+ const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
1310
+ const clientId = options.clientId ?? this.clientId;
1311
+ const payload = {
1312
+ amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
1313
+ aud: [clientId],
1314
+ auth_time: authTime,
1315
+ azp: clientId,
1316
+ email: user.email,
1317
+ email_verified: user.emailVerified,
1318
+ exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
1319
+ family_name: user.familyName,
1320
+ given_name: user.givenName,
1321
+ iat: now,
1322
+ iss: this.issuer,
1323
+ jti: (0, import_node_crypto3.randomUUID)(),
1324
+ name: name || null,
1325
+ nonce: options.nonce,
1326
+ org_codes: organization ? [organization.code] : void 0,
1327
+ picture: user.picture,
1328
+ rat: authTime,
1329
+ sub: user.id,
1330
+ updated_at: now,
1331
+ ...user.claims
1332
+ };
1333
+ for (const key of Object.keys(payload)) {
1334
+ if (payload[key] === null || payload[key] === void 0) delete payload[key];
1335
+ }
1336
+ const token = await this.sign(payload);
1337
+ for (const observer of this.observers) observer.idToken?.(payload, token);
1338
+ return token;
1339
+ }
1340
+ async headersFor(scenario, overrides = {}) {
1341
+ const token = await this.tokenFor(scenario, overrides);
1342
+ return token ? { authorization: `Bearer ${token}` } : {};
1343
+ }
1344
+ principalFor(scenario) {
1345
+ if (scenario.kind === "unauthenticated") return null;
1346
+ return scenarioPrincipal(scenario, this.issuer);
1347
+ }
1348
+ async signPayload(payload, invalid3) {
1349
+ return this.sign(payload, invalid3);
1350
+ }
1351
+ async sign(payload, invalid3) {
1352
+ if (invalid3 === "unsigned") {
1353
+ const header = base64url_exports.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
1354
+ return `${header}.${base64url_exports.encode(JSON.stringify(payload))}.`;
1355
+ }
1356
+ const key = invalid3 === "unknown-key" ? await this.stranger() : this.signingKey;
1357
+ const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
1358
+ return invalid3 === "bad-signature" ? tamperSignature(jwt) : jwt;
1359
+ }
1360
+ stranger() {
1361
+ this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
1362
+ return this.strangerKey;
1363
+ }
1364
+ };
1365
+ function scenarioPrincipal(scenario, issuer) {
1366
+ return {
1367
+ type: "user",
1368
+ subject: scenario.user.id,
1369
+ issuer,
1370
+ organization: scenario.organization ? { code: scenario.organization.code } : null,
1371
+ roles: [...scenario.roles],
1372
+ permissions: [...scenario.permissions],
1373
+ claims: { ...scenario.claims }
1374
+ };
1375
+ }
1376
+ function applyInvalidClaims(payload, invalid3, now) {
1377
+ const next = { ...payload };
1378
+ switch (invalid3) {
1379
+ case "expired":
1380
+ next.iat = now - 7200;
1381
+ next.exp = now - 3600;
1382
+ break;
1383
+ case "future-iat":
1384
+ next.iat = now + 3600;
1385
+ next.exp = now + 7200;
1386
+ break;
1387
+ case "wrong-issuer":
1388
+ next.iss = WRONG_ISSUER;
1389
+ break;
1390
+ case "wrong-audience":
1391
+ next.aud = [WRONG_AUDIENCE];
1392
+ break;
1393
+ case "missing-subject":
1394
+ delete next.sub;
1395
+ break;
1396
+ case "missing-organization":
1397
+ delete next.org_code;
1398
+ break;
1399
+ case "missing-permissions":
1400
+ next.permissions = [];
1401
+ break;
1402
+ default:
1403
+ break;
1404
+ }
1405
+ return next;
1406
+ }
1407
+ async function createSigningKey(prefix) {
1408
+ const { privateKey, publicKey } = await generateKeyPair("RS256");
1409
+ const jwk = await exportJWK(publicKey);
1410
+ const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
1411
+ return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
1412
+ }
1413
+ function tamperSignature(jwt) {
1414
+ const [header, payload, signature] = jwt.split(".");
1415
+ const bytes = base64url_exports.decode(signature);
1416
+ bytes[0] = (bytes[0] ?? 0) ^ 255;
1417
+ return `${header}.${payload}.${base64url_exports.encode(bytes)}`;
1418
+ }
1419
+ function toArray(value) {
1420
+ if (value === void 0) return [];
1421
+ return Array.isArray(value) ? [...value] : [value];
1422
+ }
1423
+ function trimSlash(value) {
1424
+ return value.replace(/\/+$/, "");
1425
+ }
1426
+ function warnIfRealKindeDomain(issuer) {
1427
+ if (/^https:\/\/[^/]+\.kinde\.com$/i.test(issuer)) {
1428
+ process.emitWarning(
1429
+ `kinde-testkit issuer is set to ${issuer}, which looks like a real Kinde domain. Test tokens are signed with a local key and will never verify against Kinde's JWKS.`,
1430
+ { code: "KINDE_TESTKIT_REAL_ISSUER" }
1431
+ );
1432
+ }
1433
+ }
1434
+
1435
+ // src/login-page.ts
1436
+ var STYLE = `
1437
+ :root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--warn:#8a5a00;--warn-bg:#fff6e0}
1438
+ @media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--warn:#f0c46a;--warn-bg:#2a2210}}
1439
+ *{box-sizing:border-box}
1440
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;padding:24px}
1441
+ main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
1442
+ .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
1443
+ h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
1444
+ p{margin:0;color:var(--muted)}
1445
+ .note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
1446
+ form{margin:0}
1447
+ label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
1448
+ input[type=email]{width:100%;height:42px;padding:0 12px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit}
1449
+ input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
1450
+ .primary{margin-top:12px;width:100%;height:42px;border:0;border-radius:8px;background:var(--accent);color:var(--accent-ink);font-family:inherit;font-size:15px;font-weight:600;cursor:pointer}
1451
+ h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
1452
+ .list{display:grid;gap:8px}
1453
+ .option{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;padding:11px 12px;border:1px solid var(--line);border-radius:8px;background:transparent;color:var(--ink);font:inherit;cursor:pointer}
1454
+ .option:hover{border-color:var(--muted)}
1455
+ .option strong{display:block;font-weight:500}
1456
+ .option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
1457
+ .tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
1458
+ .error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
1459
+ `;
1460
+ function escapeHtml(value) {
1461
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1462
+ }
1463
+ function layout(title, body) {
1464
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body><main><div class="brand">kinde-testkit</div>${body}</main></body></html>`;
1465
+ }
1466
+ function displayName(user) {
1467
+ return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
1468
+ }
1469
+ function renderSignIn(options) {
1470
+ const users = options.users.map(({ user, organizations }) => {
1471
+ const value = escapeHtml(user.email ?? user.id);
1472
+ const hasName = Boolean(user.givenName || user.familyName);
1473
+ const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
1474
+ const tag2 = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
1475
+ 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>`;
1476
+ }).join("");
1477
+ const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
1478
+ return layout(
1479
+ "Sign in",
1480
+ `<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}</form>`
1481
+ );
1482
+ }
1483
+ function renderOrganizationPicker(options) {
1484
+ const choices = options.organizations.map(
1485
+ (org) => `<button class="option" type="submit" name="org" value="${escapeHtml(org.code)}"><span><strong>${escapeHtml(org.name)}</strong><small>${escapeHtml(org.code)}</small></span></button>`
1486
+ ).join("");
1487
+ return layout(
1488
+ "Choose an organization",
1489
+ `<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>`
1490
+ );
1491
+ }
1492
+ function renderMessage(title, message2) {
1493
+ return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message2)}</p>`);
1494
+ }
1495
+
1496
+ // src/seed.ts
1497
+ function roleRecord(key, extra = {}) {
1498
+ return {
1499
+ id: stableId("role", key),
1500
+ key,
1501
+ name: extra.name ?? titleCase(key),
1502
+ description: extra.description ?? null,
1503
+ isDefault: extra.isDefault ?? false,
1504
+ permissions: [...extra.permissions ?? []]
1505
+ };
1506
+ }
1507
+ function permissionRecord(key, extra = {}) {
1508
+ return {
1509
+ id: stableId("perm", key),
1510
+ key,
1511
+ name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
1512
+ description: extra.description ?? null
1513
+ };
1514
+ }
1515
+ function effectivePermissions(seed, membership) {
1516
+ if (!membership) return [];
1517
+ const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
1518
+ return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
1519
+ }
1520
+ function resolveSeed(input) {
1521
+ const problems = [];
1522
+ if (!isRecord(input)) {
1523
+ throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
1524
+ }
1525
+ const rawUsers = listOf(input.users, "users", problems);
1526
+ const rawOrganizations = listOf(input.organizations, "organizations", problems);
1527
+ const rawMemberships = listOf(input.memberships, "memberships", problems);
1528
+ const rawApplications = listOf(input.applications, "applications", problems);
1529
+ const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
1530
+ const rawRoles = listOf(input.roles, "roles", problems);
1531
+ const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
1532
+ const rawPlans = listOf(input.plans, "plans", problems);
1533
+ const rawPermissions = listOf(input.permissions, "permissions", problems);
1534
+ const webhooks = [];
1535
+ rawWebhooks.forEach((raw, index) => {
1536
+ if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
1537
+ problems.push(`webhooks[${index}] needs an http or https "url".`);
1538
+ return;
1539
+ }
1540
+ if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
1541
+ problems.push(`webhooks[${index}].events must be a list of event type names.`);
1542
+ return;
1543
+ }
1544
+ webhooks.push({ url: raw.url, events: raw.events });
1545
+ });
1546
+ const users = [];
1547
+ rawUsers.forEach((raw, index) => {
1548
+ if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
1549
+ problems.push(`users[${index}] needs a string "id".`);
1550
+ return;
1551
+ }
1552
+ if (users.some((user) => user.id === raw.id)) {
1553
+ problems.push(`users[${index}] repeats the id "${raw.id}".`);
1554
+ return;
1555
+ }
1556
+ users.push(createKindeUser(raw));
1557
+ });
1558
+ const organizations = [];
1559
+ rawOrganizations.forEach((raw, index) => {
1560
+ if (!isRecord(raw) || typeof raw.code !== "string" || raw.code.length === 0) {
1561
+ problems.push(`organizations[${index}] needs a string "code".`);
1562
+ return;
1563
+ }
1564
+ if (organizations.some((org) => org.code === raw.code)) {
1565
+ problems.push(`organizations[${index}] repeats the code "${raw.code}".`);
1566
+ return;
1567
+ }
1568
+ organizations.push(createKindeOrganization(raw));
1569
+ });
1570
+ const memberships = [];
1571
+ rawMemberships.forEach((raw, index) => {
1572
+ if (!isRecord(raw) || typeof raw.user !== "string" || typeof raw.organization !== "string") {
1573
+ problems.push(`memberships[${index}] needs string "user" and "organization" fields.`);
1574
+ return;
1575
+ }
1576
+ const user = findUser(users, raw.user);
1577
+ if (!user) problems.push(`memberships[${index}] points to an unknown user "${raw.user}".`);
1578
+ if (!organizations.some((org) => org.code === raw.organization)) {
1579
+ problems.push(`memberships[${index}] points to an unknown organization "${raw.organization}".`);
1580
+ }
1581
+ for (const field of ["roles", "permissions"]) {
1582
+ const value = raw[field];
1583
+ if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
1584
+ problems.push(`memberships[${index}].${field} must be a list of strings.`);
1585
+ }
1586
+ }
1587
+ if (!user) return;
1588
+ if (memberships.some((m) => m.userId === user.id && m.organizationCode === raw.organization)) {
1589
+ problems.push(`memberships[${index}] repeats ${user.id} in ${raw.organization}.`);
1590
+ return;
1591
+ }
1592
+ memberships.push(
1593
+ createMembership({
1594
+ userId: user.id,
1595
+ organizationCode: raw.organization,
1596
+ roles: raw.roles,
1597
+ permissions: raw.permissions
1598
+ })
1599
+ );
1600
+ });
1601
+ const applications = [];
1602
+ rawApplications.forEach((raw, index) => {
1603
+ if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
1604
+ problems.push(`applications[${index}] needs a string "clientId".`);
1605
+ return;
1606
+ }
1607
+ if (applications.some((app) => app.clientId === raw.clientId)) {
1608
+ problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
1609
+ return;
1610
+ }
1611
+ if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
1612
+ problems.push(`applications[${index}].clientSecret must be a string.`);
1613
+ }
1614
+ if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
1615
+ problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
1616
+ }
1617
+ for (const field of ["scopes", "permissions"]) {
1618
+ const value = raw[field];
1619
+ if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
1620
+ problems.push(`applications[${index}].${field} must be a list of strings.`);
1621
+ }
1622
+ }
1623
+ const audience = raw.audience;
1624
+ applications.push({
1625
+ clientId: raw.clientId,
1626
+ clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
1627
+ name: typeof raw.name === "string" ? raw.name : raw.clientId,
1628
+ organizationCode: typeof raw.organization === "string" ? raw.organization : null,
1629
+ scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
1630
+ permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
1631
+ audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
1632
+ });
1633
+ });
1634
+ if (problems.length > 0) {
1635
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
1636
+ }
1637
+ const permissions = [];
1638
+ rawPermissions.forEach((raw, index) => {
1639
+ if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
1640
+ problems.push(`permissions[${index}] needs a string "key".`);
1641
+ return;
1642
+ }
1643
+ if (permissions.some((p) => p.key === raw.key)) {
1644
+ problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
1645
+ return;
1646
+ }
1647
+ permissions.push(
1648
+ permissionRecord(raw.key, {
1649
+ name: typeof raw.name === "string" ? raw.name : void 0,
1650
+ description: typeof raw.description === "string" ? raw.description : void 0
1651
+ })
1652
+ );
1653
+ });
1654
+ const roles = [];
1655
+ rawRoles.forEach((raw, index) => {
1656
+ if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
1657
+ problems.push(`roles[${index}] needs a string "key".`);
1658
+ return;
1659
+ }
1660
+ if (roles.some((r) => r.key === raw.key)) {
1661
+ problems.push(`roles[${index}] repeats the key "${raw.key}".`);
1662
+ return;
1663
+ }
1664
+ if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
1665
+ problems.push(`roles[${index}].permissions must be a list of permission keys.`);
1666
+ return;
1667
+ }
1668
+ roles.push(
1669
+ roleRecord(raw.key, {
1670
+ name: typeof raw.name === "string" ? raw.name : void 0,
1671
+ description: typeof raw.description === "string" ? raw.description : void 0,
1672
+ isDefault: raw.isDefault === true,
1673
+ permissions: raw.permissions ?? []
1674
+ })
1675
+ );
1676
+ });
1677
+ if (problems.length > 0) {
1678
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
1679
+ }
1680
+ const featureFlags = [];
1681
+ rawFlags.forEach((raw, index) => {
1682
+ if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
1683
+ problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
1684
+ return;
1685
+ }
1686
+ const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
1687
+ featureFlags.push({
1688
+ id: stableId("flag", raw.key),
1689
+ key: raw.key,
1690
+ name: typeof raw.name === "string" ? raw.name : raw.key,
1691
+ type,
1692
+ value: raw.value,
1693
+ organizations: isRecord(raw.organizations) ? raw.organizations : {}
1694
+ });
1695
+ });
1696
+ const plans = [];
1697
+ rawPlans.forEach((raw, index) => {
1698
+ if (!isRecord(raw) || typeof raw.key !== "string") {
1699
+ problems.push(`plans[${index}] needs a string "key".`);
1700
+ return;
1701
+ }
1702
+ const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
1703
+ plans.push({
1704
+ key: raw.key,
1705
+ name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
1706
+ subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
1707
+ subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
1708
+ entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
1709
+ id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
1710
+ featureKey: e.featureKey,
1711
+ featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
1712
+ priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
1713
+ fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
1714
+ unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
1715
+ limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
1716
+ limitMin: typeof e.limitMin === "number" ? e.limitMin : null
1717
+ }))
1718
+ });
1719
+ });
1720
+ const userProperties = {};
1721
+ rawUsers.forEach((raw) => {
1722
+ if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
1723
+ userProperties[raw.id] = raw.properties;
1724
+ }
1725
+ });
1726
+ if (problems.length > 0) {
1727
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
1728
+ }
1729
+ const usedRoles = new Set(memberships.flatMap((m) => m.roles));
1730
+ for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
1731
+ const usedPermissions = /* @__PURE__ */ new Set([
1732
+ ...memberships.flatMap((m) => m.permissions),
1733
+ ...roles.flatMap((r) => r.permissions),
1734
+ ...applications.flatMap((a) => a.permissions ?? [])
1735
+ ]);
1736
+ for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
1737
+ return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
1738
+ }
1739
+ function findUser(users, ref) {
1740
+ const needle = ref.toLowerCase();
1741
+ return users.find((user) => user.id === ref || user.email?.toLowerCase() === needle);
1742
+ }
1743
+ function seedScenario(seed, ref) {
1744
+ const user = findUser(seed.users, ref.user);
1745
+ if (!user) {
1746
+ throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${ref.user}".`, [
1747
+ `Known users: ${seed.users.map((u) => u.email ?? u.id).join(", ") || "none"}`
1748
+ ]);
1749
+ }
1750
+ const userMemberships = seed.memberships.filter((m) => m.userId === user.id);
1751
+ let membership;
1752
+ if (ref.organization) {
1753
+ if (!seed.organizations.some((org) => org.code === ref.organization)) {
1754
+ throw new TestkitError(
1755
+ "SEED_UNKNOWN_ORGANIZATION",
1756
+ `No seeded organization has the code "${ref.organization}".`
1757
+ );
1758
+ }
1759
+ membership = userMemberships.find((m) => m.organizationCode === ref.organization);
1760
+ if (!membership) {
1761
+ throw new TestkitError(
1762
+ "SEED_NO_MEMBERSHIP",
1763
+ `${user.email ?? user.id} is not a member of ${ref.organization}, so Kinde would not issue a token for that organization.`,
1764
+ [`Member of: ${userMemberships.map((m) => m.organizationCode).join(", ") || "no organizations"}`]
1765
+ );
1766
+ }
1767
+ } else if (userMemberships.length === 1) {
1768
+ membership = userMemberships[0];
1769
+ } else if (userMemberships.length > 1) {
1770
+ throw new TestkitError(
1771
+ "INVALID_REQUEST",
1772
+ `${user.email ?? user.id} belongs to ${userMemberships.length} organizations. Choose the active one.`,
1773
+ [`Organizations: ${userMemberships.map((m) => m.organizationCode).join(", ")}`]
1774
+ );
1775
+ }
1776
+ const organization = membership ? seed.organizations.find((org) => org.code === membership.organizationCode) ?? null : null;
1777
+ return {
1778
+ kind: "authenticated",
1779
+ user,
1780
+ organization,
1781
+ roles: [...membership?.roles ?? []],
1782
+ permissions: effectivePermissions(seed, membership),
1783
+ claims: {}
1784
+ };
1785
+ }
1786
+ function listOf(value, field, problems) {
1787
+ if (value === void 0) return [];
1788
+ if (!Array.isArray(value)) {
1789
+ problems.push(`"${field}" must be a list.`);
1790
+ return [];
1791
+ }
1792
+ return value;
1793
+ }
1794
+ function isRecord(value) {
1795
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1796
+ }
1797
+ function featureFlagsFor(seed, organizationCode) {
1798
+ if (seed.featureFlags.length === 0) return void 0;
1799
+ const claim = {};
1800
+ for (const flag of seed.featureFlags) {
1801
+ const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
1802
+ claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
1803
+ }
1804
+ return claim;
1805
+ }
1806
+
1807
+ // src/oauth.ts
1808
+ var import_node_crypto4 = require("crypto");
1809
+ var CODE_LIFETIME_MS = 10 * 60 * 1e3;
1810
+ var OAuthError = class extends Error {
1811
+ constructor(status, error, description) {
1812
+ super(description);
1813
+ this.status = status;
1814
+ this.error = error;
1815
+ }
1816
+ status;
1817
+ error;
1818
+ };
1819
+ var AuthorizationServer = class {
1820
+ constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
1821
+ this.testkit = testkit;
1822
+ this.seed = seed;
1823
+ this.emit = emit;
1824
+ this.directory = directory;
1825
+ this.observe = observe;
1826
+ }
1827
+ testkit;
1828
+ seed;
1829
+ emit;
1830
+ directory;
1831
+ observe;
1832
+ codes = /* @__PURE__ */ new Map();
1833
+ refreshTokens = /* @__PURE__ */ new Map();
1834
+ signedUpUsers = /* @__PURE__ */ new Map();
1835
+ async handle(req, res, url, readBody) {
1836
+ const method = req.method ?? "GET";
1837
+ switch (`${method} ${url.pathname}`) {
1838
+ case "GET /oauth2/auth":
1839
+ this.authorize(res, url.searchParams);
1840
+ return true;
1841
+ case "POST /oauth2/auth/login":
1842
+ this.login(res, await readBody());
1843
+ return true;
1844
+ case "POST /oauth2/token":
1845
+ await this.token(req, res, await readBody());
1846
+ return true;
1847
+ case "GET /oauth2/v2/user_profile":
1848
+ await this.profile(req, res);
1849
+ return true;
1850
+ case "POST /oauth2/revoke":
1851
+ this.revoke(res, await readBody());
1852
+ return true;
1853
+ case "GET /logout":
1854
+ this.logout(res, url.searchParams);
1855
+ return true;
1856
+ default:
1857
+ return false;
1858
+ }
1859
+ }
1860
+ authorize(res, params) {
1861
+ let request;
1862
+ try {
1863
+ request = parseAuthorizeRequest(params);
1864
+ } catch (error) {
1865
+ return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
1866
+ }
1867
+ if (params.get("prompt") === "none") {
1868
+ this.observe("session.silent");
1869
+ return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
1870
+ }
1871
+ sendHtml(
1872
+ res,
1873
+ 200,
1874
+ renderSignIn({
1875
+ request: encodeRequest(request),
1876
+ users: this.loginPageUsers(),
1877
+ loginHint: request.loginHint ?? void 0,
1878
+ requiredOrganization: request.orgCode ?? void 0
1879
+ })
1880
+ );
1881
+ }
1882
+ login(res, form2) {
1883
+ let request;
1884
+ try {
1885
+ request = decodeRequest(form2.request ?? "");
1886
+ } catch {
1887
+ return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
1888
+ }
1889
+ const encoded = encodeRequest(request);
1890
+ const ref = (form2.user || form2.email || "").trim();
1891
+ if (!ref) {
1892
+ 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." }));
1893
+ }
1894
+ const user = this.resolveUser(ref);
1895
+ if (!user) {
1896
+ return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
1897
+ }
1898
+ if (this.directory?.isSuspended(user.id)) {
1899
+ this.observe("identity.suspended");
1900
+ return sendHtml(
1901
+ res,
1902
+ 403,
1903
+ renderSignIn({
1904
+ request: encoded,
1905
+ users: this.loginPageUsers(),
1906
+ requiredOrganization: request.orgCode ?? void 0,
1907
+ error: `${user.email ?? user.id} is suspended and cannot sign in.`
1908
+ })
1909
+ );
1910
+ }
1911
+ const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
1912
+ const wanted = request.orgCode ?? form2.org ?? null;
1913
+ let organizationCode = null;
1914
+ if (wanted) {
1915
+ if (!memberships.some((m) => m.organizationCode === wanted)) {
1916
+ this.observe("organization.non-member");
1917
+ return sendHtml(
1918
+ res,
1919
+ 403,
1920
+ renderSignIn({
1921
+ request: encoded,
1922
+ users: this.loginPageUsers(),
1923
+ requiredOrganization: request.orgCode ?? void 0,
1924
+ error: `${user.email ?? user.id} is not a member of ${wanted}.`
1925
+ })
1926
+ );
1927
+ }
1928
+ organizationCode = wanted;
1929
+ } else if (memberships.length === 1) {
1930
+ organizationCode = memberships[0].organizationCode;
1931
+ } else if (memberships.length > 1) {
1932
+ return sendHtml(
1933
+ res,
1934
+ 200,
1935
+ renderOrganizationPicker({
1936
+ request: encoded,
1937
+ user,
1938
+ organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
1939
+ })
1940
+ );
1941
+ }
1942
+ const membership = memberships.find((m) => m.organizationCode === organizationCode);
1943
+ const scenario = {
1944
+ kind: "authenticated",
1945
+ user,
1946
+ organization: organizationCode ? this.organization(organizationCode) : null,
1947
+ roles: [...membership?.roles ?? []],
1948
+ permissions: effectivePermissions(this.seed, membership),
1949
+ claims: {}
1950
+ };
1951
+ const code = randomToken();
1952
+ this.codes.set(code, {
1953
+ clientId: request.clientId,
1954
+ redirectUri: request.redirectUri,
1955
+ scenario,
1956
+ scope: request.scope,
1957
+ audience: request.audience,
1958
+ nonce: request.nonce,
1959
+ authTime: Math.floor(Date.now() / 1e3),
1960
+ codeChallenge: request.codeChallenge,
1961
+ codeChallengeMethod: request.codeChallengeMethod,
1962
+ expiresAt: Date.now() + CODE_LIFETIME_MS
1963
+ });
1964
+ this.directory?.recordSignIn(user, organizationCode);
1965
+ this.emit("user.authenticated", user);
1966
+ const target = new URL(request.redirectUri);
1967
+ target.searchParams.set("code", code);
1968
+ if (request.state !== null) target.searchParams.set("state", request.state);
1969
+ redirect(res, target.toString());
1970
+ }
1971
+ async token(req, res, form2) {
1972
+ try {
1973
+ const clientId = clientIdFrom(req, form2);
1974
+ const grantType = form2.grant_type;
1975
+ if (grantType === "client_credentials") {
1976
+ return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
1977
+ }
1978
+ let grant;
1979
+ if (grantType === "authorization_code") {
1980
+ grant = this.redeemCode(form2, clientId);
1981
+ this.observe("session.sign-in");
1982
+ } else if (grantType === "refresh_token") {
1983
+ grant = this.redeemRefreshToken(form2, clientId);
1984
+ this.observe("session.refresh");
1985
+ } else {
1986
+ throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
1987
+ }
1988
+ sendJson(res, 200, await this.issueTokens(grant));
1989
+ } catch (error) {
1990
+ if (error instanceof OAuthError) {
1991
+ return sendJson(res, error.status, { error: error.error, error_description: error.message });
1992
+ }
1993
+ throw error;
1994
+ }
1995
+ }
1996
+ async clientCredentials(clientId, clientSecret, form2) {
1997
+ const app = this.seed.applications.find((a) => a.clientId === clientId);
1998
+ if (app?.clientSecret && app.clientSecret !== clientSecret) {
1999
+ throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
2000
+ }
2001
+ const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
2002
+ const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
2003
+ const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
2004
+ return {
2005
+ access_token: await this.testkit.m2mToken({
2006
+ clientId,
2007
+ organizationCode: app?.organizationCode ?? null,
2008
+ scopes: requested,
2009
+ grantedScopes: granted,
2010
+ audience: audience.length > 0 ? audience : app?.audience ?? void 0,
2011
+ permissions: app?.permissions ?? void 0
2012
+ }),
2013
+ expires_in: this.testkit.accessTokenLifetime,
2014
+ scope: granted.join(" "),
2015
+ token_type: "bearer"
2016
+ };
2017
+ }
2018
+ reset() {
2019
+ this.codes.clear();
2020
+ this.refreshTokens.clear();
2021
+ this.signedUpUsers.clear();
2022
+ }
2023
+ redeemCode(form2, clientId) {
2024
+ const code = form2.code ?? "";
2025
+ const pending = this.codes.get(code);
2026
+ this.codes.delete(code);
2027
+ if (!pending || pending.expiresAt < Date.now()) {
2028
+ throw new OAuthError(400, "invalid_grant", "The authorization code is unknown, expired or already used.");
2029
+ }
2030
+ if (pending.clientId !== clientId) {
2031
+ throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
2032
+ }
2033
+ if (form2.redirect_uri !== pending.redirectUri) {
2034
+ throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
2035
+ }
2036
+ if (pending.codeChallenge) {
2037
+ const verifier = form2.code_verifier ?? "";
2038
+ const expected = pending.codeChallengeMethod === "plain" ? verifier : (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
2039
+ if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
2040
+ throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
2041
+ }
2042
+ }
2043
+ return pending;
2044
+ }
2045
+ redeemRefreshToken(form2, clientId) {
2046
+ const token = form2.refresh_token ?? "";
2047
+ const grant = this.refreshTokens.get(token);
2048
+ this.refreshTokens.delete(token);
2049
+ if (!grant) {
2050
+ throw new OAuthError(400, "invalid_grant", "The refresh token is unknown, revoked or already used.");
2051
+ }
2052
+ if (grant.clientId !== clientId) {
2053
+ throw new OAuthError(400, "invalid_grant", "The refresh token was issued to a different client.");
2054
+ }
2055
+ return grant;
2056
+ }
2057
+ async issueTokens(grant) {
2058
+ const { scenario } = grant;
2059
+ const body = {
2060
+ access_token: await this.testkit.token({
2061
+ subject: scenario.user.id,
2062
+ organizationCode: scenario.organization?.code ?? null,
2063
+ roles: scenario.roles.length > 0 ? scenario.roles : void 0,
2064
+ permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
2065
+ scopes: grant.scope,
2066
+ clientId: grant.clientId,
2067
+ audience: grant.audience.length > 0 ? grant.audience : void 0,
2068
+ authTime: grant.authTime,
2069
+ featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
2070
+ }),
2071
+ expires_in: this.testkit.accessTokenLifetime,
2072
+ scope: grant.scope.join(" "),
2073
+ token_type: "bearer"
2074
+ };
2075
+ if (grant.scope.includes("openid")) {
2076
+ body.id_token = await this.testkit.idTokenFor(scenario, {
2077
+ clientId: grant.clientId,
2078
+ nonce: grant.nonce ?? void 0,
2079
+ authTime: grant.authTime
2080
+ });
2081
+ }
2082
+ if (grant.scope.includes("offline")) {
2083
+ const refreshToken = randomToken();
2084
+ this.refreshTokens.set(refreshToken, { ...grant, nonce: null });
2085
+ body.refresh_token = refreshToken;
2086
+ }
2087
+ return body;
2088
+ }
2089
+ async profile(req, res) {
2090
+ const header = req.headers.authorization ?? "";
2091
+ if (!header.startsWith("Bearer ")) {
2092
+ return sendJson(res, 401, { error: "invalid_token", error_description: "Send the access token as a Bearer token." });
2093
+ }
2094
+ let sub;
2095
+ try {
2096
+ sub = String((await this.testkit.verify(header.slice(7))).sub ?? "");
2097
+ } catch {
2098
+ return sendJson(res, 401, { error: "invalid_token", error_description: "The access token is not valid for this issuer." });
2099
+ }
2100
+ const user = this.seed.users.find((u) => u.id === sub) ?? this.signedUpUsers.get(sub);
2101
+ if (!user) {
2102
+ return sendJson(res, 404, { error: "not_found", error_description: `No user has the id ${sub}.` });
2103
+ }
2104
+ const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
2105
+ sendJson(res, 200, {
2106
+ id: user.id,
2107
+ sub: user.id,
2108
+ provided_id: null,
2109
+ name: name || null,
2110
+ given_name: user.givenName,
2111
+ family_name: user.familyName,
2112
+ updated_at: Math.floor(Date.now() / 1e3),
2113
+ email: user.email,
2114
+ email_verified: user.emailVerified,
2115
+ picture: user.picture,
2116
+ preferred_username: null,
2117
+ phone: null
2118
+ });
2119
+ }
2120
+ revoke(res, form2) {
2121
+ if (form2.token) this.refreshTokens.delete(form2.token);
2122
+ this.observe("session.revoke");
2123
+ sendJson(res, 200, {});
2124
+ }
2125
+ logout(res, params) {
2126
+ this.observe("session.sign-out");
2127
+ const target = params.get("redirect");
2128
+ if (target && isHttpUrl(target)) return redirect(res, target);
2129
+ sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
2130
+ }
2131
+ resolveUser(ref) {
2132
+ const seeded = findUser(this.seed.users, ref);
2133
+ if (seeded) return seeded;
2134
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
2135
+ const user = createKindeUser({ email: ref.toLowerCase() });
2136
+ if (!this.signedUpUsers.has(user.id)) {
2137
+ this.signedUpUsers.set(user.id, user);
2138
+ this.observe("identity.unseeded");
2139
+ if (this.directory) this.seed.users.push(user);
2140
+ this.emit("user.created", user);
2141
+ }
2142
+ return this.signedUpUsers.get(user.id);
2143
+ }
2144
+ organization(code) {
2145
+ return this.seed.organizations.find((org) => org.code === code) ?? null;
2146
+ }
2147
+ loginPageUsers() {
2148
+ return this.seed.users.map((user) => ({
2149
+ user,
2150
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
2151
+ }));
2152
+ }
2153
+ };
2154
+ function parseAuthorizeRequest(params) {
2155
+ const clientId = params.get("client_id");
2156
+ const redirectUri = params.get("redirect_uri");
2157
+ if (!clientId) throw new Error("client_id is missing.");
2158
+ if (!redirectUri || !isHttpUrl(redirectUri)) {
2159
+ throw new Error("redirect_uri must be an absolute http or https URL.");
2160
+ }
2161
+ if (params.get("response_type") !== "code") {
2162
+ throw new Error('response_type must be "code".');
2163
+ }
2164
+ const method = params.get("code_challenge_method");
2165
+ const challenge = params.get("code_challenge");
2166
+ if (challenge && method && method !== "S256" && method !== "plain") {
2167
+ throw new Error('code_challenge_method must be "S256" or "plain".');
2168
+ }
2169
+ return {
2170
+ clientId,
2171
+ redirectUri,
2172
+ state: params.get("state"),
2173
+ scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
2174
+ nonce: params.get("nonce"),
2175
+ audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
2176
+ orgCode: params.get("org_code"),
2177
+ loginHint: params.get("login_hint"),
2178
+ codeChallenge: challenge,
2179
+ codeChallengeMethod: challenge ? method ?? "plain" : null
2180
+ };
2181
+ }
2182
+ function encodeRequest(request) {
2183
+ return Buffer.from(JSON.stringify(request)).toString("base64url");
2184
+ }
2185
+ function decodeRequest(value) {
2186
+ const request = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
2187
+ if (!request.clientId || !request.redirectUri || !isHttpUrl(request.redirectUri)) {
2188
+ throw new Error("invalid request");
2189
+ }
2190
+ return request;
2191
+ }
2192
+ function clientIdFrom(req, form2) {
2193
+ const header = req.headers.authorization ?? "";
2194
+ if (header.startsWith("Basic ")) {
2195
+ const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
2196
+ const id = decodeURIComponent(decoded.split(":")[0] ?? "");
2197
+ if (id) return id;
2198
+ }
2199
+ if (form2.client_id) return form2.client_id;
2200
+ throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
2201
+ }
2202
+ function clientSecretFrom(req, form2) {
2203
+ const header = req.headers.authorization ?? "";
2204
+ if (header.startsWith("Basic ")) {
2205
+ const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
2206
+ const index = decoded.indexOf(":");
2207
+ if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
2208
+ }
2209
+ return form2.client_secret ?? null;
2210
+ }
2211
+ function redirectWithError(res, request, error, description) {
2212
+ const target = new URL(request.redirectUri);
2213
+ target.searchParams.set("error", error);
2214
+ target.searchParams.set("error_description", description);
2215
+ if (request.state !== null) target.searchParams.set("state", request.state);
2216
+ redirect(res, target.toString());
2217
+ }
2218
+ function isHttpUrl(value) {
2219
+ try {
2220
+ const { protocol } = new URL(value);
2221
+ return protocol === "http:" || protocol === "https:";
2222
+ } catch {
2223
+ return false;
2224
+ }
2225
+ }
2226
+ function randomToken() {
2227
+ return (0, import_node_crypto4.randomBytes)(32).toString("base64url");
2228
+ }
2229
+ function safeEqual(a, b) {
2230
+ const left = Buffer.from(a);
2231
+ const right = Buffer.from(b);
2232
+ return left.length === right.length && (0, import_node_crypto4.timingSafeEqual)(left, right);
2233
+ }
2234
+ function redirect(res, location) {
2235
+ res.writeHead(303, { location, "cache-control": "no-store" });
2236
+ res.end();
2237
+ }
2238
+ function sendHtml(res, status, html) {
2239
+ res.writeHead(status, {
2240
+ "content-type": "text/html; charset=utf-8",
2241
+ "cache-control": "no-store",
2242
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
2243
+ });
2244
+ res.end(html);
2245
+ }
2246
+ function sendJson(res, status, body) {
2247
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2248
+ res.end(JSON.stringify(body));
2249
+ }
2250
+
2251
+ // src/account.ts
2252
+ var DEFAULT_PAGE_SIZE = 10;
2253
+ var AccountApi = class {
2254
+ constructor(testkit, directory) {
2255
+ this.testkit = testkit;
2256
+ this.directory = directory;
2257
+ }
2258
+ testkit;
2259
+ directory;
2260
+ async handle(req, res, url) {
2261
+ if (!url.pathname.startsWith("/account_api/v1/")) return false;
2262
+ if ((req.method ?? "GET") !== "GET") {
2263
+ sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
2264
+ return true;
2265
+ }
2266
+ const header = req.headers.authorization ?? "";
2267
+ let token;
2268
+ try {
2269
+ if (!header.startsWith("Bearer ")) throw new Error("missing");
2270
+ token = await this.testkit.verify(header.slice(7));
2271
+ } catch {
2272
+ sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
2273
+ return true;
2274
+ }
2275
+ if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
2276
+ sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
2277
+ return true;
2278
+ }
2279
+ const userId = token.sub;
2280
+ const orgCode = typeof token.org_code === "string" ? token.org_code : null;
2281
+ const path = url.pathname.slice("/account_api/v1/".length);
2282
+ const d = this.directory;
2283
+ const membership = orgCode ? d.membership(userId, orgCode) : void 0;
2284
+ if (path === "permissions") {
2285
+ const items = effectivePermissions(d.seed, membership).map((key) => {
2286
+ const p = d.ensurePermission(key);
2287
+ return { id: p.id, name: p.name, key: p.key };
2288
+ });
2289
+ sendPage(res, url, "permissions", items, { org_code: orgCode });
2290
+ return true;
2291
+ }
2292
+ if (path.startsWith("permission/")) {
2293
+ const key = decodeURIComponent(path.slice("permission/".length));
2294
+ sendJson2(res, 200, {
2295
+ data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
2296
+ });
2297
+ return true;
2298
+ }
2299
+ if (path === "roles") {
2300
+ const items = (membership?.roles ?? []).map((key) => {
2301
+ const r = d.ensureRole(key);
2302
+ return { id: r.id, name: r.name, key: r.key };
2303
+ });
2304
+ sendPage(res, url, "roles", items, { org_code: orgCode });
2305
+ return true;
2306
+ }
2307
+ if (path === "feature_flags") {
2308
+ const items = d.seed.featureFlags.map((flag) => ({
2309
+ id: flag.id,
2310
+ name: flag.name,
2311
+ key: flag.key,
2312
+ type: flag.type,
2313
+ value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
2314
+ }));
2315
+ sendPage(res, url, "feature_flags", items, {});
2316
+ return true;
2317
+ }
2318
+ if (path === "properties") {
2319
+ const values = d.seed.userProperties[userId] ?? {};
2320
+ const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
2321
+ sendPage(res, url, "properties", items, {});
2322
+ return true;
2323
+ }
2324
+ if (path === "entitlements" || path.startsWith("entitlement")) {
2325
+ const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
2326
+ const entitlements = (plan?.entitlements ?? []).map((e) => ({
2327
+ id: e.id,
2328
+ fixed_charge: e.fixedCharge,
2329
+ price_name: e.priceName,
2330
+ unit_amount: e.unitAmount,
2331
+ feature_key: e.featureKey,
2332
+ feature_name: e.featureName,
2333
+ entitlement_limit_max: e.limitMax,
2334
+ entitlement_limit_min: e.limitMin
2335
+ }));
2336
+ if (path === "entitlements") {
2337
+ const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
2338
+ sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
2339
+ return true;
2340
+ }
2341
+ const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
2342
+ const entitlement = entitlements.find((e) => e.feature_key === key);
2343
+ if (!entitlement) {
2344
+ sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
2345
+ } else {
2346
+ sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
2347
+ }
2348
+ return true;
2349
+ }
2350
+ if (path === "portal_link") {
2351
+ sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
2352
+ return true;
2353
+ }
2354
+ sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
2355
+ return true;
2356
+ }
2357
+ };
2358
+ function sendPage(res, url, field, items, extra) {
2359
+ const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
2360
+ const after = url.searchParams.get("starting_after");
2361
+ const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
2362
+ const page = items.slice(start, start + size);
2363
+ const hasMore = start + size < items.length;
2364
+ sendJson2(res, 200, {
2365
+ data: { ...extra, [field]: page },
2366
+ metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
2367
+ });
2368
+ }
2369
+ function errors(code, message2) {
2370
+ return { errors: [{ code, message: message2 }] };
2371
+ }
2372
+ function sendJson2(res, status, body) {
2373
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2374
+ res.end(JSON.stringify(body));
2375
+ }
2376
+
2377
+ // src/directory.ts
2378
+ var import_node_crypto5 = require("crypto");
2379
+ var Directory = class {
2380
+ constructor(seed) {
2381
+ this.seed = seed;
2382
+ this.snapshot = JSON.stringify(seed);
2383
+ }
2384
+ seed;
2385
+ userMeta = /* @__PURE__ */ new Map();
2386
+ orgMeta = /* @__PURE__ */ new Map();
2387
+ snapshot;
2388
+ restore() {
2389
+ const original = JSON.parse(this.snapshot);
2390
+ for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
2391
+ this.seed[key].splice(0, this.seed[key].length, ...original[key]);
2392
+ }
2393
+ this.userMeta.clear();
2394
+ this.orgMeta.clear();
2395
+ }
2396
+ /** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
2397
+ load(next) {
2398
+ for (const key of Object.keys(next)) {
2399
+ const current = this.seed[key];
2400
+ if (Array.isArray(current)) {
2401
+ current.splice(0, current.length, ...next[key]);
2402
+ } else {
2403
+ const record = current;
2404
+ for (const name of Object.keys(record)) delete record[name];
2405
+ Object.assign(record, next[key]);
2406
+ }
2407
+ }
2408
+ this.snapshot = JSON.stringify(this.seed);
2409
+ this.userMeta.clear();
2410
+ this.orgMeta.clear();
2411
+ }
2412
+ user(id) {
2413
+ return this.seed.users.find((user) => user.id === id);
2414
+ }
2415
+ meta(user) {
2416
+ let meta = this.userMeta.get(user.id);
2417
+ if (!meta) {
2418
+ meta = {
2419
+ providedId: null,
2420
+ isSuspended: false,
2421
+ isPasswordResetRequested: false,
2422
+ createdOn: (/* @__PURE__ */ new Date()).toISOString(),
2423
+ totalSignIns: 0,
2424
+ lastSignedIn: null
2425
+ };
2426
+ this.userMeta.set(user.id, meta);
2427
+ }
2428
+ return meta;
2429
+ }
2430
+ isSuspended(userId) {
2431
+ return this.userMeta.get(userId)?.isSuspended ?? false;
2432
+ }
2433
+ recordSignIn(user, organizationCode) {
2434
+ const meta = this.meta(user);
2435
+ meta.totalSignIns += 1;
2436
+ meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
2437
+ void organizationCode;
2438
+ }
2439
+ createUser(input) {
2440
+ const user = createKindeUser({
2441
+ id: `kp_${(0, import_node_crypto5.randomBytes)(16).toString("hex")}`,
2442
+ email: input.email ?? null,
2443
+ givenName: input.givenName ?? null,
2444
+ familyName: input.familyName ?? null,
2445
+ picture: input.picture ?? null
2446
+ });
2447
+ this.seed.users.push(user);
2448
+ this.meta(user).providedId = input.providedId ?? null;
2449
+ return user;
2450
+ }
2451
+ deleteUser(id) {
2452
+ const index = this.seed.users.findIndex((user) => user.id === id);
2453
+ if (index < 0) return false;
2454
+ this.seed.users.splice(index, 1);
2455
+ for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
2456
+ if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
2457
+ }
2458
+ this.userMeta.delete(id);
2459
+ return true;
2460
+ }
2461
+ organization(code) {
2462
+ return this.seed.organizations.find((org) => org.code === code);
2463
+ }
2464
+ orgInfo(org) {
2465
+ let meta = this.orgMeta.get(org.code);
2466
+ if (!meta) {
2467
+ meta = {
2468
+ externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
2469
+ handle: slug(org.name),
2470
+ createdOn: (/* @__PURE__ */ new Date()).toISOString(),
2471
+ isAllowRegistrations: false
2472
+ };
2473
+ this.orgMeta.set(org.code, meta);
2474
+ }
2475
+ return meta;
2476
+ }
2477
+ createOrganization(input) {
2478
+ const org = createKindeOrganization({ code: `org_${(0, import_node_crypto5.randomBytes)(6).toString("hex").slice(0, 11)}`, name: input.name });
2479
+ this.seed.organizations.push(org);
2480
+ const meta = this.orgInfo(org);
2481
+ meta.externalId = input.externalId ?? null;
2482
+ if (input.handle) meta.handle = input.handle;
2483
+ return org;
2484
+ }
2485
+ deleteOrganization(code) {
2486
+ const index = this.seed.organizations.findIndex((org) => org.code === code);
2487
+ if (index < 0) return false;
2488
+ this.seed.organizations.splice(index, 1);
2489
+ for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
2490
+ if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
2491
+ }
2492
+ this.orgMeta.delete(code);
2493
+ return true;
2494
+ }
2495
+ membership(userId, organizationCode) {
2496
+ return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
2497
+ }
2498
+ addMembership(userId, organizationCode, roles = [], permissions = []) {
2499
+ const existing = this.membership(userId, organizationCode);
2500
+ if (existing) return existing;
2501
+ const membership = createMembership({ userId, organizationCode, roles, permissions });
2502
+ this.seed.memberships.push(membership);
2503
+ for (const key of roles) this.ensureRole(key);
2504
+ for (const key of permissions) this.ensurePermission(key);
2505
+ return membership;
2506
+ }
2507
+ removeMembership(userId, organizationCode) {
2508
+ const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
2509
+ if (index < 0) return false;
2510
+ this.seed.memberships.splice(index, 1);
2511
+ return true;
2512
+ }
2513
+ role(idOrKey) {
2514
+ return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
2515
+ }
2516
+ permission(idOrKey) {
2517
+ return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
2518
+ }
2519
+ ensureRole(key, extra = {}) {
2520
+ const existing = this.role(key);
2521
+ if (existing) return existing;
2522
+ const role = roleRecord(key, extra);
2523
+ this.seed.roles.push(role);
2524
+ return role;
2525
+ }
2526
+ ensurePermission(key, extra = {}) {
2527
+ const existing = this.permission(key);
2528
+ if (existing) return existing;
2529
+ const permission = permissionRecord(key, extra);
2530
+ this.seed.permissions.push(permission);
2531
+ return permission;
2532
+ }
2533
+ deleteRole(id) {
2534
+ const role = this.role(id);
2535
+ if (!role) return void 0;
2536
+ this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
2537
+ for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
2538
+ return role;
2539
+ }
2540
+ deletePermission(id) {
2541
+ const permission = this.permission(id);
2542
+ if (!permission) return void 0;
2543
+ this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
2544
+ for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
2545
+ for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
2546
+ return permission;
2547
+ }
2548
+ };
2549
+
2550
+ // src/management.ts
2551
+ var OK = { code: "OK", message: "Success" };
2552
+ var DEFAULT_PAGE_SIZE2 = 10;
2553
+ var MAX_PAGE_SIZE = 500;
2554
+ var ManagementApi = class {
2555
+ constructor(testkit, directory, webhooks) {
2556
+ this.testkit = testkit;
2557
+ this.directory = directory;
2558
+ this.webhooks = webhooks;
2559
+ this.register();
2560
+ }
2561
+ testkit;
2562
+ directory;
2563
+ webhooks;
2564
+ routes = [];
2565
+ async handle(req, res, url, readBody) {
2566
+ if (!url.pathname.startsWith("/api/v1/")) return false;
2567
+ const method = req.method ?? "GET";
2568
+ const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
2569
+ if (!route) {
2570
+ sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
2571
+ return true;
2572
+ }
2573
+ const token = await this.authenticate(req.headers.authorization);
2574
+ if ("error" in token) {
2575
+ sendJson3(res, 403, errors2(token.code, token.error));
2576
+ return true;
2577
+ }
2578
+ const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
2579
+ if (granted.length > 0 && !granted.includes(route.scope)) {
2580
+ sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
2581
+ return true;
2582
+ }
2583
+ const match = route.pattern.exec(url.pathname);
2584
+ const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
2585
+ const body = method === "GET" || method === "DELETE" ? {} : await readBody();
2586
+ const [status, payload] = await route.handler({ params, query: url.searchParams, body });
2587
+ sendJson3(res, status, payload);
2588
+ return true;
2589
+ }
2590
+ async authenticate(header) {
2591
+ if (!header?.startsWith("Bearer ")) {
2592
+ return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
2593
+ }
2594
+ let payload;
2595
+ try {
2596
+ payload = await this.testkit.verify(header.slice(7));
2597
+ } catch {
2598
+ return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
2599
+ }
2600
+ const audience = `${this.testkit.issuer}/api`;
2601
+ const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
2602
+ if (!aud.includes(audience)) {
2603
+ return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
2604
+ }
2605
+ if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
2606
+ return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
2607
+ }
2608
+ return { payload };
2609
+ }
2610
+ route(method, path, scope, handler) {
2611
+ const keys = [];
2612
+ const pattern = new RegExp(
2613
+ `^${path.replace(/\{(\w+)\}/g, (_, key) => {
2614
+ keys.push(key);
2615
+ return "([^/]+)";
2616
+ })}$`
2617
+ );
2618
+ this.routes.push({ method, pattern, keys, scope, handler });
2619
+ }
2620
+ register() {
2621
+ const d = this.directory;
2622
+ this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
2623
+ let users = [...d.seed.users];
2624
+ const userId = query.get("user_id");
2625
+ const email = query.get("email")?.toLowerCase();
2626
+ if (userId) users = users.filter((u) => u.id === userId);
2627
+ if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
2628
+ const page = paginate(users, query);
2629
+ return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
2630
+ });
2631
+ this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
2632
+ const user = d.user(query.get("id") ?? "");
2633
+ return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
2634
+ });
2635
+ this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
2636
+ const profile = body.profile ?? {};
2637
+ const identities = Array.isArray(body.identities) ? body.identities : [];
2638
+ const emailIdentity = identities.find((i) => i.type === "email");
2639
+ const email = (emailIdentity?.details ?? {}).email;
2640
+ if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
2641
+ return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
2642
+ }
2643
+ const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
2644
+ if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
2645
+ const user = d.createUser({
2646
+ email: typeof email === "string" ? email : null,
2647
+ givenName: str(profile.given_name),
2648
+ familyName: str(profile.family_name),
2649
+ picture: str(profile.picture),
2650
+ providedId: str(body.provided_id)
2651
+ });
2652
+ if (orgCode) d.addMembership(user.id, orgCode);
2653
+ this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
2654
+ return [
2655
+ 200,
2656
+ { id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
2657
+ ];
2658
+ });
2659
+ this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
2660
+ const user = d.user(query.get("id") ?? "");
2661
+ if (!user) return notFound("USER_INVALID", "No user has that id.");
2662
+ if (typeof body.given_name === "string") user.givenName = body.given_name;
2663
+ if (typeof body.family_name === "string") user.familyName = body.family_name;
2664
+ if (typeof body.picture === "string") user.picture = body.picture;
2665
+ const meta = d.meta(user);
2666
+ if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
2667
+ if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
2668
+ if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
2669
+ this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
2670
+ return [
2671
+ 200,
2672
+ {
2673
+ id: user.id,
2674
+ given_name: user.givenName,
2675
+ family_name: user.familyName,
2676
+ email: user.email,
2677
+ is_suspended: meta.isSuspended,
2678
+ is_password_reset_requested: meta.isPasswordResetRequested,
2679
+ picture: user.picture
2680
+ }
2681
+ ];
2682
+ });
2683
+ this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
2684
+ const id = query.get("id") ?? "";
2685
+ if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
2686
+ this.webhooks.emit("user.deleted", { user: { id } });
2687
+ return [200, OK];
2688
+ });
2689
+ this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
2690
+ const page = paginate(d.seed.organizations, query);
2691
+ return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
2692
+ });
2693
+ this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
2694
+ const org = d.organization(query.get("code") ?? "");
2695
+ if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
2696
+ const meta = d.orgInfo(org);
2697
+ return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
2698
+ });
2699
+ this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
2700
+ if (typeof body.name !== "string" || body.name.trim() === "") {
2701
+ return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
2702
+ }
2703
+ const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
2704
+ if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
2705
+ this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
2706
+ return [200, { ...OK, organization: { code: org.code } }];
2707
+ });
2708
+ this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
2709
+ const org = d.organization(params.org_code);
2710
+ if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
2711
+ const meta = d.orgInfo(org);
2712
+ if (typeof body.name === "string") org.name = body.name;
2713
+ if (typeof body.external_id === "string") meta.externalId = body.external_id;
2714
+ if (typeof body.handle === "string") meta.handle = body.handle;
2715
+ if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
2716
+ this.webhooks.emit("organization.updated", {
2717
+ organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
2718
+ });
2719
+ return [200, OK];
2720
+ });
2721
+ this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
2722
+ if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
2723
+ this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
2724
+ return [200, OK];
2725
+ });
2726
+ this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
2727
+ if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
2728
+ const members = d.seed.memberships.filter((m) => m.organizationCode === params.org_code).map((m) => ({ membership: m, user: d.user(m.userId) })).filter((m) => m.user !== void 0);
2729
+ const page = paginate(members, query);
2730
+ return [
2731
+ 200,
2732
+ {
2733
+ ...OK,
2734
+ organization_users: page.items.map(({ membership, user }) => ({
2735
+ id: user.id,
2736
+ email: user.email,
2737
+ full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
2738
+ last_name: user.familyName,
2739
+ first_name: user.givenName,
2740
+ picture: user.picture,
2741
+ joined_on: d.meta(user).createdOn,
2742
+ last_accessed_on: d.meta(user).lastSignedIn,
2743
+ is_suspended: d.meta(user).isSuspended,
2744
+ roles: [...membership.roles]
2745
+ })),
2746
+ next_token: page.nextToken
2747
+ }
2748
+ ];
2749
+ });
2750
+ this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
2751
+ if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
2752
+ const users = Array.isArray(body.users) ? body.users : [];
2753
+ const added = [];
2754
+ const blocked = [];
2755
+ for (const entry of users) {
2756
+ const id = typeof entry.id === "string" ? entry.id : "";
2757
+ if (!d.user(id)) {
2758
+ blocked.push(id);
2759
+ continue;
2760
+ }
2761
+ d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
2762
+ added.push(id);
2763
+ }
2764
+ return [200, { ...OK, users_added: added, users_blocked: blocked }];
2765
+ });
2766
+ this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
2767
+ return d.removeMembership(params.user_id, params.org_code) ? [200, OK] : notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
2768
+ });
2769
+ this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
2770
+ const membership = d.membership(params.user_id, params.org_code);
2771
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
2772
+ const roles = membership.roles.map((key) => d.ensureRole(key));
2773
+ return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
2774
+ });
2775
+ this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
2776
+ const membership = d.membership(params.user_id, params.org_code);
2777
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
2778
+ const role = d.role(str(body.role_id) ?? "");
2779
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
2780
+ if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
2781
+ return [200, OK];
2782
+ });
2783
+ this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
2784
+ const membership = d.membership(params.user_id, params.org_code);
2785
+ const role = d.role(params.role_id);
2786
+ if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
2787
+ membership.roles = membership.roles.filter((key) => key !== role.key);
2788
+ return [200, OK];
2789
+ });
2790
+ this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
2791
+ const membership = d.membership(params.user_id, params.org_code);
2792
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
2793
+ const permissions = effectivePermissions(d.seed, membership).map((key) => {
2794
+ const permission = d.ensurePermission(key);
2795
+ const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
2796
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
2797
+ });
2798
+ return [200, { ...OK, permissions }];
2799
+ });
2800
+ this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
2801
+ const membership = d.membership(params.user_id, params.org_code);
2802
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
2803
+ const permission = d.permission(str(body.permission_id) ?? "");
2804
+ if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
2805
+ if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
2806
+ return [200, OK];
2807
+ });
2808
+ this.route(
2809
+ "DELETE",
2810
+ "/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
2811
+ "delete:organization_user_permissions",
2812
+ ({ params }) => {
2813
+ const membership = d.membership(params.user_id, params.org_code);
2814
+ const permission = d.permission(params.permission_id);
2815
+ if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
2816
+ membership.permissions = membership.permissions.filter((key) => key !== permission.key);
2817
+ return [200, OK];
2818
+ }
2819
+ );
2820
+ this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
2821
+ const page = paginate(d.seed.roles, query);
2822
+ return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
2823
+ });
2824
+ this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
2825
+ const key = str(body.key);
2826
+ if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
2827
+ if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
2828
+ const role = d.ensureRole(key, {
2829
+ name: str(body.name) ?? void 0,
2830
+ description: str(body.description) ?? void 0,
2831
+ isDefault: body.is_default_role === true
2832
+ });
2833
+ this.webhooks.emit("role.created", {
2834
+ role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
2835
+ });
2836
+ return [201, { ...OK, role: { id: role.id } }];
2837
+ });
2838
+ this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
2839
+ const role = d.role(params.role_id);
2840
+ return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
2841
+ });
2842
+ this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
2843
+ const role = d.deleteRole(params.role_id);
2844
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
2845
+ this.webhooks.emit("role.deleted", { role: { id: role.id } });
2846
+ return [200, OK];
2847
+ });
2848
+ this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
2849
+ const role = d.role(params.role_id);
2850
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
2851
+ return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
2852
+ });
2853
+ this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
2854
+ const page = paginate(d.seed.permissions, query);
2855
+ return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
2856
+ });
2857
+ this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
2858
+ const key = str(body.key);
2859
+ if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
2860
+ if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
2861
+ const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
2862
+ this.webhooks.emit("permission.created", {
2863
+ permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
2864
+ });
2865
+ return [201, OK];
2866
+ });
2867
+ this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
2868
+ const permission = d.deletePermission(params.permission_id);
2869
+ if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
2870
+ this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
2871
+ return [200, OK];
2872
+ });
2873
+ }
2874
+ userListItem(user) {
2875
+ const meta = this.directory.meta(user);
2876
+ return {
2877
+ id: user.id,
2878
+ provided_id: meta.providedId,
2879
+ email: user.email,
2880
+ phone: null,
2881
+ username: null,
2882
+ last_name: user.familyName,
2883
+ first_name: user.givenName,
2884
+ is_suspended: meta.isSuspended,
2885
+ picture: user.picture,
2886
+ total_sign_ins: meta.totalSignIns,
2887
+ failed_sign_ins: 0,
2888
+ last_signed_in: meta.lastSignedIn,
2889
+ created_on: meta.createdOn,
2890
+ organizations: this.organizationsOf(user),
2891
+ identities: user.email ? [{ type: "email", identity: user.email }] : []
2892
+ };
2893
+ }
2894
+ userDetail(user) {
2895
+ const { email, ...rest } = this.userListItem(user);
2896
+ return { ...rest, preferred_email: email };
2897
+ }
2898
+ organizationsOf(user) {
2899
+ return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
2900
+ }
2901
+ organizationItem(org) {
2902
+ const meta = this.directory.orgInfo(org);
2903
+ return {
2904
+ code: org.code,
2905
+ name: org.name,
2906
+ handle: meta.handle,
2907
+ is_default: false,
2908
+ external_id: meta.externalId,
2909
+ is_auto_membership_enabled: false
2910
+ };
2911
+ }
2912
+ organizationEvent(org) {
2913
+ const meta = this.directory.orgInfo(org);
2914
+ return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
2915
+ }
2916
+ roleItem(role) {
2917
+ return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
2918
+ }
2919
+ permissionItem(permission) {
2920
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
2921
+ }
2922
+ };
2923
+ function paginate(items, query) {
2924
+ const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
2925
+ const token = query.get("next_token");
2926
+ const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
2927
+ const page = items.slice(offset, offset + size);
2928
+ const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
2929
+ return { items: page, nextToken: next };
2930
+ }
2931
+ function errors2(code, message2) {
2932
+ return { errors: [{ code, message: message2 }] };
2933
+ }
2934
+ function notFound(code, message2) {
2935
+ return [404, errors2(code, message2)];
2936
+ }
2937
+ function str(value) {
2938
+ return typeof value === "string" ? value : null;
2939
+ }
2940
+ function strings(value) {
2941
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
2942
+ }
2943
+ function sendJson3(res, status, body) {
2944
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2945
+ res.end(JSON.stringify(body));
2946
+ }
2947
+
2948
+ // src/failures.ts
2949
+ var MAX_DELAY_MS = 6e4;
2950
+ var FailureInjector = class {
2951
+ rules = [];
2952
+ nextId = 1;
2953
+ add(rule) {
2954
+ const problems = validate(rule);
2955
+ if (problems.length > 0) {
2956
+ throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
2957
+ }
2958
+ const active = {
2959
+ id: `failure_${this.nextId++}`,
2960
+ path: rule.path,
2961
+ method: rule.method ? rule.method.toUpperCase() : null,
2962
+ status: rule.status ?? null,
2963
+ delayMs: rule.delayMs ?? 0,
2964
+ hang: rule.hang ?? false,
2965
+ remaining: rule.times ?? null,
2966
+ retryAfter: rule.retryAfter ?? 1,
2967
+ hits: 0
2968
+ };
2969
+ this.rules.push(active);
2970
+ return { ...active };
2971
+ }
2972
+ remove(id) {
2973
+ const before = this.rules.length;
2974
+ this.rules = this.rules.filter((rule) => rule.id !== id);
2975
+ return this.rules.length < before;
2976
+ }
2977
+ clear() {
2978
+ this.rules = [];
2979
+ }
2980
+ list() {
2981
+ return this.rules.map((rule) => ({ ...rule }));
2982
+ }
2983
+ take(method, path) {
2984
+ const rule = this.rules.find((r) => matches(r, method, path));
2985
+ if (!rule) return null;
2986
+ rule.hits += 1;
2987
+ if (rule.remaining !== null) {
2988
+ rule.remaining -= 1;
2989
+ if (rule.remaining <= 0) this.remove(rule.id);
2990
+ }
2991
+ return { ...rule };
2992
+ }
2993
+ };
2994
+ function failureBody(status) {
2995
+ const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
2996
+ return { error, error_description: `kinde-testkit injected a ${status} response.` };
2997
+ }
2998
+ function matches(rule, method, path) {
2999
+ if (rule.method && rule.method !== method.toUpperCase()) return false;
3000
+ if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
3001
+ return rule.path === path;
3002
+ }
3003
+ function validate(rule) {
3004
+ const problems = [];
3005
+ if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
3006
+ problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
3007
+ } else if (rule.path.startsWith("/testkit/")) {
3008
+ problems.push("Failures cannot target /testkit/ control endpoints.");
3009
+ }
3010
+ if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
3011
+ problems.push('"status" must be an HTTP error status between 400 and 599.');
3012
+ }
3013
+ if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
3014
+ problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
3015
+ }
3016
+ if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
3017
+ problems.push('"times" must be a whole number of 1 or more.');
3018
+ }
3019
+ if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
3020
+ problems.push('"retryAfter" must be a whole number of seconds.');
3021
+ }
3022
+ if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
3023
+ problems.push('Set at least one of "status", "delayMs" or "hang".');
3024
+ }
3025
+ return problems;
3026
+ }
3027
+
3028
+ // src/webhooks.ts
3029
+ var import_node_crypto6 = require("crypto");
3030
+ var WEBHOOK_EVENT_TYPES = [
3031
+ "user.created",
3032
+ "user.updated",
3033
+ "user.deleted",
3034
+ "user.authenticated",
3035
+ "user.authentication_failed",
3036
+ "organization.created",
3037
+ "organization.updated",
3038
+ "organization.deleted",
3039
+ "role.created",
3040
+ "role.updated",
3041
+ "role.deleted",
3042
+ "permission.created",
3043
+ "permission.updated",
3044
+ "permission.deleted",
3045
+ "subscriber.created",
3046
+ "access_request.created"
3047
+ ];
3048
+ var BILLING_EVENT_TYPES = [
3049
+ "customer.agreement_cancelled",
3050
+ "customer.agreement_created",
3051
+ "customer.invoice_overdue",
3052
+ "customer.meter_usage_updated",
3053
+ "customer.payment_failed",
3054
+ "customer.payment_succeeded",
3055
+ "customer.plan_assigned",
3056
+ "customer.plan_changed"
3057
+ ];
3058
+ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
3059
+ var DEFAULT_TIMEOUT_MS = 5e3;
3060
+ var MAX_DUPLICATES = 10;
3061
+ var WebhookDispatcher = class {
3062
+ constructor(testkit, seed, endpoints = [], options = {}) {
3063
+ this.testkit = testkit;
3064
+ this.seed = seed;
3065
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
3066
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
3067
+ for (const endpoint of endpoints) this.addEndpoint(endpoint);
3068
+ this.seededEndpoints = [...this.endpoints];
3069
+ }
3070
+ testkit;
3071
+ seed;
3072
+ endpoints = [];
3073
+ seededEndpoints = [];
3074
+ log = [];
3075
+ nextEndpoint = 1;
3076
+ retryDelaysMs;
3077
+ timeoutMs;
3078
+ /** Set by the server to record coverage. */
3079
+ observe = () => void 0;
3080
+ addEndpoint(input) {
3081
+ if (!isHttpUrl2(input.url)) {
3082
+ throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
3083
+ }
3084
+ if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
3085
+ throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
3086
+ }
3087
+ const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
3088
+ this.endpoints.push(endpoint);
3089
+ return { ...endpoint };
3090
+ }
3091
+ /** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
3092
+ replaceSeededEndpoints(endpoints) {
3093
+ const seeded = new Set(this.seededEndpoints.map((e) => e.id));
3094
+ this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
3095
+ const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
3096
+ const ids = new Set(added.map((e) => e.id));
3097
+ this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
3098
+ }
3099
+ removeEndpoint(id) {
3100
+ const before = this.endpoints.length;
3101
+ this.endpoints = this.endpoints.filter((e) => e.id !== id);
3102
+ return this.endpoints.length < before;
3103
+ }
3104
+ listEndpoints() {
3105
+ return this.endpoints.map((e) => ({ ...e }));
3106
+ }
3107
+ deliveries() {
3108
+ return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
3109
+ }
3110
+ reset() {
3111
+ this.log = [];
3112
+ this.endpoints = [...this.seededEndpoints];
3113
+ }
3114
+ buildEvent(options) {
3115
+ if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
3116
+ throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
3117
+ }
3118
+ const now = /* @__PURE__ */ new Date();
3119
+ const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
3120
+ const event = {
3121
+ data: options.data ?? this.buildData(options),
3122
+ event_id: `event_${(0, import_node_crypto6.randomBytes)(16).toString("hex")}`,
3123
+ event_timestamp: timestamp,
3124
+ source: options.source ?? "admin",
3125
+ timestamp,
3126
+ type: options.type
3127
+ };
3128
+ if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
3129
+ event.ip_address = options.ipAddress ?? "127.0.0.1";
3130
+ }
3131
+ return event;
3132
+ }
3133
+ async send(options) {
3134
+ const event = this.buildEvent(options);
3135
+ const copies = options.duplicate ?? 1;
3136
+ if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
3137
+ throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
3138
+ }
3139
+ const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
3140
+ if (options.to && !isHttpUrl2(options.to)) {
3141
+ throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
3142
+ }
3143
+ if (targets.length === 0) {
3144
+ throw new TestkitError(
3145
+ "INVALID_REQUEST",
3146
+ `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
3147
+ );
3148
+ }
3149
+ if (copies > 1) this.observe("webhook.duplicate");
3150
+ if (options.invalid === "stale") this.observe("webhook.stale");
3151
+ else if (options.invalid) this.observe("webhook.forged");
3152
+ if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
3153
+ const signed = await this.testkit.signPayload(
3154
+ event,
3155
+ options.invalid === "stale" ? void 0 : options.invalid
3156
+ );
3157
+ const jobs = targets.flatMap((target) => {
3158
+ const webhookId = `wh_${(0, import_node_crypto6.randomBytes)(12).toString("hex")}`;
3159
+ return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
3160
+ });
3161
+ const deliveries = await Promise.all(jobs);
3162
+ if (!options.invalid) {
3163
+ for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
3164
+ }
3165
+ return deliveries;
3166
+ }
3167
+ async deliver(url, webhookId, body, event, copy) {
3168
+ const delivery = {
3169
+ webhookId,
3170
+ eventId: String(event.event_id),
3171
+ type: String(event.type),
3172
+ url,
3173
+ copy,
3174
+ delivered: false,
3175
+ attempts: [],
3176
+ payload: event
3177
+ };
3178
+ this.log.push(delivery);
3179
+ for (const [index, delay] of this.retryDelaysMs.entries()) {
3180
+ if (delay > 0) await sleep(delay);
3181
+ const started = Date.now();
3182
+ try {
3183
+ const response = await fetch(url, {
3184
+ method: "POST",
3185
+ headers: { "content-type": "application/jwt", "webhook-id": webhookId },
3186
+ body,
3187
+ signal: AbortSignal.timeout(this.timeoutMs)
3188
+ });
3189
+ await response.arrayBuffer().catch(() => void 0);
3190
+ delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
3191
+ if (response.status === 200) {
3192
+ delivery.delivered = true;
3193
+ break;
3194
+ }
3195
+ } catch (error) {
3196
+ const name = error.name;
3197
+ delivery.attempts.push({
3198
+ attempt: index + 1,
3199
+ status: null,
3200
+ error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
3201
+ durationMs: Date.now() - started
3202
+ });
3203
+ }
3204
+ }
3205
+ return { ...delivery, attempts: [...delivery.attempts] };
3206
+ }
3207
+ buildData(options) {
3208
+ const [subject] = options.type.split(".");
3209
+ switch (subject) {
3210
+ case "user":
3211
+ return { user: this.userData(options) };
3212
+ case "organization":
3213
+ return { organization: this.organizationData(options) };
3214
+ case "role":
3215
+ return { role: this.namedData(options, "role") };
3216
+ case "permission":
3217
+ return { permission: this.namedData(options, "permission") };
3218
+ case "subscriber": {
3219
+ const user = this.requireUser(options);
3220
+ return {
3221
+ subscriber: {
3222
+ email: user.email,
3223
+ first_name: user.givenName,
3224
+ id: stableId("sub", user.id),
3225
+ last_name: user.familyName,
3226
+ user_id: user.id
3227
+ }
3228
+ };
3229
+ }
3230
+ case "access_request": {
3231
+ const user = this.requireUser(options);
3232
+ return {
3233
+ access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
3234
+ };
3235
+ }
3236
+ default:
3237
+ throw new TestkitError(
3238
+ "INVALID_REQUEST",
3239
+ `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
3240
+ );
3241
+ }
3242
+ }
3243
+ emit(type, data, source = "api") {
3244
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
3245
+ void this.send({ type, data, source }).catch(() => void 0);
3246
+ }
3247
+ userEventData(user) {
3248
+ return this.userPayload(user);
3249
+ }
3250
+ emitForUser(type, user) {
3251
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
3252
+ const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
3253
+ void this.send({ type, data, source: "user" }).catch(() => void 0);
3254
+ }
3255
+ userData(options) {
3256
+ const user = this.requireUser(options);
3257
+ if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
3258
+ return this.userPayload(user);
3259
+ }
3260
+ userPayload(user) {
3261
+ return {
3262
+ email: user.email,
3263
+ first_name: user.givenName,
3264
+ id: user.id,
3265
+ is_password_reset_requested: false,
3266
+ is_suspended: false,
3267
+ last_name: user.familyName,
3268
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
3269
+ code: m.organizationCode,
3270
+ permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
3271
+ roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
3272
+ })),
3273
+ phone: null,
3274
+ username: typeof user.claims.username === "string" ? user.claims.username : null
3275
+ };
3276
+ }
3277
+ organizationData(options) {
3278
+ if (!options.organization) {
3279
+ throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
3280
+ }
3281
+ const org = this.seed.organizations.find((o) => o.code === options.organization);
3282
+ if (options.type === "organization.deleted") return { code: options.organization };
3283
+ const name = org?.name ?? titleCase(options.organization);
3284
+ const data = { code: options.organization, external_id: null, handle: slug(name), name };
3285
+ if (options.type === "organization.updated") data.is_allow_registrations = false;
3286
+ return data;
3287
+ }
3288
+ namedData(options, kind) {
3289
+ const key = kind === "role" ? options.role : options.permission;
3290
+ if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
3291
+ const id = stableId(kind === "role" ? "role" : "perm", key);
3292
+ if (options.type.endsWith(".deleted")) return { id };
3293
+ const data = { description: "", id, key, name: titleCase(key) };
3294
+ if (kind === "role") data.is_default_role = false;
3295
+ return data;
3296
+ }
3297
+ requireUser(options) {
3298
+ if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
3299
+ const user = findUser(this.seed.users, options.user);
3300
+ if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
3301
+ return user;
3302
+ }
3303
+ };
3304
+ function isHttpUrl2(value) {
3305
+ if (typeof value !== "string") return false;
3306
+ try {
3307
+ const { protocol } = new URL(value);
3308
+ return protocol === "http:" || protocol === "https:";
3309
+ } catch {
3310
+ return false;
3311
+ }
3312
+ }
3313
+ function sleep(ms) {
3314
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
3315
+ }
3316
+
3317
+ // src/activity.ts
3318
+ var LIMIT = 200;
3319
+ var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
3320
+ var ActivityLog = class {
3321
+ requestLog = [];
3322
+ tokenLog = [];
3323
+ request(entry) {
3324
+ const query = new URLSearchParams(entry.query);
3325
+ for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
3326
+ const search = query.toString();
3327
+ push(this.requestLog, {
3328
+ at: (/* @__PURE__ */ new Date()).toISOString(),
3329
+ method: entry.method,
3330
+ path: search ? `${entry.path}?${search}` : entry.path,
3331
+ status: entry.status,
3332
+ durationMs: entry.durationMs,
3333
+ injected: entry.injected
3334
+ });
3335
+ }
3336
+ token(kind, claims, invalid3, token) {
3337
+ const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
3338
+ push(this.tokenLog, {
3339
+ at: (/* @__PURE__ */ new Date()).toISOString(),
3340
+ kind,
3341
+ subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
3342
+ organization: typeof claims.org_code === "string" ? claims.org_code : null,
3343
+ permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
3344
+ roles,
3345
+ invalid: invalid3 ?? null,
3346
+ expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
3347
+ claims,
3348
+ token
3349
+ });
3350
+ }
3351
+ requests() {
3352
+ return [...this.requestLog];
3353
+ }
3354
+ tokens() {
3355
+ return [...this.tokenLog];
3356
+ }
3357
+ reset() {
3358
+ this.requestLog = [];
3359
+ this.tokenLog = [];
3360
+ }
3361
+ };
3362
+ function push(list, entry) {
3363
+ list.push(entry);
3364
+ if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
3365
+ }
3366
+
3367
+ // src/coverage.ts
3368
+ var import_node_fs2 = require("fs");
3369
+ var import_node_path2 = require("path");
3370
+ var COVERAGE_GROUPS = [
3371
+ {
3372
+ name: "Identity",
3373
+ items: [
3374
+ { id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
3375
+ { id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
3376
+ { id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
3377
+ { id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
3378
+ { id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
3379
+ { id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
3380
+ ]
3381
+ },
3382
+ {
3383
+ name: "Organizations",
3384
+ items: [
3385
+ { id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
3386
+ { id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
3387
+ { id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
3388
+ { 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." },
3389
+ { id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
3390
+ ]
3391
+ },
3392
+ {
3393
+ name: "Permissions",
3394
+ items: [
3395
+ { id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
3396
+ { 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." },
3397
+ { id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
3398
+ { id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
3399
+ { id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
3400
+ ]
3401
+ },
3402
+ {
3403
+ name: "Token validation",
3404
+ items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
3405
+ (kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
3406
+ )
3407
+ },
3408
+ {
3409
+ name: "Sessions",
3410
+ items: [
3411
+ { id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
3412
+ { id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
3413
+ { id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
3414
+ { id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
3415
+ { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
3416
+ ]
3417
+ },
3418
+ {
3419
+ name: "Machine-to-machine",
3420
+ items: [
3421
+ { id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
3422
+ { id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
3423
+ { id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
3424
+ { id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
3425
+ ]
3426
+ },
3427
+ {
3428
+ name: "Kinde APIs",
3429
+ items: [
3430
+ { id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
3431
+ { id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
3432
+ { id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
3433
+ { id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
3434
+ ]
3435
+ },
3436
+ {
3437
+ name: "Webhooks",
3438
+ items: [
3439
+ { id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
3440
+ { id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
3441
+ { id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
3442
+ { id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
3443
+ { id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
3444
+ ]
3445
+ },
3446
+ {
3447
+ name: "Outages",
3448
+ items: [
3449
+ { id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
3450
+ { id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
3451
+ { id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
3452
+ { id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
3453
+ ]
3454
+ }
3455
+ ];
3456
+ var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
3457
+ function tokenLabel(kind) {
3458
+ return {
3459
+ expired: "Expired token",
3460
+ "future-iat": "Token issued in the future",
3461
+ "wrong-issuer": "Wrong issuer",
3462
+ "wrong-audience": "Wrong audience",
3463
+ "bad-signature": "Tampered signature",
3464
+ "unknown-key": "Unknown signing key",
3465
+ unsigned: "Unsigned token",
3466
+ "missing-subject": "No subject"
3467
+ }[kind];
3468
+ }
3469
+ var CoverageRecorder = class {
3470
+ hits = /* @__PURE__ */ new Map();
3471
+ userOrganizations = /* @__PURE__ */ new Map();
3472
+ organizationUsers = /* @__PURE__ */ new Map();
3473
+ organizationPermissionSets = /* @__PURE__ */ new Map();
3474
+ hit(id) {
3475
+ if (!ALL_IDS.has(id)) return;
3476
+ this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
3477
+ }
3478
+ /** Called for every access token the testkit signs. */
3479
+ observeAccessToken(payload, invalid3) {
3480
+ if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
3481
+ this.hit("m2m.token");
3482
+ if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
3483
+ if (typeof payload.org_code === "string") this.hit("m2m.organization");
3484
+ if (invalid3) this.hit("m2m.invalid");
3485
+ return;
3486
+ }
3487
+ if (invalid3 === "missing-organization") return this.hit("organization.missing");
3488
+ if (invalid3 === "missing-permissions") return this.hit("permission.none");
3489
+ if (invalid3) return this.hit(`token.${invalid3}`);
3490
+ const subject = typeof payload.sub === "string" ? payload.sub : null;
3491
+ const organization = typeof payload.org_code === "string" ? payload.org_code : null;
3492
+ const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
3493
+ if (subject) this.hit("identity.user");
3494
+ if (!organization) this.hit("identity.no-organization");
3495
+ if (permissions.length > 0) this.hit("permission.granted");
3496
+ else this.hit("permission.none");
3497
+ if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
3498
+ if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
3499
+ if (!organization) return;
3500
+ this.hit("organization.token");
3501
+ if (subject) {
3502
+ const organizations = add(this.userOrganizations, subject, organization);
3503
+ if (organizations.size > 1) this.hit("organization.two-for-one-user");
3504
+ add(this.organizationUsers, organization, subject);
3505
+ const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
3506
+ const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
3507
+ if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
3508
+ }
3509
+ const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
3510
+ if (sets.size > 1) this.hit("permission.different-sets");
3511
+ }
3512
+ report() {
3513
+ return buildReport(Object.fromEntries(this.hits));
3514
+ }
3515
+ snapshot() {
3516
+ return { version: 1, hits: Object.fromEntries(this.hits) };
3517
+ }
3518
+ reset() {
3519
+ this.hits.clear();
3520
+ this.userOrganizations.clear();
3521
+ this.organizationUsers.clear();
3522
+ this.organizationPermissionSets.clear();
3523
+ }
3524
+ /** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
3525
+ write(directory = DEFAULT_COVERAGE_DIRECTORY) {
3526
+ const folder = (0, import_node_path2.resolve)(directory);
3527
+ (0, import_node_fs2.mkdirSync)(folder, { recursive: true });
3528
+ const file = (0, import_node_path2.join)(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
3529
+ (0, import_node_fs2.writeFileSync)(file, `${JSON.stringify(this.snapshot())}
3530
+ `);
3531
+ return file;
3532
+ }
3533
+ };
3534
+ var DEFAULT_COVERAGE_DIRECTORY = (0, import_node_path2.join)(".kinde-testkit", "coverage");
3535
+ function add(map, key, value) {
3536
+ let set2 = map.get(key);
3537
+ if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
3538
+ set2.add(value);
3539
+ return set2;
3540
+ }
3541
+ function buildReport(hits) {
3542
+ const groups = COVERAGE_GROUPS.map((group) => {
3543
+ const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
3544
+ return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
3545
+ });
3546
+ return {
3547
+ covered: groups.reduce((sum, g) => sum + g.covered, 0),
3548
+ total: groups.reduce((sum, g) => sum + g.total, 0),
3549
+ groups
3550
+ };
3551
+ }
3552
+
3553
+ // src/dashboard.ts
3554
+ var STYLE2 = `
3555
+ :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}
3556
+ @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}}
3557
+ *{box-sizing:border-box}
3558
+ body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
3559
+ 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)}
3560
+ header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
3561
+ header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
3562
+ nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
3563
+ nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
3564
+ main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
3565
+ section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
3566
+ h2{margin:0 0 4px;font-size:16px;font-weight:600}
3567
+ .sub{margin:0 0 14px;color:var(--muted);font-size:13px}
3568
+ table{width:100%;border-collapse:collapse;font-size:13px}
3569
+ th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
3570
+ td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
3571
+ tr:last-child td{border-bottom:0}
3572
+ code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
3573
+ .chips{display:flex;flex-wrap:wrap;gap:4px}
3574
+ .chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
3575
+ .ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
3576
+ .empty{color:var(--muted);font-size:13px;margin:0}
3577
+ .row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
3578
+ label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
3579
+ 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}
3580
+ input[type=checkbox]{height:auto}
3581
+ 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}
3582
+ button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
3583
+ button:hover{border-color:var(--muted)}
3584
+ details summary{cursor:pointer;color:var(--muted)}
3585
+ 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}
3586
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
3587
+ .group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
3588
+ .group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
3589
+ .notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
3590
+ .split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
3591
+ `;
3592
+ function renderDashboard(data) {
3593
+ const e = escapeHtml;
3594
+ const { seed } = data;
3595
+ const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
3596
+ const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
3597
+ const users = seed.users.length ? table2(
3598
+ ["User", "ID", "Organizations", "Sign-ins", "Status"],
3599
+ seed.users.map((user) => [
3600
+ e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
3601
+ `<code>${e(user.id)}</code>`,
3602
+ chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
3603
+ String(data.signIns(user.id)),
3604
+ data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
3605
+ ])
3606
+ ) : empty("No users yet. Seed some, or sign in with any email.");
3607
+ const organizations = seed.organizations.length ? table2(
3608
+ ["Organization", "Code", "Members"],
3609
+ seed.organizations.map((org) => [
3610
+ e(org.name),
3611
+ `<code>${e(org.code)}</code>`,
3612
+ String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
3613
+ ])
3614
+ ) : empty("No organizations.");
3615
+ const memberships = seed.memberships.length ? table2(
3616
+ ["User", "Organization", "Roles", "Permissions in the token"],
3617
+ seed.memberships.map((m) => [
3618
+ e(userLabel(m.userId)),
3619
+ e(orgName(m.organizationCode)),
3620
+ chips(m.roles),
3621
+ chips(effectivePermissions(seed, m))
3622
+ ])
3623
+ ) : empty("No memberships.");
3624
+ const applications = seed.applications.length ? table2(
3625
+ ["Client ID", "Organization", "Scopes"],
3626
+ seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
3627
+ ) : "";
3628
+ const tokens = data.tokens.length ? table2(
3629
+ ["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
3630
+ [...data.tokens].reverse().slice(0, 50).map((t) => [
3631
+ time(t.at),
3632
+ t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
3633
+ `<code>${e(t.subject ?? "none")}</code>`,
3634
+ e(t.organization ?? "none"),
3635
+ chips(t.permissions),
3636
+ `<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
3637
+ ])
3638
+ ) : empty("No tokens issued yet.");
3639
+ const requests = data.requests.length ? table2(
3640
+ ["Time", "Request", "Status", "Time taken"],
3641
+ [...data.requests].reverse().slice(0, 100).map((r) => [
3642
+ time(r.at),
3643
+ `<code>${e(r.method)} ${e(r.path)}</code>`,
3644
+ `<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
3645
+ `${r.durationMs} ms`
3646
+ ])
3647
+ ) : empty("No requests yet.");
3648
+ const deliveries = data.deliveries.length ? table2(
3649
+ ["Event", "Endpoint", "Copy", "Result"],
3650
+ [...data.deliveries].reverse().slice(0, 50).map((d) => [
3651
+ `<code>${e(d.type)}</code>`,
3652
+ `<code>${e(d.url)}</code>`,
3653
+ String(d.copy),
3654
+ 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>`
3655
+ ])
3656
+ ) : empty("No webhooks sent yet.");
3657
+ 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>`;
3658
+ const webhookForm = data.endpoints.length ? form(
3659
+ "/dashboard/webhooks",
3660
+ `<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
3661
+ <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>
3662
+ <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>
3663
+ <label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
3664
+ <button class="primary">Send</button>`
3665
+ ) : "";
3666
+ const failures = data.failures.length ? table2(
3667
+ ["Path", "Method", "Effect", "Remaining", "Hits", ""],
3668
+ data.failures.map((f) => [
3669
+ `<code>${e(f.path)}</code>`,
3670
+ e(f.method ?? "any"),
3671
+ e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
3672
+ f.remaining === null ? "Until removed" : String(f.remaining),
3673
+ String(f.hits),
3674
+ form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
3675
+ ])
3676
+ ) : empty("No failure rules.");
3677
+ const coverage = `<div class="grid">${data.coverage.groups.map(
3678
+ (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>`
3679
+ ).join("")}</div>`;
3680
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
3681
+ ${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
3682
+ <title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
3683
+ <header>
3684
+ <div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
3685
+ <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>
3686
+ <div class="row">
3687
+ <a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
3688
+ ${form("/dashboard/reset", `<button>Reset state</button>`)}
3689
+ </div>
3690
+ </header>
3691
+ <main>
3692
+ ${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
3693
+ <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>
3694
+ <div class="split">
3695
+ <section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
3696
+ <section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
3697
+ </div>
3698
+ ${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
3699
+ <section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
3700
+ <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>
3701
+ <section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
3702
+ <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>
3703
+ ${form(
3704
+ "/dashboard/failures",
3705
+ `<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
3706
+ <label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
3707
+ <label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
3708
+ <label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
3709
+ <label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
3710
+ <label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
3711
+ <button class="primary">Add rule</button>`
3712
+ )}
3713
+ <div style="margin-top:14px">${failures}</div>
3714
+ ${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
3715
+ </section>
3716
+ <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}
3717
+ <div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
3718
+ </main></body></html>`;
3719
+ }
3720
+ function table2(headers, rows) {
3721
+ 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>`;
3722
+ }
3723
+ function chips(values) {
3724
+ if (values.length === 0) return `<span class="muted">none</span>`;
3725
+ return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
3726
+ }
3727
+ function empty(text) {
3728
+ return `<p class="empty">${escapeHtml(text)}</p>`;
3729
+ }
3730
+ function time(iso) {
3731
+ return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
3732
+ }
3733
+ function form(action, body) {
3734
+ return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
3735
+ }
3736
+
3737
+ // src/seed-file.ts
3738
+ var import_node_fs3 = require("fs");
3739
+ var import_node_path3 = require("path");
3740
+ var import_node_url = require("url");
3741
+ var import_yaml = require("yaml");
3742
+ async function loadSeedFile(path) {
3743
+ const file = (0, import_node_path3.resolve)(path);
3744
+ const extension = (0, import_node_path3.extname)(file).toLowerCase();
3745
+ let value;
3746
+ try {
3747
+ if (extension === ".yaml" || extension === ".yml") {
3748
+ value = (0, import_yaml.parse)((0, import_node_fs3.readFileSync)(file, "utf8"));
3749
+ } else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
3750
+ const module2 = await import((0, import_node_url.pathToFileURL)(file).href);
3751
+ value = module2.seed ?? module2.default;
3752
+ if (value && typeof value === "object" && "default" in value && !("users" in value)) {
3753
+ value = value.default;
3754
+ }
3755
+ } else {
3756
+ value = JSON.parse((0, import_node_fs3.readFileSync)(file, "utf8"));
3757
+ }
3758
+ } catch (error) {
3759
+ const message2 = error instanceof Error ? error.message : String(error);
3760
+ const details = [message2];
3761
+ if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message2)) {
3762
+ details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
3763
+ }
3764
+ throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
3765
+ }
3766
+ if (value === null || value === void 0) value = {};
3767
+ if (typeof value !== "object" || Array.isArray(value)) {
3768
+ throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
3769
+ }
3770
+ return value;
3771
+ }
3772
+
3773
+ // src/server.ts
3774
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
3775
+ var MAX_BODY_BYTES = 64 * 1024;
3776
+ var JWKS_PATHS = /* @__PURE__ */ new Set(["/.well-known/jwks", "/.well-known/jwks.json"]);
3777
+ async function startKindeTestkit(options = {}) {
3778
+ const host = options.host ?? "127.0.0.1";
3779
+ if (!LOOPBACK_HOSTS.has(host) && !options.allowPublic) {
3780
+ throw new TestkitError(
3781
+ "PUBLIC_BIND_REFUSED",
3782
+ `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).`
3783
+ );
3784
+ }
3785
+ const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
3786
+ const seed = resolveSeed(seedInput);
3787
+ const failures = new FailureInjector();
3788
+ let ready;
3789
+ const testkitReady = new Promise((resolve4) => ready = resolve4);
3790
+ const listener = (req, res) => {
3791
+ testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
3792
+ };
3793
+ const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
3794
+ const server = certificate ? (0, import_node_https.createServer)({ cert: certificate.cert, key: certificate.key }, listener) : (0, import_node_http.createServer)(listener);
3795
+ await new Promise((resolve4, reject) => {
3796
+ server.once("error", reject);
3797
+ server.listen(options.port ?? 4400, host, () => resolve4());
3798
+ });
3799
+ const { port } = server.address();
3800
+ const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
3801
+ const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
3802
+ const testkit = await KindeTestkit.create({
3803
+ issuer: options.issuer ?? seedInput.issuer ?? url,
3804
+ audience: options.audience ?? seedInput.audience,
3805
+ clientId: options.clientId ?? seedInput.clientId
3806
+ });
3807
+ const coverage = new CoverageRecorder();
3808
+ const activity = new ActivityLog();
3809
+ testkit.observe({
3810
+ accessToken(payload, invalid3, token) {
3811
+ coverage.observeAccessToken(payload, invalid3);
3812
+ const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
3813
+ activity.token(m2m ? "m2m" : "access", payload, invalid3, token);
3814
+ },
3815
+ idToken(payload, token) {
3816
+ coverage.hit("identity.id-token");
3817
+ activity.token("id", payload, void 0, token);
3818
+ },
3819
+ anonymous() {
3820
+ coverage.hit("identity.anonymous");
3821
+ }
3822
+ });
3823
+ const observe = (id) => coverage.hit(id);
3824
+ const directory = new Directory(seed);
3825
+ const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
3826
+ webhooks.observe = observe;
3827
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
3828
+ const management = new ManagementApi(testkit, directory, webhooks);
3829
+ const account = new AccountApi(testkit, directory);
3830
+ const reset = () => {
3831
+ auth.reset();
3832
+ failures.clear();
3833
+ webhooks.reset();
3834
+ directory.restore();
3835
+ };
3836
+ const loadSeed = (input) => {
3837
+ const next = resolveSeed(input);
3838
+ directory.load(next);
3839
+ webhooks.replaceSeededEndpoints(next.webhooks);
3840
+ reset();
3841
+ };
3842
+ let closed = false;
3843
+ const close = () => new Promise((resolve4, reject) => {
3844
+ if (closed) return resolve4();
3845
+ closed = true;
3846
+ if (options.coverage) {
3847
+ coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
3848
+ }
3849
+ server.closeAllConnections();
3850
+ server.close((error) => error ? reject(error) : resolve4());
3851
+ });
3852
+ ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
3853
+ return {
3854
+ url,
3855
+ issuer: testkit.issuer,
3856
+ discoveryUrl: `${url}/.well-known/openid-configuration`,
3857
+ jwksUri: `${url}/.well-known/jwks`,
3858
+ testkit,
3859
+ seed,
3860
+ failures,
3861
+ webhooks,
3862
+ directory,
3863
+ certificatePath: certificate?.certPath ?? null,
3864
+ coverage,
3865
+ activity,
3866
+ loadSeed,
3867
+ reset,
3868
+ close
3869
+ };
3870
+ }
3871
+ async function handle(req, res, context) {
3872
+ const { testkit, auth, seed, failures, webhooks, coverage } = context;
3873
+ const url = new URL(req.url ?? "/", "http://localhost");
3874
+ const { pathname } = url;
3875
+ const method = req.method ?? "GET";
3876
+ const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
3877
+ let injected = false;
3878
+ if (!internal && pathname !== "/favicon.ico") {
3879
+ const started = Date.now();
3880
+ res.once("close", () => {
3881
+ context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
3882
+ });
3883
+ }
3884
+ if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
3885
+ if (!internal) {
3886
+ const failure = failures.take(method, pathname);
3887
+ if (failure) {
3888
+ injected = true;
3889
+ if (failure.hang) coverage.hit("outage.timeout");
3890
+ else if (failure.status === 429) coverage.hit("outage.rate-limit");
3891
+ else if (failure.status !== null) coverage.hit("outage.error");
3892
+ if (failure.delayMs > 0) coverage.hit("outage.slow");
3893
+ if (failure.hang) return;
3894
+ if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
3895
+ if (failure.status !== null) {
3896
+ const headers = {};
3897
+ if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
3898
+ return sendJson4(res, failure.status, failureBody(failure.status), headers);
3899
+ }
3900
+ }
3901
+ }
3902
+ if (await auth.handle(req, res, url, () => readForm(req))) return;
3903
+ if (await context.management.handle(req, res, url, async () => await readJson(req))) {
3904
+ if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
3905
+ else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
3906
+ return;
3907
+ }
3908
+ if (await context.account.handle(req, res, url)) {
3909
+ if (res.statusCode < 400) coverage.hit("api.account");
3910
+ return;
3911
+ }
3912
+ if (method === "GET" && pathname === "/testkit/portal") {
3913
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
3914
+ res.end(
3915
+ `<!doctype html><meta charset="utf-8"><title>Self-serve portal</title><body style="font:15px system-ui;padding:40px"><h1>Self-serve portal</h1><p>kinde-testkit does not emulate Kinde's self-serve portal. Your app linked here for <code>${escapeHtml(url.searchParams.get("subnav") ?? "profile")}</code>.</p>`
3916
+ );
3917
+ return;
3918
+ }
3919
+ if (method === "GET" && pathname === "/.well-known/openid-configuration") {
3920
+ return sendJson4(res, 200, discovery(testkit));
3921
+ }
3922
+ if (method === "GET" && JWKS_PATHS.has(pathname)) {
3923
+ return sendJson4(res, 200, testkit.jwks());
3924
+ }
3925
+ if (method === "GET" && pathname === "/testkit/health") {
3926
+ return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
3927
+ }
3928
+ if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
3929
+ if (method === "GET" && pathname === "/testkit/organizations") {
3930
+ return sendJson4(res, 200, seed.organizations);
3931
+ }
3932
+ if (method === "GET" && pathname === "/testkit/memberships") {
3933
+ return sendJson4(res, 200, seed.memberships);
3934
+ }
3935
+ if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
3936
+ if (method === "POST" && pathname === "/testkit/failures") {
3937
+ return sendJson4(res, 201, failures.add(await readJson(req)));
3938
+ }
3939
+ if (method === "DELETE" && pathname === "/testkit/failures") {
3940
+ failures.clear();
3941
+ return sendJson4(res, 200, { ok: true });
3942
+ }
3943
+ if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
3944
+ const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
3945
+ return sendJson4(res, removed ? 200 : 404, { ok: removed });
3946
+ }
3947
+ if (method === "POST" && pathname === "/testkit/webhooks") {
3948
+ return sendJson4(res, 200, await webhooks.send(await readJson(req)));
3949
+ }
3950
+ if (method === "GET" && pathname === "/testkit/webhooks/types") {
3951
+ return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
3952
+ }
3953
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
3954
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
3955
+ if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
3956
+ return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
3957
+ }
3958
+ if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
3959
+ const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
3960
+ return sendJson4(res, removed ? 200 : 404, { ok: removed });
3961
+ }
3962
+ if (method === "POST" && pathname === "/testkit/reset") {
3963
+ context.reset();
3964
+ return sendJson4(res, 200, { ok: true });
3965
+ }
3966
+ if (method === "POST" && pathname === "/testkit/token") {
3967
+ const body = await readJson(req);
3968
+ let accessToken;
3969
+ try {
3970
+ accessToken = await issueToken(testkit, seed, body);
3971
+ } catch (error) {
3972
+ if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
3973
+ throw error;
3974
+ }
3975
+ return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
3976
+ }
3977
+ if (method === "GET" && pathname === "/testkit/coverage") {
3978
+ return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
3979
+ }
3980
+ if (method === "DELETE" && pathname === "/testkit/coverage") {
3981
+ coverage.reset();
3982
+ return sendJson4(res, 200, { ok: true });
3983
+ }
3984
+ if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
3985
+ if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
3986
+ if (method === "POST" && pathname === "/testkit/seed") {
3987
+ const body = await readJson(req);
3988
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
3989
+ throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
3990
+ }
3991
+ context.loadSeed(body);
3992
+ return sendJson4(res, 200, {
3993
+ ok: true,
3994
+ users: seed.users.length,
3995
+ organizations: seed.organizations.length,
3996
+ memberships: seed.memberships.length
3997
+ });
3998
+ }
3999
+ if (method === "POST" && pathname === "/testkit/stop") {
4000
+ sendJson4(res, 200, { ok: true });
4001
+ res.once("finish", () => void context.close().catch(() => void 0));
4002
+ return;
4003
+ }
4004
+ return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
4005
+ }
4006
+ async function dashboard(req, res, url, context) {
4007
+ const method = req.method ?? "GET";
4008
+ const { pathname } = url;
4009
+ if (method === "GET" && pathname === "/dashboard") {
4010
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
4011
+ res.end(
4012
+ renderDashboard({
4013
+ issuer: context.testkit.issuer,
4014
+ seed: context.seed,
4015
+ suspended: (id) => context.directory.isSuspended(id),
4016
+ signIns: (id) => {
4017
+ const user = context.directory.user(id);
4018
+ return user ? context.directory.meta(user).totalSignIns : 0;
4019
+ },
4020
+ tokens: context.activity.tokens(),
4021
+ requests: context.activity.requests(),
4022
+ deliveries: context.webhooks.deliveries(),
4023
+ endpoints: context.webhooks.listEndpoints(),
4024
+ failures: context.failures.list(),
4025
+ coverage: context.coverage.report(),
4026
+ webhookTypes: WEBHOOK_EVENT_TYPES,
4027
+ live: url.searchParams.has("live"),
4028
+ notice: url.searchParams.get("notice")
4029
+ })
4030
+ );
4031
+ return;
4032
+ }
4033
+ if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
4034
+ const origin = req.headers.origin;
4035
+ if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
4036
+ return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
4037
+ }
4038
+ const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
4039
+ let notice = "Done.";
4040
+ try {
4041
+ if (pathname === "/dashboard/reset") {
4042
+ context.reset();
4043
+ notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
4044
+ } else if (pathname === "/dashboard/coverage/reset") {
4045
+ context.coverage.reset();
4046
+ notice = "Cleared coverage.";
4047
+ } else if (pathname === "/dashboard/failures/clear") {
4048
+ context.failures.clear();
4049
+ notice = "Removed every failure rule.";
4050
+ } else if (pathname === "/dashboard/failures") {
4051
+ const rule = { path: form2.path ?? "" };
4052
+ if (form2.method) rule.method = form2.method;
4053
+ if (form2.status) rule.status = Number(form2.status);
4054
+ if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
4055
+ if (form2.times) rule.times = Number(form2.times);
4056
+ if (form2.hang) rule.hang = true;
4057
+ const added = context.failures.add(rule);
4058
+ notice = `Added ${added.id} for ${added.path}.`;
4059
+ } else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
4060
+ const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
4061
+ notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
4062
+ } else if (pathname === "/dashboard/webhooks") {
4063
+ const deliveries = await context.webhooks.send({
4064
+ type: form2.type ?? "",
4065
+ user: form2.user || void 0,
4066
+ invalid: form2.invalid || void 0,
4067
+ duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
4068
+ });
4069
+ const delivered = deliveries.filter((d) => d.delivered).length;
4070
+ notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
4071
+ } else {
4072
+ return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
4073
+ }
4074
+ } catch (error) {
4075
+ notice = error.message.replace(/\s+/g, " ").trim();
4076
+ }
4077
+ const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
4078
+ res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
4079
+ res.end();
4080
+ }
4081
+ function discovery(testkit) {
4082
+ const base = testkit.issuer;
4083
+ return {
4084
+ issuer: base,
4085
+ authorization_endpoint: `${base}/oauth2/auth`,
4086
+ token_endpoint: `${base}/oauth2/token`,
4087
+ userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
4088
+ end_session_endpoint: `${base}/logout`,
4089
+ revocation_endpoint: `${base}/oauth2/revoke`,
4090
+ jwks_uri: `${base}/.well-known/jwks`,
4091
+ response_types_supported: ["code"],
4092
+ grant_types_supported: ["authorization_code", "refresh_token"],
4093
+ code_challenge_methods_supported: ["S256", "plain"],
4094
+ subject_types_supported: ["public"],
4095
+ id_token_signing_alg_values_supported: ["RS256"],
4096
+ scopes_supported: ["openid", "profile", "email", "offline"],
4097
+ token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic", "none"],
4098
+ claims_supported: ["aud", "exp", "iat", "iss", "sub", "org_code", "permissions", "roles", "scp"]
4099
+ };
4100
+ }
4101
+ async function issueToken(testkit, seed, body) {
4102
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
4103
+ throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
4104
+ }
4105
+ const input = body;
4106
+ const invalid3 = optionalString(input, "invalid");
4107
+ if (invalid3 !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid3)) {
4108
+ throw new TestkitError("INVALID_REQUEST", `"${invalid3}" is not a known invalid token kind.`, [
4109
+ `Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
4110
+ ]);
4111
+ }
4112
+ const expiresIn = input.expiresIn;
4113
+ if (input.m2m === true) {
4114
+ const clientId = optionalString(input, "clientId");
4115
+ const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
4116
+ const scopes = optionalStrings(input, "scopes") ?? [];
4117
+ return testkit.m2mToken({
4118
+ clientId,
4119
+ organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
4120
+ scopes,
4121
+ grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
4122
+ audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
4123
+ permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
4124
+ expiresIn,
4125
+ invalid: invalid3
4126
+ });
4127
+ }
4128
+ const permissions = optionalStrings(input, "permissions");
4129
+ const roles = optionalStrings(input, "roles");
4130
+ const userRef = optionalString(input, "user");
4131
+ if (userRef) {
4132
+ const scenario = seedScenario(seed, {
4133
+ user: userRef,
4134
+ organization: optionalString(input, "organization") ?? null
4135
+ });
4136
+ if (permissions) scenario.permissions = permissions;
4137
+ if (roles) scenario.roles = roles;
4138
+ return await testkit.tokenFor(scenario, {
4139
+ expiresIn,
4140
+ invalid: invalid3,
4141
+ featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
4142
+ });
4143
+ }
4144
+ const options = {
4145
+ subject: optionalString(input, "subject"),
4146
+ organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? null,
4147
+ permissions,
4148
+ roles,
4149
+ scopes: optionalStrings(input, "scopes"),
4150
+ expiresIn,
4151
+ invalid: invalid3
4152
+ };
4153
+ if (typeof input.claims === "object" && input.claims !== null) {
4154
+ options.claims = input.claims;
4155
+ }
4156
+ return testkit.token(options);
4157
+ }
4158
+ function optionalString(input, field) {
4159
+ const value = input[field];
4160
+ if (value === void 0 || value === null) return void 0;
4161
+ if (typeof value !== "string") {
4162
+ throw new TestkitError("INVALID_REQUEST", `"${field}" must be a string.`);
4163
+ }
4164
+ return value;
4165
+ }
4166
+ function optionalStrings(input, field) {
4167
+ const value = input[field];
4168
+ if (value === void 0) return void 0;
4169
+ if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
4170
+ throw new TestkitError("INVALID_REQUEST", `"${field}" must be a list of strings.`);
4171
+ }
4172
+ return value;
4173
+ }
4174
+ async function readForm(req) {
4175
+ const text = await readText(req);
4176
+ if ((req.headers["content-type"] ?? "").includes("application/json")) {
4177
+ try {
4178
+ const parsed = JSON.parse(text || "{}");
4179
+ return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));
4180
+ } catch {
4181
+ throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
4182
+ }
4183
+ }
4184
+ return Object.fromEntries(new URLSearchParams(text));
4185
+ }
4186
+ async function readJson(req) {
4187
+ const text = await readText(req);
4188
+ if (text.length === 0) return {};
4189
+ try {
4190
+ return JSON.parse(text);
4191
+ } catch {
4192
+ throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
4193
+ }
4194
+ }
4195
+ async function readText(req) {
4196
+ const chunks = [];
4197
+ let size = 0;
4198
+ for await (const chunk of req) {
4199
+ size += chunk.length;
4200
+ if (size > MAX_BODY_BYTES) {
4201
+ throw new TestkitError("INVALID_REQUEST", "The request body is larger than 64 KB.");
4202
+ }
4203
+ chunks.push(chunk);
4204
+ }
4205
+ return Buffer.concat(chunks).toString("utf8").trim();
4206
+ }
4207
+ function sendJson4(res, status, body, headers = {}) {
4208
+ res.writeHead(status, {
4209
+ "content-type": "application/json; charset=utf-8",
4210
+ "cache-control": "no-store",
4211
+ ...headers
4212
+ });
4213
+ res.end(JSON.stringify(body));
4214
+ }
4215
+ function sendError(res, error) {
4216
+ if (res.headersSent) {
4217
+ res.end();
4218
+ return;
4219
+ }
4220
+ if (error instanceof TestkitError) {
4221
+ sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
4222
+ return;
4223
+ }
4224
+ sendJson4(res, 500, {
4225
+ error: "server_error",
4226
+ error_description: error instanceof Error ? error.message : String(error)
4227
+ });
4228
+ }
4229
+
4230
+ // src/cypress.ts
4231
+ async function setupKindeTestkit(on, config, options = {}) {
4232
+ let url = options.url ?? config.env.KINDE_TESTKIT_URL ?? process.env.KINDE_ISSUER_URL ?? "http://localhost:4400";
4233
+ let running = null;
4234
+ if (options.start) {
4235
+ running = await startKindeTestkit({ port: 4400, ...options.start });
4236
+ url = running.url;
4237
+ on("after:run", async () => {
4238
+ await running?.close();
4239
+ running = null;
4240
+ });
4241
+ }
4242
+ config.env.KINDE_TESTKIT_URL = url.replace(/\/+$/, "");
4243
+ return config;
4244
+ }
4245
+ // Annotate the CommonJS export names for ESM import in node:
4246
+ 0 && (module.exports = {
4247
+ setupKindeTestkit
4248
+ });
4249
+ //# sourceMappingURL=cypress.cjs.map