kinde-testkit 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawnSync } from "child_process";
5
- import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
6
- import { resolve as resolve2 } from "path";
5
+ import { existsSync as existsSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
6
+ import { resolve as resolve4 } from "path";
7
7
  import { parseArgs } from "util";
8
8
 
9
9
  // src/errors.ts
@@ -180,8 +180,8 @@ import {
180
180
  // src/ids.ts
181
181
  import { createHash as createHash2 } from "crypto";
182
182
  var counters = /* @__PURE__ */ new Map();
183
- function stableId(prefix, seed) {
184
- return `${prefix}_${createHash2("sha256").update(seed).digest("hex").slice(0, 16)}`;
183
+ function stableId(prefix, seed2) {
184
+ return `${prefix}_${createHash2("sha256").update(seed2).digest("hex").slice(0, 16)}`;
185
185
  }
186
186
  function nextSequence(prefix) {
187
187
  const next = (counters.get(prefix) ?? 0) + 1;
@@ -275,6 +275,20 @@ var INVALID_TOKEN_KINDS = [
275
275
  var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
276
276
  var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
277
277
  var KindeTestkit = class _KindeTestkit {
278
+ observers = [];
279
+ /** Calls the observer for every token signed from now on. Returns a function that stops it. */
280
+ observe(observer) {
281
+ this.observers.push(observer);
282
+ return () => {
283
+ this.observers = this.observers.filter((o) => o !== observer);
284
+ };
285
+ }
286
+ async signAccess(payload, invalid2, now) {
287
+ const final = applyInvalidClaims(payload, invalid2, now);
288
+ const token2 = await this.sign(final, invalid2);
289
+ for (const observer of this.observers) observer.accessToken?.(final, invalid2, token2);
290
+ return token2;
291
+ }
278
292
  issuer;
279
293
  audience;
280
294
  clientId;
@@ -334,7 +348,7 @@ var KindeTestkit = class _KindeTestkit {
334
348
  if (options.organizationCode) payload.org_code = options.organizationCode;
335
349
  if (options.featureFlags) payload.feature_flags = options.featureFlags;
336
350
  Object.assign(payload, options.claims ?? {});
337
- return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
351
+ return this.signAccess(payload, options.invalid, now);
338
352
  }
339
353
  async m2mToken(options = {}) {
340
354
  const now = this.clock();
@@ -355,10 +369,13 @@ var KindeTestkit = class _KindeTestkit {
355
369
  if (options.organizationCode) payload.org_code = options.organizationCode;
356
370
  if (options.permissions !== void 0) payload.permissions = [...options.permissions];
357
371
  Object.assign(payload, options.claims ?? {});
358
- return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
372
+ return this.signAccess(payload, options.invalid, now);
359
373
  }
360
374
  async tokenFor(scenario, overrides = {}) {
361
- if (scenario.kind === "unauthenticated") return null;
375
+ if (scenario.kind === "unauthenticated") {
376
+ for (const observer of this.observers) observer.anonymous?.();
377
+ return null;
378
+ }
362
379
  return this.token({
363
380
  subject: scenario.user.id,
364
381
  organizationCode: scenario.organization?.code ?? null,
@@ -400,7 +417,9 @@ var KindeTestkit = class _KindeTestkit {
400
417
  for (const key of Object.keys(payload)) {
401
418
  if (payload[key] === null || payload[key] === void 0) delete payload[key];
402
419
  }
403
- return this.sign(payload);
420
+ const token2 = await this.sign(payload);
421
+ for (const observer of this.observers) observer.idToken?.(payload, token2);
422
+ return token2;
404
423
  }
405
424
  async headersFor(scenario, overrides = {}) {
406
425
  const token2 = await this.tokenFor(scenario, overrides);
@@ -577,9 +596,9 @@ function permissionRecord(key, extra = {}) {
577
596
  description: extra.description ?? null
578
597
  };
579
598
  }
580
- function effectivePermissions(seed, membership) {
599
+ function effectivePermissions(seed2, membership) {
581
600
  if (!membership) return [];
582
- const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
601
+ const fromRoles = membership.roles.flatMap((key) => seed2.roles.find((role) => role.key === key)?.permissions ?? []);
583
602
  return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
584
603
  }
585
604
  function resolveSeed(input) {
@@ -805,17 +824,17 @@ function findUser(users, ref) {
805
824
  const needle = ref.toLowerCase();
806
825
  return users.find((user) => user.id === ref || user.email?.toLowerCase() === needle);
807
826
  }
808
- function seedScenario(seed, ref) {
809
- const user = findUser(seed.users, ref.user);
827
+ function seedScenario(seed2, ref) {
828
+ const user = findUser(seed2.users, ref.user);
810
829
  if (!user) {
811
830
  throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${ref.user}".`, [
812
- `Known users: ${seed.users.map((u) => u.email ?? u.id).join(", ") || "none"}`
831
+ `Known users: ${seed2.users.map((u) => u.email ?? u.id).join(", ") || "none"}`
813
832
  ]);
814
833
  }
815
- const userMemberships = seed.memberships.filter((m) => m.userId === user.id);
834
+ const userMemberships = seed2.memberships.filter((m) => m.userId === user.id);
816
835
  let membership;
817
836
  if (ref.organization) {
818
- if (!seed.organizations.some((org) => org.code === ref.organization)) {
837
+ if (!seed2.organizations.some((org) => org.code === ref.organization)) {
819
838
  throw new TestkitError(
820
839
  "SEED_UNKNOWN_ORGANIZATION",
821
840
  `No seeded organization has the code "${ref.organization}".`
@@ -838,13 +857,13 @@ function seedScenario(seed, ref) {
838
857
  [`Organizations: ${userMemberships.map((m) => m.organizationCode).join(", ")}`]
839
858
  );
840
859
  }
841
- const organization = membership ? seed.organizations.find((org) => org.code === membership.organizationCode) ?? null : null;
860
+ const organization = membership ? seed2.organizations.find((org) => org.code === membership.organizationCode) ?? null : null;
842
861
  return {
843
862
  kind: "authenticated",
844
863
  user,
845
864
  organization,
846
865
  roles: [...membership?.roles ?? []],
847
- permissions: effectivePermissions(seed, membership),
866
+ permissions: effectivePermissions(seed2, membership),
848
867
  claims: {}
849
868
  };
850
869
  }
@@ -859,10 +878,10 @@ function listOf(value, field, problems) {
859
878
  function isRecord(value) {
860
879
  return typeof value === "object" && value !== null && !Array.isArray(value);
861
880
  }
862
- function featureFlagsFor(seed, organizationCode) {
863
- if (seed.featureFlags.length === 0) return void 0;
881
+ function featureFlagsFor(seed2, organizationCode) {
882
+ if (seed2.featureFlags.length === 0) return void 0;
864
883
  const claim = {};
865
- for (const flag of seed.featureFlags) {
884
+ for (const flag of seed2.featureFlags) {
866
885
  const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
867
886
  claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
868
887
  }
@@ -882,16 +901,18 @@ var OAuthError = class extends Error {
882
901
  error;
883
902
  };
884
903
  var AuthorizationServer = class {
885
- constructor(testkit, seed, emit = () => void 0, directory) {
904
+ constructor(testkit, seed2, emit = () => void 0, directory, observe = () => void 0) {
886
905
  this.testkit = testkit;
887
- this.seed = seed;
906
+ this.seed = seed2;
888
907
  this.emit = emit;
889
908
  this.directory = directory;
909
+ this.observe = observe;
890
910
  }
891
911
  testkit;
892
912
  seed;
893
913
  emit;
894
914
  directory;
915
+ observe;
895
916
  codes = /* @__PURE__ */ new Map();
896
917
  refreshTokens = /* @__PURE__ */ new Map();
897
918
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -928,6 +949,7 @@ var AuthorizationServer = class {
928
949
  return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
929
950
  }
930
951
  if (params.get("prompt") === "none") {
952
+ this.observe("session.silent");
931
953
  return redirectWithError(res, request2, "login_required", "kinde-testkit has no signed-in browser session.");
932
954
  }
933
955
  sendHtml(
@@ -941,15 +963,15 @@ var AuthorizationServer = class {
941
963
  })
942
964
  );
943
965
  }
944
- login(res, form) {
966
+ login(res, form2) {
945
967
  let request2;
946
968
  try {
947
- request2 = decodeRequest(form.request ?? "");
969
+ request2 = decodeRequest(form2.request ?? "");
948
970
  } catch {
949
971
  return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
950
972
  }
951
973
  const encoded = encodeRequest(request2);
952
- const ref = (form.user || form.email || "").trim();
974
+ const ref = (form2.user || form2.email || "").trim();
953
975
  if (!ref) {
954
976
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
955
977
  }
@@ -958,6 +980,7 @@ var AuthorizationServer = class {
958
980
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
959
981
  }
960
982
  if (this.directory?.isSuspended(user.id)) {
983
+ this.observe("identity.suspended");
961
984
  return sendHtml(
962
985
  res,
963
986
  403,
@@ -970,10 +993,11 @@ var AuthorizationServer = class {
970
993
  );
971
994
  }
972
995
  const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
973
- const wanted = request2.orgCode ?? form.org ?? null;
996
+ const wanted = request2.orgCode ?? form2.org ?? null;
974
997
  let organizationCode = null;
975
998
  if (wanted) {
976
999
  if (!memberships.some((m) => m.organizationCode === wanted)) {
1000
+ this.observe("organization.non-member");
977
1001
  return sendHtml(
978
1002
  res,
979
1003
  403,
@@ -1028,18 +1052,20 @@ var AuthorizationServer = class {
1028
1052
  if (request2.state !== null) target.searchParams.set("state", request2.state);
1029
1053
  redirect(res, target.toString());
1030
1054
  }
1031
- async token(req, res, form) {
1055
+ async token(req, res, form2) {
1032
1056
  try {
1033
- const clientId = clientIdFrom(req, form);
1034
- const grantType = form.grant_type;
1057
+ const clientId = clientIdFrom(req, form2);
1058
+ const grantType = form2.grant_type;
1035
1059
  if (grantType === "client_credentials") {
1036
- return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
1060
+ return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
1037
1061
  }
1038
1062
  let grant;
1039
1063
  if (grantType === "authorization_code") {
1040
- grant = this.redeemCode(form, clientId);
1064
+ grant = this.redeemCode(form2, clientId);
1065
+ this.observe("session.sign-in");
1041
1066
  } else if (grantType === "refresh_token") {
1042
- grant = this.redeemRefreshToken(form, clientId);
1067
+ grant = this.redeemRefreshToken(form2, clientId);
1068
+ this.observe("session.refresh");
1043
1069
  } else {
1044
1070
  throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
1045
1071
  }
@@ -1051,14 +1077,14 @@ var AuthorizationServer = class {
1051
1077
  throw error;
1052
1078
  }
1053
1079
  }
1054
- async clientCredentials(clientId, clientSecret, form) {
1080
+ async clientCredentials(clientId, clientSecret, form2) {
1055
1081
  const app = this.seed.applications.find((a) => a.clientId === clientId);
1056
1082
  if (app?.clientSecret && app.clientSecret !== clientSecret) {
1057
1083
  throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
1058
1084
  }
1059
- const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
1085
+ const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
1060
1086
  const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
1061
- const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
1087
+ const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
1062
1088
  return {
1063
1089
  access_token: await this.testkit.m2mToken({
1064
1090
  clientId,
@@ -1078,8 +1104,8 @@ var AuthorizationServer = class {
1078
1104
  this.refreshTokens.clear();
1079
1105
  this.signedUpUsers.clear();
1080
1106
  }
1081
- redeemCode(form, clientId) {
1082
- const code = form.code ?? "";
1107
+ redeemCode(form2, clientId) {
1108
+ const code = form2.code ?? "";
1083
1109
  const pending = this.codes.get(code);
1084
1110
  this.codes.delete(code);
1085
1111
  if (!pending || pending.expiresAt < Date.now()) {
@@ -1088,11 +1114,11 @@ var AuthorizationServer = class {
1088
1114
  if (pending.clientId !== clientId) {
1089
1115
  throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
1090
1116
  }
1091
- if (form.redirect_uri !== pending.redirectUri) {
1117
+ if (form2.redirect_uri !== pending.redirectUri) {
1092
1118
  throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
1093
1119
  }
1094
1120
  if (pending.codeChallenge) {
1095
- const verifier = form.code_verifier ?? "";
1121
+ const verifier = form2.code_verifier ?? "";
1096
1122
  const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
1097
1123
  if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
1098
1124
  throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
@@ -1100,8 +1126,8 @@ var AuthorizationServer = class {
1100
1126
  }
1101
1127
  return pending;
1102
1128
  }
1103
- redeemRefreshToken(form, clientId) {
1104
- const token2 = form.refresh_token ?? "";
1129
+ redeemRefreshToken(form2, clientId) {
1130
+ const token2 = form2.refresh_token ?? "";
1105
1131
  const grant = this.refreshTokens.get(token2);
1106
1132
  this.refreshTokens.delete(token2);
1107
1133
  if (!grant) {
@@ -1175,11 +1201,13 @@ var AuthorizationServer = class {
1175
1201
  phone: null
1176
1202
  });
1177
1203
  }
1178
- revoke(res, form) {
1179
- if (form.token) this.refreshTokens.delete(form.token);
1204
+ revoke(res, form2) {
1205
+ if (form2.token) this.refreshTokens.delete(form2.token);
1206
+ this.observe("session.revoke");
1180
1207
  sendJson(res, 200, {});
1181
1208
  }
1182
1209
  logout(res, params) {
1210
+ this.observe("session.sign-out");
1183
1211
  const target = params.get("redirect");
1184
1212
  if (target && isHttpUrl(target)) return redirect(res, target);
1185
1213
  sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
@@ -1191,6 +1219,7 @@ var AuthorizationServer = class {
1191
1219
  const user = createKindeUser({ email: ref.toLowerCase() });
1192
1220
  if (!this.signedUpUsers.has(user.id)) {
1193
1221
  this.signedUpUsers.set(user.id, user);
1222
+ this.observe("identity.unseeded");
1194
1223
  if (this.directory) this.seed.users.push(user);
1195
1224
  this.emit("user.created", user);
1196
1225
  }
@@ -1244,24 +1273,24 @@ function decodeRequest(value) {
1244
1273
  }
1245
1274
  return request2;
1246
1275
  }
1247
- function clientIdFrom(req, form) {
1276
+ function clientIdFrom(req, form2) {
1248
1277
  const header = req.headers.authorization ?? "";
1249
1278
  if (header.startsWith("Basic ")) {
1250
1279
  const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
1251
1280
  const id = decodeURIComponent(decoded.split(":")[0] ?? "");
1252
1281
  if (id) return id;
1253
1282
  }
1254
- if (form.client_id) return form.client_id;
1283
+ if (form2.client_id) return form2.client_id;
1255
1284
  throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
1256
1285
  }
1257
- function clientSecretFrom(req, form) {
1286
+ function clientSecretFrom(req, form2) {
1258
1287
  const header = req.headers.authorization ?? "";
1259
1288
  if (header.startsWith("Basic ")) {
1260
1289
  const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
1261
1290
  const index = decoded.indexOf(":");
1262
1291
  if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
1263
1292
  }
1264
- return form.client_secret ?? null;
1293
+ return form2.client_secret ?? null;
1265
1294
  }
1266
1295
  function redirectWithError(res, request2, error, description) {
1267
1296
  const target = new URL(request2.redirectUri);
@@ -1432,9 +1461,9 @@ function sendJson2(res, status, body) {
1432
1461
  // src/directory.ts
1433
1462
  import { randomBytes as randomBytes3 } from "crypto";
1434
1463
  var Directory = class {
1435
- constructor(seed) {
1436
- this.seed = seed;
1437
- this.snapshot = JSON.stringify(seed);
1464
+ constructor(seed2) {
1465
+ this.seed = seed2;
1466
+ this.snapshot = JSON.stringify(seed2);
1438
1467
  }
1439
1468
  seed;
1440
1469
  userMeta = /* @__PURE__ */ new Map();
@@ -1448,6 +1477,22 @@ var Directory = class {
1448
1477
  this.userMeta.clear();
1449
1478
  this.orgMeta.clear();
1450
1479
  }
1480
+ /** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
1481
+ load(next) {
1482
+ for (const key of Object.keys(next)) {
1483
+ const current = this.seed[key];
1484
+ if (Array.isArray(current)) {
1485
+ current.splice(0, current.length, ...next[key]);
1486
+ } else {
1487
+ const record = current;
1488
+ for (const name of Object.keys(record)) delete record[name];
1489
+ Object.assign(record, next[key]);
1490
+ }
1491
+ }
1492
+ this.snapshot = JSON.stringify(this.seed);
1493
+ this.userMeta.clear();
1494
+ this.orgMeta.clear();
1495
+ }
1451
1496
  user(id) {
1452
1497
  return this.seed.users.find((user) => user.id === id);
1453
1498
  }
@@ -2098,9 +2143,9 @@ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
2098
2143
  var DEFAULT_TIMEOUT_MS = 5e3;
2099
2144
  var MAX_DUPLICATES = 10;
2100
2145
  var WebhookDispatcher = class {
2101
- constructor(testkit, seed, endpoints = [], options = {}) {
2146
+ constructor(testkit, seed2, endpoints = [], options = {}) {
2102
2147
  this.testkit = testkit;
2103
- this.seed = seed;
2148
+ this.seed = seed2;
2104
2149
  this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
2105
2150
  this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2106
2151
  for (const endpoint of endpoints) this.addEndpoint(endpoint);
@@ -2114,6 +2159,8 @@ var WebhookDispatcher = class {
2114
2159
  nextEndpoint = 1;
2115
2160
  retryDelaysMs;
2116
2161
  timeoutMs;
2162
+ /** Set by the server to record coverage. */
2163
+ observe = () => void 0;
2117
2164
  addEndpoint(input) {
2118
2165
  if (!isHttpUrl2(input.url)) {
2119
2166
  throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
@@ -2125,6 +2172,14 @@ var WebhookDispatcher = class {
2125
2172
  this.endpoints.push(endpoint);
2126
2173
  return { ...endpoint };
2127
2174
  }
2175
+ /** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
2176
+ replaceSeededEndpoints(endpoints) {
2177
+ const seeded = new Set(this.seededEndpoints.map((e) => e.id));
2178
+ this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
2179
+ const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
2180
+ const ids = new Set(added.map((e) => e.id));
2181
+ this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
2182
+ }
2128
2183
  removeEndpoint(id) {
2129
2184
  const before = this.endpoints.length;
2130
2185
  this.endpoints = this.endpoints.filter((e) => e.id !== id);
@@ -2175,6 +2230,9 @@ var WebhookDispatcher = class {
2175
2230
  `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
2176
2231
  );
2177
2232
  }
2233
+ if (copies > 1) this.observe("webhook.duplicate");
2234
+ if (options.invalid === "stale") this.observe("webhook.stale");
2235
+ else if (options.invalid) this.observe("webhook.forged");
2178
2236
  if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
2179
2237
  const signed = await this.testkit.signPayload(
2180
2238
  event,
@@ -2184,7 +2242,11 @@ var WebhookDispatcher = class {
2184
2242
  const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
2185
2243
  return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
2186
2244
  });
2187
- return Promise.all(jobs);
2245
+ const deliveries = await Promise.all(jobs);
2246
+ if (!options.invalid) {
2247
+ for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
2248
+ }
2249
+ return deliveries;
2188
2250
  }
2189
2251
  async deliver(url, webhookId, body, event, copy) {
2190
2252
  const delivery = {
@@ -2333,7 +2395,511 @@ function isHttpUrl2(value) {
2333
2395
  }
2334
2396
  }
2335
2397
  function sleep(ms) {
2336
- return new Promise((resolve3) => setTimeout(resolve3, ms));
2398
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
2399
+ }
2400
+
2401
+ // src/activity.ts
2402
+ var LIMIT = 200;
2403
+ var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
2404
+ var ActivityLog = class {
2405
+ requestLog = [];
2406
+ tokenLog = [];
2407
+ request(entry) {
2408
+ const query = new URLSearchParams(entry.query);
2409
+ for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
2410
+ const search = query.toString();
2411
+ push(this.requestLog, {
2412
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2413
+ method: entry.method,
2414
+ path: search ? `${entry.path}?${search}` : entry.path,
2415
+ status: entry.status,
2416
+ durationMs: entry.durationMs,
2417
+ injected: entry.injected
2418
+ });
2419
+ }
2420
+ token(kind, claims, invalid2, token2) {
2421
+ const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
2422
+ push(this.tokenLog, {
2423
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2424
+ kind,
2425
+ subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
2426
+ organization: typeof claims.org_code === "string" ? claims.org_code : null,
2427
+ permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
2428
+ roles,
2429
+ invalid: invalid2 ?? null,
2430
+ expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
2431
+ claims,
2432
+ token: token2
2433
+ });
2434
+ }
2435
+ requests() {
2436
+ return [...this.requestLog];
2437
+ }
2438
+ tokens() {
2439
+ return [...this.tokenLog];
2440
+ }
2441
+ reset() {
2442
+ this.requestLog = [];
2443
+ this.tokenLog = [];
2444
+ }
2445
+ };
2446
+ function push(list2, entry) {
2447
+ list2.push(entry);
2448
+ if (list2.length > LIMIT) list2.splice(0, list2.length - LIMIT);
2449
+ }
2450
+
2451
+ // src/coverage.ts
2452
+ import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
2453
+ import { join as join2, resolve as resolve2 } from "path";
2454
+ var COVERAGE_GROUPS = [
2455
+ {
2456
+ name: "Identity",
2457
+ items: [
2458
+ { id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
2459
+ { id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
2460
+ { id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
2461
+ { id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
2462
+ { id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
2463
+ { id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
2464
+ ]
2465
+ },
2466
+ {
2467
+ name: "Organizations",
2468
+ items: [
2469
+ { id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
2470
+ { id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
2471
+ { id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
2472
+ { 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." },
2473
+ { id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
2474
+ ]
2475
+ },
2476
+ {
2477
+ name: "Permissions",
2478
+ items: [
2479
+ { id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
2480
+ { 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." },
2481
+ { id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
2482
+ { id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
2483
+ { id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
2484
+ ]
2485
+ },
2486
+ {
2487
+ name: "Token validation",
2488
+ items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
2489
+ (kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
2490
+ )
2491
+ },
2492
+ {
2493
+ name: "Sessions",
2494
+ items: [
2495
+ { id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
2496
+ { id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
2497
+ { id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
2498
+ { id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
2499
+ { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
2500
+ ]
2501
+ },
2502
+ {
2503
+ name: "Machine-to-machine",
2504
+ items: [
2505
+ { id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
2506
+ { id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
2507
+ { id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
2508
+ { id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
2509
+ ]
2510
+ },
2511
+ {
2512
+ name: "Kinde APIs",
2513
+ items: [
2514
+ { id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
2515
+ { id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
2516
+ { id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
2517
+ { id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
2518
+ ]
2519
+ },
2520
+ {
2521
+ name: "Webhooks",
2522
+ items: [
2523
+ { id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
2524
+ { id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
2525
+ { id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
2526
+ { id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
2527
+ { id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
2528
+ ]
2529
+ },
2530
+ {
2531
+ name: "Outages",
2532
+ items: [
2533
+ { id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
2534
+ { id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
2535
+ { id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
2536
+ { id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
2537
+ ]
2538
+ }
2539
+ ];
2540
+ var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
2541
+ function tokenLabel(kind) {
2542
+ return {
2543
+ expired: "Expired token",
2544
+ "future-iat": "Token issued in the future",
2545
+ "wrong-issuer": "Wrong issuer",
2546
+ "wrong-audience": "Wrong audience",
2547
+ "bad-signature": "Tampered signature",
2548
+ "unknown-key": "Unknown signing key",
2549
+ unsigned: "Unsigned token",
2550
+ "missing-subject": "No subject"
2551
+ }[kind];
2552
+ }
2553
+ var CoverageRecorder = class {
2554
+ hits = /* @__PURE__ */ new Map();
2555
+ userOrganizations = /* @__PURE__ */ new Map();
2556
+ organizationUsers = /* @__PURE__ */ new Map();
2557
+ organizationPermissionSets = /* @__PURE__ */ new Map();
2558
+ hit(id) {
2559
+ if (!ALL_IDS.has(id)) return;
2560
+ this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
2561
+ }
2562
+ /** Called for every access token the testkit signs. */
2563
+ observeAccessToken(payload, invalid2) {
2564
+ if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
2565
+ this.hit("m2m.token");
2566
+ if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
2567
+ if (typeof payload.org_code === "string") this.hit("m2m.organization");
2568
+ if (invalid2) this.hit("m2m.invalid");
2569
+ return;
2570
+ }
2571
+ if (invalid2 === "missing-organization") return this.hit("organization.missing");
2572
+ if (invalid2 === "missing-permissions") return this.hit("permission.none");
2573
+ if (invalid2) return this.hit(`token.${invalid2}`);
2574
+ const subject = typeof payload.sub === "string" ? payload.sub : null;
2575
+ const organization = typeof payload.org_code === "string" ? payload.org_code : null;
2576
+ const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
2577
+ if (subject) this.hit("identity.user");
2578
+ if (!organization) this.hit("identity.no-organization");
2579
+ if (permissions.length > 0) this.hit("permission.granted");
2580
+ else this.hit("permission.none");
2581
+ if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
2582
+ if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
2583
+ if (!organization) return;
2584
+ this.hit("organization.token");
2585
+ if (subject) {
2586
+ const organizations = add(this.userOrganizations, subject, organization);
2587
+ if (organizations.size > 1) this.hit("organization.two-for-one-user");
2588
+ add(this.organizationUsers, organization, subject);
2589
+ const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
2590
+ const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
2591
+ if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
2592
+ }
2593
+ const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
2594
+ if (sets.size > 1) this.hit("permission.different-sets");
2595
+ }
2596
+ report() {
2597
+ return buildReport(Object.fromEntries(this.hits));
2598
+ }
2599
+ snapshot() {
2600
+ return { version: 1, hits: Object.fromEntries(this.hits) };
2601
+ }
2602
+ reset() {
2603
+ this.hits.clear();
2604
+ this.userOrganizations.clear();
2605
+ this.organizationUsers.clear();
2606
+ this.organizationPermissionSets.clear();
2607
+ }
2608
+ /** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
2609
+ write(directory = DEFAULT_COVERAGE_DIRECTORY) {
2610
+ const folder = resolve2(directory);
2611
+ mkdirSync2(folder, { recursive: true });
2612
+ const file = join2(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
2613
+ writeFileSync2(file, `${JSON.stringify(this.snapshot())}
2614
+ `);
2615
+ return file;
2616
+ }
2617
+ };
2618
+ var DEFAULT_COVERAGE_DIRECTORY = join2(".kinde-testkit", "coverage");
2619
+ function add(map, key, value) {
2620
+ let set2 = map.get(key);
2621
+ if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
2622
+ set2.add(value);
2623
+ return set2;
2624
+ }
2625
+ function buildReport(hits) {
2626
+ const groups = COVERAGE_GROUPS.map((group) => {
2627
+ const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
2628
+ return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
2629
+ });
2630
+ return {
2631
+ covered: groups.reduce((sum, g) => sum + g.covered, 0),
2632
+ total: groups.reduce((sum, g) => sum + g.total, 0),
2633
+ groups
2634
+ };
2635
+ }
2636
+ function mergeSnapshots(snapshots) {
2637
+ const hits = {};
2638
+ for (const snapshot of snapshots) {
2639
+ for (const [id, count2] of Object.entries(snapshot.hits ?? {})) hits[id] = (hits[id] ?? 0) + count2;
2640
+ }
2641
+ return hits;
2642
+ }
2643
+ function readCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
2644
+ const folder = resolve2(directory);
2645
+ let names = [];
2646
+ try {
2647
+ names = readdirSync(folder).filter((name) => name.endsWith(".json"));
2648
+ } catch {
2649
+ }
2650
+ const snapshots = names.map((name) => JSON.parse(readFileSync2(join2(folder, name), "utf8")));
2651
+ return { files: names.length, report: buildReport(mergeSnapshots(snapshots)) };
2652
+ }
2653
+ function clearCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
2654
+ rmSync(resolve2(directory), { recursive: true, force: true });
2655
+ }
2656
+ function formatCoverageReport(report, options = {}) {
2657
+ const width = Math.max(...report.groups.map((g) => g.name.length)) + 3;
2658
+ const lines = ["Kinde authentication coverage", ""];
2659
+ for (const group of report.groups) {
2660
+ lines.push(`${group.name.padEnd(width)}${String(group.covered).padStart(2)}/${group.total}`);
2661
+ }
2662
+ lines.push("", `Overall: ${report.covered}/${report.total}`);
2663
+ if (options.missing !== false) {
2664
+ const missing = report.groups.flatMap((g) => g.items.filter((i) => !i.covered).map((i) => ({ group: g.name, ...i })));
2665
+ if (missing.length > 0) {
2666
+ lines.push("", "Not covered:");
2667
+ for (const item of missing) lines.push(` ${item.group}: ${item.label}. ${item.hint}`);
2668
+ }
2669
+ }
2670
+ return lines.join("\n");
2671
+ }
2672
+
2673
+ // src/dashboard.ts
2674
+ var STYLE2 = `
2675
+ :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}
2676
+ @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}}
2677
+ *{box-sizing:border-box}
2678
+ body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
2679
+ 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)}
2680
+ header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
2681
+ header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
2682
+ nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
2683
+ nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
2684
+ main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
2685
+ section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
2686
+ h2{margin:0 0 4px;font-size:16px;font-weight:600}
2687
+ .sub{margin:0 0 14px;color:var(--muted);font-size:13px}
2688
+ table{width:100%;border-collapse:collapse;font-size:13px}
2689
+ th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
2690
+ td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
2691
+ tr:last-child td{border-bottom:0}
2692
+ code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
2693
+ .chips{display:flex;flex-wrap:wrap;gap:4px}
2694
+ .chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
2695
+ .ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
2696
+ .empty{color:var(--muted);font-size:13px;margin:0}
2697
+ .row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
2698
+ label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
2699
+ 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}
2700
+ input[type=checkbox]{height:auto}
2701
+ 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}
2702
+ button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
2703
+ button:hover{border-color:var(--muted)}
2704
+ details summary{cursor:pointer;color:var(--muted)}
2705
+ 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}
2706
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
2707
+ .group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
2708
+ .group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
2709
+ .notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
2710
+ .split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
2711
+ `;
2712
+ function renderDashboard(data) {
2713
+ const e = escapeHtml;
2714
+ const { seed: seed2 } = data;
2715
+ const orgName = (code) => seed2.organizations.find((o) => o.code === code)?.name ?? code;
2716
+ const userLabel = (id) => seed2.users.find((u) => u.id === id)?.email ?? id;
2717
+ const users = seed2.users.length ? table(
2718
+ ["User", "ID", "Organizations", "Sign-ins", "Status"],
2719
+ seed2.users.map((user) => [
2720
+ e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
2721
+ `<code>${e(user.id)}</code>`,
2722
+ chips(seed2.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
2723
+ String(data.signIns(user.id)),
2724
+ data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
2725
+ ])
2726
+ ) : empty("No users yet. Seed some, or sign in with any email.");
2727
+ const organizations = seed2.organizations.length ? table(
2728
+ ["Organization", "Code", "Members"],
2729
+ seed2.organizations.map((org) => [
2730
+ e(org.name),
2731
+ `<code>${e(org.code)}</code>`,
2732
+ String(seed2.memberships.filter((m) => m.organizationCode === org.code).length)
2733
+ ])
2734
+ ) : empty("No organizations.");
2735
+ const memberships = seed2.memberships.length ? table(
2736
+ ["User", "Organization", "Roles", "Permissions in the token"],
2737
+ seed2.memberships.map((m) => [
2738
+ e(userLabel(m.userId)),
2739
+ e(orgName(m.organizationCode)),
2740
+ chips(m.roles),
2741
+ chips(effectivePermissions(seed2, m))
2742
+ ])
2743
+ ) : empty("No memberships.");
2744
+ const applications = seed2.applications.length ? table(
2745
+ ["Client ID", "Organization", "Scopes"],
2746
+ seed2.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
2747
+ ) : "";
2748
+ const tokens = data.tokens.length ? table(
2749
+ ["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
2750
+ [...data.tokens].reverse().slice(0, 50).map((t) => [
2751
+ time(t.at),
2752
+ t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
2753
+ `<code>${e(t.subject ?? "none")}</code>`,
2754
+ e(t.organization ?? "none"),
2755
+ chips(t.permissions),
2756
+ `<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
2757
+ ])
2758
+ ) : empty("No tokens issued yet.");
2759
+ const requests = data.requests.length ? table(
2760
+ ["Time", "Request", "Status", "Time taken"],
2761
+ [...data.requests].reverse().slice(0, 100).map((r) => [
2762
+ time(r.at),
2763
+ `<code>${e(r.method)} ${e(r.path)}</code>`,
2764
+ `<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
2765
+ `${r.durationMs} ms`
2766
+ ])
2767
+ ) : empty("No requests yet.");
2768
+ const deliveries = data.deliveries.length ? table(
2769
+ ["Event", "Endpoint", "Copy", "Result"],
2770
+ [...data.deliveries].reverse().slice(0, 50).map((d) => [
2771
+ `<code>${e(d.type)}</code>`,
2772
+ `<code>${e(d.url)}</code>`,
2773
+ String(d.copy),
2774
+ 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>`
2775
+ ])
2776
+ ) : empty("No webhooks sent yet.");
2777
+ 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>`;
2778
+ const webhookForm = data.endpoints.length ? form(
2779
+ "/dashboard/webhooks",
2780
+ `<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
2781
+ <label>User<select name="user"><option value="">First seeded user</option>${seed2.users.map((u) => `<option value="${e(u.id)}">${e(u.email ?? u.id)}</option>`).join("")}</select></label>
2782
+ <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>
2783
+ <label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
2784
+ <button class="primary">Send</button>`
2785
+ ) : "";
2786
+ const failures = data.failures.length ? table(
2787
+ ["Path", "Method", "Effect", "Remaining", "Hits", ""],
2788
+ data.failures.map((f) => [
2789
+ `<code>${e(f.path)}</code>`,
2790
+ e(f.method ?? "any"),
2791
+ e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
2792
+ f.remaining === null ? "Until removed" : String(f.remaining),
2793
+ String(f.hits),
2794
+ form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
2795
+ ])
2796
+ ) : empty("No failure rules.");
2797
+ const coverage2 = `<div class="grid">${data.coverage.groups.map(
2798
+ (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>`
2799
+ ).join("")}</div>`;
2800
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
2801
+ ${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
2802
+ <title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
2803
+ <header>
2804
+ <div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
2805
+ <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>
2806
+ <div class="row">
2807
+ <a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
2808
+ ${form("/dashboard/reset", `<button>Reset state</button>`)}
2809
+ </div>
2810
+ </header>
2811
+ <main>
2812
+ ${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
2813
+ <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>
2814
+ <div class="split">
2815
+ <section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
2816
+ <section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
2817
+ </div>
2818
+ ${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
2819
+ <section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
2820
+ <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>
2821
+ <section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
2822
+ <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>
2823
+ ${form(
2824
+ "/dashboard/failures",
2825
+ `<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
2826
+ <label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
2827
+ <label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
2828
+ <label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
2829
+ <label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
2830
+ <label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
2831
+ <button class="primary">Add rule</button>`
2832
+ )}
2833
+ <div style="margin-top:14px">${failures}</div>
2834
+ ${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
2835
+ </section>
2836
+ <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>${coverage2}
2837
+ <div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
2838
+ </main></body></html>`;
2839
+ }
2840
+ function table(headers, rows) {
2841
+ 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>`;
2842
+ }
2843
+ function chips(values) {
2844
+ if (values.length === 0) return `<span class="muted">none</span>`;
2845
+ return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
2846
+ }
2847
+ function empty(text) {
2848
+ return `<p class="empty">${escapeHtml(text)}</p>`;
2849
+ }
2850
+ function time(iso) {
2851
+ return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
2852
+ }
2853
+ function form(action, body) {
2854
+ return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
2855
+ }
2856
+
2857
+ // src/seed-file.ts
2858
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
2859
+ import { extname, resolve as resolve3 } from "path";
2860
+ import { pathToFileURL } from "url";
2861
+ import { parse as parseYaml } from "yaml";
2862
+ var DEFAULT_SEED_FILES = [
2863
+ "kinde-testkit.json",
2864
+ "kinde-testkit.yaml",
2865
+ "kinde-testkit.yml",
2866
+ "kinde-testkit.ts",
2867
+ "kinde-testkit.mts",
2868
+ "kinde-testkit.js",
2869
+ "kinde-testkit.mjs"
2870
+ ];
2871
+ function findSeedFile(directory = ".") {
2872
+ return DEFAULT_SEED_FILES.map((name) => resolve3(directory, name)).find((path) => existsSync2(path));
2873
+ }
2874
+ async function loadSeedFile(path) {
2875
+ const file = resolve3(path);
2876
+ const extension = extname(file).toLowerCase();
2877
+ let value;
2878
+ try {
2879
+ if (extension === ".yaml" || extension === ".yml") {
2880
+ value = parseYaml(readFileSync3(file, "utf8"));
2881
+ } else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
2882
+ const module = await import(pathToFileURL(file).href);
2883
+ value = module.seed ?? module.default;
2884
+ if (value && typeof value === "object" && "default" in value && !("users" in value)) {
2885
+ value = value.default;
2886
+ }
2887
+ } else {
2888
+ value = JSON.parse(readFileSync3(file, "utf8"));
2889
+ }
2890
+ } catch (error) {
2891
+ const message = error instanceof Error ? error.message : String(error);
2892
+ const details = [message];
2893
+ if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message)) {
2894
+ details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
2895
+ }
2896
+ throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
2897
+ }
2898
+ if (value === null || value === void 0) value = {};
2899
+ if (typeof value !== "object" || Array.isArray(value)) {
2900
+ throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
2901
+ }
2902
+ return value;
2337
2903
  }
2338
2904
 
2339
2905
  // src/server.ts
@@ -2348,30 +2914,49 @@ async function startKindeTestkit(options = {}) {
2348
2914
  `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).`
2349
2915
  );
2350
2916
  }
2351
- const seed = resolveSeed(options.seed ?? {});
2917
+ const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
2918
+ const seed2 = resolveSeed(seedInput);
2352
2919
  const failures = new FailureInjector();
2353
2920
  let ready;
2354
- const testkitReady = new Promise((resolve3) => ready = resolve3);
2921
+ const testkitReady = new Promise((resolve5) => ready = resolve5);
2355
2922
  const listener = (req, res) => {
2356
2923
  testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
2357
2924
  };
2358
2925
  const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
2359
2926
  const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
2360
- await new Promise((resolve3, reject) => {
2927
+ await new Promise((resolve5, reject) => {
2361
2928
  server.once("error", reject);
2362
- server.listen(options.port ?? 4400, host, () => resolve3());
2929
+ server.listen(options.port ?? 4400, host, () => resolve5());
2363
2930
  });
2364
2931
  const { port } = server.address();
2365
- const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
2932
+ const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
2366
2933
  const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
2367
2934
  const testkit = await KindeTestkit.create({
2368
- issuer: options.issuer ?? options.seed?.issuer ?? url,
2369
- audience: options.audience ?? options.seed?.audience,
2370
- clientId: options.clientId ?? options.seed?.clientId
2935
+ issuer: options.issuer ?? seedInput.issuer ?? url,
2936
+ audience: options.audience ?? seedInput.audience,
2937
+ clientId: options.clientId ?? seedInput.clientId
2938
+ });
2939
+ const coverage2 = new CoverageRecorder();
2940
+ const activity = new ActivityLog();
2941
+ testkit.observe({
2942
+ accessToken(payload, invalid2, token2) {
2943
+ coverage2.observeAccessToken(payload, invalid2);
2944
+ const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
2945
+ activity.token(m2m ? "m2m" : "access", payload, invalid2, token2);
2946
+ },
2947
+ idToken(payload, token2) {
2948
+ coverage2.hit("identity.id-token");
2949
+ activity.token("id", payload, void 0, token2);
2950
+ },
2951
+ anonymous() {
2952
+ coverage2.hit("identity.anonymous");
2953
+ }
2371
2954
  });
2372
- const directory = new Directory(seed);
2373
- const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
2374
- const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
2955
+ const observe = (id) => coverage2.hit(id);
2956
+ const directory = new Directory(seed2);
2957
+ const webhooks = new WebhookDispatcher(testkit, seed2, seed2.webhooks, options.webhooks);
2958
+ webhooks.observe = observe;
2959
+ const auth = new AuthorizationServer(testkit, seed2, (type, user) => webhooks.emitForUser(type, user), directory, observe);
2375
2960
  const management = new ManagementApi(testkit, directory, webhooks);
2376
2961
  const account = new AccountApi(testkit, directory);
2377
2962
  const reset2 = () => {
@@ -2380,35 +2965,65 @@ async function startKindeTestkit(options = {}) {
2380
2965
  webhooks.reset();
2381
2966
  directory.restore();
2382
2967
  };
2383
- ready({ testkit, auth, seed, failures, webhooks, management, account, reset: reset2 });
2968
+ const loadSeed = (input) => {
2969
+ const next = resolveSeed(input);
2970
+ directory.load(next);
2971
+ webhooks.replaceSeededEndpoints(next.webhooks);
2972
+ reset2();
2973
+ };
2974
+ let closed = false;
2975
+ const close = () => new Promise((resolve5, reject) => {
2976
+ if (closed) return resolve5();
2977
+ closed = true;
2978
+ if (options.coverage) {
2979
+ coverage2.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
2980
+ }
2981
+ server.closeAllConnections();
2982
+ server.close((error) => error ? reject(error) : resolve5());
2983
+ });
2984
+ ready({ testkit, auth, seed: seed2, failures, webhooks, management, account, reset: reset2, coverage: coverage2, activity, directory, loadSeed, close });
2384
2985
  return {
2385
2986
  url,
2386
2987
  issuer: testkit.issuer,
2387
2988
  discoveryUrl: `${url}/.well-known/openid-configuration`,
2388
2989
  jwksUri: `${url}/.well-known/jwks`,
2389
2990
  testkit,
2390
- seed,
2991
+ seed: seed2,
2391
2992
  failures,
2392
2993
  webhooks,
2393
2994
  directory,
2394
2995
  certificatePath: certificate?.certPath ?? null,
2996
+ coverage: coverage2,
2997
+ activity,
2998
+ loadSeed,
2395
2999
  reset: reset2,
2396
- close: () => new Promise((resolve3, reject) => {
2397
- server.closeAllConnections();
2398
- server.close((error) => error ? reject(error) : resolve3());
2399
- })
3000
+ close
2400
3001
  };
2401
3002
  }
2402
3003
  async function handle(req, res, context) {
2403
- const { testkit, auth, seed, failures, webhooks } = context;
3004
+ const { testkit, auth, seed: seed2, failures, webhooks, coverage: coverage2 } = context;
2404
3005
  const url = new URL(req.url ?? "/", "http://localhost");
2405
3006
  const { pathname } = url;
2406
3007
  const method = req.method ?? "GET";
2407
- if (!pathname.startsWith("/testkit/")) {
3008
+ const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
3009
+ let injected = false;
3010
+ if (!internal && pathname !== "/favicon.ico") {
3011
+ const started = Date.now();
3012
+ res.once("close", () => {
3013
+ context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
3014
+ });
3015
+ }
3016
+ if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
3017
+ if (!internal) {
2408
3018
  const failure = failures.take(method, pathname);
2409
3019
  if (failure) {
3020
+ injected = true;
3021
+ if (failure.hang) coverage2.hit("outage.timeout");
3022
+ else if (failure.status === 429) coverage2.hit("outage.rate-limit");
3023
+ else if (failure.status !== null) coverage2.hit("outage.error");
3024
+ if (failure.delayMs > 0) coverage2.hit("outage.slow");
2410
3025
  if (failure.hang) return;
2411
- if (failure.delayMs > 0) await new Promise((resolve3) => setTimeout(resolve3, failure.delayMs));
3026
+ if (failure.delayMs > 0) await new Promise((resolve5) => setTimeout(resolve5, failure.delayMs));
2412
3027
  if (failure.status !== null) {
2413
3028
  const headers = {};
2414
3029
  if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
@@ -2417,8 +3032,15 @@ async function handle(req, res, context) {
2417
3032
  }
2418
3033
  }
2419
3034
  if (await auth.handle(req, res, url, () => readForm(req))) return;
2420
- if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
2421
- if (await context.account.handle(req, res, url)) return;
3035
+ if (await context.management.handle(req, res, url, async () => await readJson(req))) {
3036
+ if (res.statusCode === 401 || res.statusCode === 403) coverage2.hit("api.management-denied");
3037
+ else if (res.statusCode < 400) coverage2.hit(method === "GET" ? "api.management-read" : "api.management-write");
3038
+ return;
3039
+ }
3040
+ if (await context.account.handle(req, res, url)) {
3041
+ if (res.statusCode < 400) coverage2.hit("api.account");
3042
+ return;
3043
+ }
2422
3044
  if (method === "GET" && pathname === "/testkit/portal") {
2423
3045
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2424
3046
  res.end(
@@ -2435,12 +3057,12 @@ async function handle(req, res, context) {
2435
3057
  if (method === "GET" && pathname === "/testkit/health") {
2436
3058
  return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
2437
3059
  }
2438
- if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
3060
+ if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed2.users);
2439
3061
  if (method === "GET" && pathname === "/testkit/organizations") {
2440
- return sendJson4(res, 200, seed.organizations);
3062
+ return sendJson4(res, 200, seed2.organizations);
2441
3063
  }
2442
3064
  if (method === "GET" && pathname === "/testkit/memberships") {
2443
- return sendJson4(res, 200, seed.memberships);
3065
+ return sendJson4(res, 200, seed2.memberships);
2444
3066
  }
2445
3067
  if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
2446
3068
  if (method === "POST" && pathname === "/testkit/failures") {
@@ -2475,11 +3097,119 @@ async function handle(req, res, context) {
2475
3097
  }
2476
3098
  if (method === "POST" && pathname === "/testkit/token") {
2477
3099
  const body = await readJson(req);
2478
- const accessToken = await issueToken(testkit, seed, body);
3100
+ let accessToken;
3101
+ try {
3102
+ accessToken = await issueToken(testkit, seed2, body);
3103
+ } catch (error) {
3104
+ if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage2.hit("organization.non-member");
3105
+ throw error;
3106
+ }
2479
3107
  return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
2480
3108
  }
3109
+ if (method === "GET" && pathname === "/testkit/coverage") {
3110
+ return sendJson4(res, 200, { report: coverage2.report(), snapshot: coverage2.snapshot() });
3111
+ }
3112
+ if (method === "DELETE" && pathname === "/testkit/coverage") {
3113
+ coverage2.reset();
3114
+ return sendJson4(res, 200, { ok: true });
3115
+ }
3116
+ if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
3117
+ if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
3118
+ if (method === "POST" && pathname === "/testkit/seed") {
3119
+ const body = await readJson(req);
3120
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
3121
+ throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
3122
+ }
3123
+ context.loadSeed(body);
3124
+ return sendJson4(res, 200, {
3125
+ ok: true,
3126
+ users: seed2.users.length,
3127
+ organizations: seed2.organizations.length,
3128
+ memberships: seed2.memberships.length
3129
+ });
3130
+ }
3131
+ if (method === "POST" && pathname === "/testkit/stop") {
3132
+ sendJson4(res, 200, { ok: true });
3133
+ res.once("finish", () => void context.close().catch(() => void 0));
3134
+ return;
3135
+ }
2481
3136
  return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
2482
3137
  }
3138
+ async function dashboard(req, res, url, context) {
3139
+ const method = req.method ?? "GET";
3140
+ const { pathname } = url;
3141
+ if (method === "GET" && pathname === "/dashboard") {
3142
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
3143
+ res.end(
3144
+ renderDashboard({
3145
+ issuer: context.testkit.issuer,
3146
+ seed: context.seed,
3147
+ suspended: (id) => context.directory.isSuspended(id),
3148
+ signIns: (id) => {
3149
+ const user = context.directory.user(id);
3150
+ return user ? context.directory.meta(user).totalSignIns : 0;
3151
+ },
3152
+ tokens: context.activity.tokens(),
3153
+ requests: context.activity.requests(),
3154
+ deliveries: context.webhooks.deliveries(),
3155
+ endpoints: context.webhooks.listEndpoints(),
3156
+ failures: context.failures.list(),
3157
+ coverage: context.coverage.report(),
3158
+ webhookTypes: WEBHOOK_EVENT_TYPES,
3159
+ live: url.searchParams.has("live"),
3160
+ notice: url.searchParams.get("notice")
3161
+ })
3162
+ );
3163
+ return;
3164
+ }
3165
+ if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
3166
+ const origin = req.headers.origin;
3167
+ if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
3168
+ return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
3169
+ }
3170
+ const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
3171
+ let notice = "Done.";
3172
+ try {
3173
+ if (pathname === "/dashboard/reset") {
3174
+ context.reset();
3175
+ notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
3176
+ } else if (pathname === "/dashboard/coverage/reset") {
3177
+ context.coverage.reset();
3178
+ notice = "Cleared coverage.";
3179
+ } else if (pathname === "/dashboard/failures/clear") {
3180
+ context.failures.clear();
3181
+ notice = "Removed every failure rule.";
3182
+ } else if (pathname === "/dashboard/failures") {
3183
+ const rule = { path: form2.path ?? "" };
3184
+ if (form2.method) rule.method = form2.method;
3185
+ if (form2.status) rule.status = Number(form2.status);
3186
+ if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
3187
+ if (form2.times) rule.times = Number(form2.times);
3188
+ if (form2.hang) rule.hang = true;
3189
+ const added = context.failures.add(rule);
3190
+ notice = `Added ${added.id} for ${added.path}.`;
3191
+ } else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
3192
+ const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
3193
+ notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
3194
+ } else if (pathname === "/dashboard/webhooks") {
3195
+ const deliveries = await context.webhooks.send({
3196
+ type: form2.type ?? "",
3197
+ user: form2.user || void 0,
3198
+ invalid: form2.invalid || void 0,
3199
+ duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
3200
+ });
3201
+ const delivered = deliveries.filter((d) => d.delivered).length;
3202
+ notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
3203
+ } else {
3204
+ return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
3205
+ }
3206
+ } catch (error) {
3207
+ notice = error.message.replace(/\s+/g, " ").trim();
3208
+ }
3209
+ const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
3210
+ res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
3211
+ res.end();
3212
+ }
2483
3213
  function discovery(testkit) {
2484
3214
  const base = testkit.issuer;
2485
3215
  return {
@@ -2500,7 +3230,7 @@ function discovery(testkit) {
2500
3230
  claims_supported: ["aud", "exp", "iat", "iss", "sub", "org_code", "permissions", "roles", "scp"]
2501
3231
  };
2502
3232
  }
2503
- async function issueToken(testkit, seed, body) {
3233
+ async function issueToken(testkit, seed2, body) {
2504
3234
  if (typeof body !== "object" || body === null || Array.isArray(body)) {
2505
3235
  throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
2506
3236
  }
@@ -2514,7 +3244,7 @@ async function issueToken(testkit, seed, body) {
2514
3244
  const expiresIn = input.expiresIn;
2515
3245
  if (input.m2m === true) {
2516
3246
  const clientId = optionalString(input, "clientId");
2517
- const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
3247
+ const app = clientId ? seed2.applications.find((a) => a.clientId === clientId) : void 0;
2518
3248
  const scopes = optionalStrings(input, "scopes") ?? [];
2519
3249
  return testkit.m2mToken({
2520
3250
  clientId,
@@ -2531,7 +3261,7 @@ async function issueToken(testkit, seed, body) {
2531
3261
  const roles = optionalStrings(input, "roles");
2532
3262
  const userRef = optionalString(input, "user");
2533
3263
  if (userRef) {
2534
- const scenario = seedScenario(seed, {
3264
+ const scenario = seedScenario(seed2, {
2535
3265
  user: userRef,
2536
3266
  organization: optionalString(input, "organization") ?? null
2537
3267
  });
@@ -2540,7 +3270,7 @@ async function issueToken(testkit, seed, body) {
2540
3270
  return await testkit.tokenFor(scenario, {
2541
3271
  expiresIn,
2542
3272
  invalid: invalid2,
2543
- featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
3273
+ featureFlags: featureFlagsFor(seed2, scenario.organization?.code ?? null)
2544
3274
  });
2545
3275
  }
2546
3276
  const options = {
@@ -2807,18 +3537,21 @@ function parseEnvFile(text) {
2807
3537
 
2808
3538
  // src/cli.ts
2809
3539
  var DEFAULT_URL = process.env.KINDE_TESTKIT_URL ?? "http://localhost:4400";
2810
- var DEFAULT_SEED_FILE = "kinde-testkit.json";
2811
3540
  var HELP = `kinde-testkit: a local Kinde issuer for testing apps
2812
3541
 
2813
3542
  Usage
2814
3543
  kinde-testkit start [options] Start the local issuer
3544
+ kinde-testkit stop Stop a running issuer
3545
+ kinde-testkit seed <file> Replace a running issuer's seed with a JSON, YAML, JS or TS file
2815
3546
  kinde-testkit token [options] Print a signed test access token
2816
3547
  kinde-testkit users [--json] List seeded users
2817
3548
  kinde-testkit organizations [--json] List seeded organizations
2818
3549
  kinde-testkit inspect [token] Decode a token and check it (reads stdin when no token)
3550
+ kinde-testkit inspect --requests Show the latest requests the issuer answered
3551
+ kinde-testkit coverage [options] Show which authentication scenarios your tests covered
2819
3552
  kinde-testkit doctor [options] Check your app's Kinde settings against the issuer
2820
3553
  kinde-testkit fail <path> [options] Make an endpoint fail, slow down or hang
2821
- kinde-testkit reset Clear sign-in sessions and failure rules
3554
+ kinde-testkit reset Clear sessions, failure rules, deliveries and API changes
2822
3555
  kinde-testkit webhook <type> [options] Send a signed webhook event
2823
3556
  kinde-testkit cert [--dir <dir>] Create the local HTTPS certificate and print its path
2824
3557
 
@@ -2828,11 +3561,13 @@ start
2828
3561
  --issuer <url> Issuer to put in tokens (default http://localhost:<port>)
2829
3562
  --audience <a,b> Audience values for access tokens
2830
3563
  --client-id <id> Value for azp
2831
- --seed <file> Seed file (default ./kinde-testkit.json when it exists)
3564
+ --seed <file> Seed file: JSON, YAML, JS or TS (default ./kinde-testkit.json,
3565
+ .yaml, .yml, .ts, .mts, .js or .mjs, the first that exists)
2832
3566
  --allow-public Allow binding to a non-loopback interface
2833
3567
  --webhook <url> Send webhooks to this URL (repeatable)
2834
3568
  --https Serve HTTPS with a local certificate (needed by @kinde/management-api-js)
2835
3569
  --cert-dir <dir> Where to keep that certificate (default ./.kinde-testkit)
3570
+ --coverage Write authentication coverage to ./.kinde-testkit/coverage when it stops
2836
3571
 
2837
3572
  token
2838
3573
  --url <url> Running issuer (default ${DEFAULT_URL})
@@ -2852,6 +3587,15 @@ token
2852
3587
 
2853
3588
  inspect
2854
3589
  --url <url> Also verify the issuer and signature against a running issuer
3590
+ --requests List the latest requests instead of checking a token
3591
+ --tokens List the latest issued tokens instead of checking a token
3592
+ --json Print JSON
3593
+
3594
+ coverage
3595
+ --url <url> Read a running issuer instead of the coverage folder
3596
+ --dir <dir> Coverage folder (default ./${DEFAULT_COVERAGE_DIRECTORY.replace(/\\/g, "/")})
3597
+ --min <n> Exit with an error when fewer than n scenarios are covered
3598
+ --clear Delete the coverage folder, or clear a running issuer's coverage
2855
3599
  --json Print JSON
2856
3600
 
2857
3601
  doctor
@@ -2906,6 +3650,12 @@ async function main(argv) {
2906
3650
  return webhook(rest);
2907
3651
  case "cert":
2908
3652
  return cert(rest);
3653
+ case "stop":
3654
+ return stop(rest);
3655
+ case "seed":
3656
+ return seed(rest);
3657
+ case "coverage":
3658
+ return coverage(rest);
2909
3659
  case void 0:
2910
3660
  case "help":
2911
3661
  case "--help":
@@ -2930,21 +3680,23 @@ async function start(args) {
2930
3680
  webhook: { type: "string", multiple: true },
2931
3681
  https: { type: "boolean" },
2932
3682
  "cert-dir": { type: "string" },
3683
+ coverage: { type: "boolean" },
2933
3684
  json: { type: "boolean" }
2934
3685
  }
2935
3686
  });
2936
- const seedPath = values.seed ?? (existsSync2(DEFAULT_SEED_FILE) ? DEFAULT_SEED_FILE : void 0);
2937
- const seed = seedPath ? readSeed(seedPath) : values.webhook ? {} : void 0;
2938
- if (seed && values.webhook) seed.webhooks = [...seed.webhooks ?? [], ...values.webhook.map((url) => ({ url }))];
3687
+ const seedPath = values.seed ?? findSeedFile();
3688
+ const seed2 = seedPath ? await loadSeedFile(seedPath) : values.webhook ? {} : void 0;
3689
+ if (seed2 && values.webhook) seed2.webhooks = [...seed2.webhooks ?? [], ...values.webhook.map((url) => ({ url }))];
2939
3690
  const running = await startKindeTestkit({
2940
3691
  port: values.port ? Number(values.port) : void 0,
2941
3692
  host: values.host,
2942
3693
  issuer: values.issuer,
2943
3694
  audience: values.audience ? csv(values.audience) : void 0,
2944
3695
  clientId: values["client-id"],
2945
- seed,
3696
+ seed: seed2,
2946
3697
  allowPublic: values["allow-public"],
2947
- https: values.https ? { certDirectory: values["cert-dir"] } : void 0
3698
+ https: values.https ? { certDirectory: values["cert-dir"] } : void 0,
3699
+ coverage: values.coverage
2948
3700
  });
2949
3701
  if (values.json) {
2950
3702
  process.stdout.write(
@@ -2953,6 +3705,7 @@ async function start(args) {
2953
3705
  issuer: running.issuer,
2954
3706
  discovery: running.discoveryUrl,
2955
3707
  jwks: running.jwksUri,
3708
+ dashboard: `${running.url}/dashboard`,
2956
3709
  users: running.seed.users.length,
2957
3710
  organizations: running.seed.organizations.length
2958
3711
  })}
@@ -2971,8 +3724,9 @@ async function start(args) {
2971
3724
  `JWKS: ${running.jwksUri}`,
2972
3725
  `Sign-in page: ${running.url}/oauth2/auth`,
2973
3726
  `Token: POST ${running.url}/testkit/token`,
3727
+ `Dashboard: ${running.url}/dashboard`,
2974
3728
  "",
2975
- `Seed: ${seedPath ? resolve2(seedPath) : "none"}`,
3729
+ `Seed: ${seedPath ? resolve4(seedPath) : "none"}`,
2976
3730
  `Users: ${running.seed.users.length}`,
2977
3731
  `Organizations: ${running.seed.organizations.length}`,
2978
3732
  `Webhooks: ${running.webhooks.listEndpoints().map((e) => e.url).join(", ") || "none"}`,
@@ -2983,11 +3737,11 @@ async function start(args) {
2983
3737
  ].join("\n")
2984
3738
  );
2985
3739
  }
2986
- const stop = () => {
3740
+ const stop2 = () => {
2987
3741
  running.close().finally(() => process.exit(0));
2988
3742
  };
2989
- process.once("SIGINT", stop);
2990
- process.once("SIGTERM", stop);
3743
+ process.once("SIGINT", stop2);
3744
+ process.once("SIGTERM", stop2);
2991
3745
  }
2992
3746
  async function token(args) {
2993
3747
  const { values } = parseArgs({
@@ -3038,8 +3792,31 @@ async function inspect(args) {
3038
3792
  const { values, positionals } = parseArgs({
3039
3793
  args,
3040
3794
  allowPositionals: true,
3041
- options: { url: { type: "string" }, json: { type: "boolean" } }
3795
+ options: { url: { type: "string" }, json: { type: "boolean" }, requests: { type: "boolean" }, tokens: { type: "boolean" } }
3042
3796
  });
3797
+ if (values.requests) {
3798
+ const entries = await request(values.url ?? DEFAULT_URL, "/testkit/requests");
3799
+ if (values.json) return void process.stdout.write(`${JSON.stringify(entries, null, 2)}
3800
+ `);
3801
+ if (entries.length === 0) return void process.stdout.write("No requests yet.\n");
3802
+ for (const e of entries) {
3803
+ process.stdout.write(`${e.at.slice(11, 19)} ${String(e.status).padEnd(4)}${e.injected ? "injected " : ""}${e.method.padEnd(7)}${e.path} ${e.durationMs}ms
3804
+ `);
3805
+ }
3806
+ return;
3807
+ }
3808
+ if (values.tokens) {
3809
+ const entries = await request(values.url ?? DEFAULT_URL, "/testkit/tokens");
3810
+ if (values.json) return void process.stdout.write(`${JSON.stringify(entries, null, 2)}
3811
+ `);
3812
+ if (entries.length === 0) return void process.stdout.write("No tokens issued yet.\n");
3813
+ for (const e of entries) {
3814
+ const parts = [e.kind, e.subject ?? "no subject", e.organization ?? "no organization", e.permissions.join(",") || "no permissions"];
3815
+ process.stdout.write(`${e.at.slice(11, 19)} ${parts.join(" ")}${e.invalid ? ` invalid: ${e.invalid}` : ""}
3816
+ `);
3817
+ }
3818
+ return;
3819
+ }
3043
3820
  const raw = positionals[0] ?? (process.stdin.isTTY ? "" : await readStdin());
3044
3821
  const token2 = raw.trim().replace(/^Bearer\s+/i, "");
3045
3822
  if (!token2) {
@@ -3082,11 +3859,11 @@ async function doctor(args) {
3082
3859
  json: { type: "boolean" }
3083
3860
  }
3084
3861
  });
3085
- const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) => existsSync2(file));
3862
+ const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) => existsSync3(file));
3086
3863
  const env = {};
3087
3864
  for (const file of files) {
3088
- if (!existsSync2(file)) throw new TestkitError("INVALID_REQUEST", `No env file at ${resolve2(file)}.`);
3089
- Object.assign(env, parseEnvFile(readFileSync2(file, "utf8")));
3865
+ if (!existsSync3(file)) throw new TestkitError("INVALID_REQUEST", `No env file at ${resolve4(file)}.`);
3866
+ Object.assign(env, parseEnvFile(readFileSync4(file, "utf8")));
3090
3867
  }
3091
3868
  for (const [key, value] of Object.entries(process.env)) {
3092
3869
  if ((key.startsWith("KINDE_") || key === "NODE_EXTRA_CA_CERTS") && value !== void 0) env[key] = value;
@@ -3166,7 +3943,79 @@ async function fail(args) {
3166
3943
  async function reset(args) {
3167
3944
  const { values } = parseArgs({ args, options: { url: { type: "string" } } });
3168
3945
  await request(values.url ?? DEFAULT_URL, "/testkit/reset", { method: "POST" });
3169
- process.stdout.write("Cleared sign-in codes, refresh tokens, signed-up users and failure rules.\n");
3946
+ process.stdout.write("Cleared sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.\n");
3947
+ }
3948
+ async function stop(args) {
3949
+ const { values } = parseArgs({ args, options: { url: { type: "string" } } });
3950
+ const url = values.url ?? DEFAULT_URL;
3951
+ await request(url, "/testkit/stop", { method: "POST" });
3952
+ process.stdout.write(`Stopped the issuer at ${url}.
3953
+ `);
3954
+ }
3955
+ async function seed(args) {
3956
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { url: { type: "string" }, json: { type: "boolean" } } });
3957
+ const path = positionals[0] ?? findSeedFile();
3958
+ if (!path) throw new TestkitError("INVALID_REQUEST", "Pass a seed file: kinde-testkit seed kinde-testkit.yaml");
3959
+ const body = await loadSeedFile(path);
3960
+ const result = await request(values.url ?? DEFAULT_URL, "/testkit/seed", {
3961
+ method: "POST",
3962
+ headers: { "content-type": "application/json" },
3963
+ body: JSON.stringify(body)
3964
+ });
3965
+ if (values.json) return void process.stdout.write(`${JSON.stringify(result)}
3966
+ `);
3967
+ process.stdout.write(
3968
+ `Loaded ${resolve4(path)}: ${count(result.users, "user")}, ${count(result.organizations, "organization")}, ${count(result.memberships, "membership")}.
3969
+ Sessions, failure rules and deliveries were cleared. The issuer, audience and signing key did not change.
3970
+ `
3971
+ );
3972
+ }
3973
+ function count(n, noun) {
3974
+ return `${n} ${noun}${n === 1 ? "" : "s"}`;
3975
+ }
3976
+ async function coverage(args) {
3977
+ const { values } = parseArgs({
3978
+ args,
3979
+ options: { url: { type: "string" }, dir: { type: "string" }, min: { type: "string" }, clear: { type: "boolean" }, json: { type: "boolean" } }
3980
+ });
3981
+ const directory = values.dir ?? DEFAULT_COVERAGE_DIRECTORY;
3982
+ if (values.clear) {
3983
+ if (values.url) await request(values.url, "/testkit/coverage", { method: "DELETE" });
3984
+ else clearCoverageDirectory(directory);
3985
+ process.stdout.write(values.url ? `Cleared coverage at ${values.url}.
3986
+ ` : `Deleted ${resolve4(directory)}.
3987
+ `);
3988
+ return;
3989
+ }
3990
+ let report;
3991
+ let source;
3992
+ if (values.url) {
3993
+ report = (await request(values.url, "/testkit/coverage")).report;
3994
+ source = values.url;
3995
+ } else {
3996
+ const read = readCoverageDirectory(directory);
3997
+ if (read.files === 0) {
3998
+ throw new TestkitError("INVALID_REQUEST", `No coverage recorded in ${resolve4(directory)}.`, [
3999
+ "Turn it on with useKindeTestkit({ coverage: true }), startKindeTestkit({ coverage: true }) or kinde-testkit start --coverage.",
4000
+ "Or read a running issuer with --url."
4001
+ ]);
4002
+ }
4003
+ report = read.report;
4004
+ source = `${read.files} test run${read.files === 1 ? "" : "s"} in ${resolve4(directory)}`;
4005
+ }
4006
+ if (values.json) process.stdout.write(`${JSON.stringify(report, null, 2)}
4007
+ `);
4008
+ else process.stdout.write(`${formatCoverageReport(report)}
4009
+
4010
+ From ${source}.
4011
+ `);
4012
+ const min = values.min === void 0 ? void 0 : Number(values.min);
4013
+ if (min !== void 0 && report.covered < min) {
4014
+ process.stderr.write(`
4015
+ Coverage ${report.covered}/${report.total} is below the minimum of ${min}.
4016
+ `);
4017
+ process.exitCode = 1;
4018
+ }
3170
4019
  }
3171
4020
  async function readStdin() {
3172
4021
  const chunks = [];
@@ -3332,15 +4181,6 @@ ${details.map((d) => ` - ${d}
3332
4181
  }
3333
4182
  return body;
3334
4183
  }
3335
- function readSeed(path) {
3336
- try {
3337
- return JSON.parse(readFileSync2(path, "utf8"));
3338
- } catch (error) {
3339
- throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${resolve2(path)}.`, [
3340
- error instanceof Error ? error.message : String(error)
3341
- ]);
3342
- }
3343
- }
3344
4184
  function csv(value) {
3345
4185
  return value.split(",").map((item) => item.trim()).filter(Boolean);
3346
4186
  }
@@ -3348,15 +4188,15 @@ function relaunchTrustingLocalCertificate(argv) {
3348
4188
  if (process.env.KINDE_TESTKIT_TRUSTED || argv[0] === "start" || argv[0] === "cert") return false;
3349
4189
  const urlArg = argv.find((arg, i) => arg.startsWith("--url=") || argv[i - 1] === "--url");
3350
4190
  const target = urlArg?.replace(/^--url=/, "") ?? process.env.KINDE_TESTKIT_URL ?? "";
3351
- const certPath = resolve2(".kinde-testkit", "localhost-cert.pem");
3352
- if (!target.startsWith("https://") || !existsSync2(certPath)) return false;
4191
+ const certPath = resolve4(".kinde-testkit", "localhost-cert.pem");
4192
+ if (!target.startsWith("https://") || !existsSync3(certPath)) return false;
3353
4193
  let trusted = certPath;
3354
4194
  const existing = process.env.NODE_EXTRA_CA_CERTS;
3355
- if (existing && resolve2(existing) !== certPath) {
3356
- trusted = resolve2(".kinde-testkit", "ca-bundle.pem");
3357
- const current = existsSync2(existing) ? readFileSync2(existing, "utf8") : "";
3358
- writeFileSync2(trusted, `${current.trimEnd()}
3359
- ${readFileSync2(certPath, "utf8")}`);
4195
+ if (existing && resolve4(existing) !== certPath) {
4196
+ trusted = resolve4(".kinde-testkit", "ca-bundle.pem");
4197
+ const current = existsSync3(existing) ? readFileSync4(existing, "utf8") : "";
4198
+ writeFileSync3(trusted, `${current.trimEnd()}
4199
+ ${readFileSync4(certPath, "utf8")}`);
3360
4200
  }
3361
4201
  const result = spawnSync(process.execPath, [process.argv[1], ...argv], {
3362
4202
  stdio: "inherit",