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/vitest.js CHANGED
@@ -129,6 +129,20 @@ var INVALID_TOKEN_KINDS = [
129
129
  var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
130
130
  var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
131
131
  var KindeTestkit = class _KindeTestkit {
132
+ observers = [];
133
+ /** Calls the observer for every token signed from now on. Returns a function that stops it. */
134
+ observe(observer) {
135
+ this.observers.push(observer);
136
+ return () => {
137
+ this.observers = this.observers.filter((o) => o !== observer);
138
+ };
139
+ }
140
+ async signAccess(payload, invalid2, now) {
141
+ const final = applyInvalidClaims(payload, invalid2, now);
142
+ const token = await this.sign(final, invalid2);
143
+ for (const observer of this.observers) observer.accessToken?.(final, invalid2, token);
144
+ return token;
145
+ }
132
146
  issuer;
133
147
  audience;
134
148
  clientId;
@@ -188,7 +202,7 @@ var KindeTestkit = class _KindeTestkit {
188
202
  if (options.organizationCode) payload.org_code = options.organizationCode;
189
203
  if (options.featureFlags) payload.feature_flags = options.featureFlags;
190
204
  Object.assign(payload, options.claims ?? {});
191
- return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
205
+ return this.signAccess(payload, options.invalid, now);
192
206
  }
193
207
  async m2mToken(options = {}) {
194
208
  const now = this.clock();
@@ -209,10 +223,13 @@ var KindeTestkit = class _KindeTestkit {
209
223
  if (options.organizationCode) payload.org_code = options.organizationCode;
210
224
  if (options.permissions !== void 0) payload.permissions = [...options.permissions];
211
225
  Object.assign(payload, options.claims ?? {});
212
- return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
226
+ return this.signAccess(payload, options.invalid, now);
213
227
  }
214
228
  async tokenFor(scenario, overrides = {}) {
215
- if (scenario.kind === "unauthenticated") return null;
229
+ if (scenario.kind === "unauthenticated") {
230
+ for (const observer of this.observers) observer.anonymous?.();
231
+ return null;
232
+ }
216
233
  return this.token({
217
234
  subject: scenario.user.id,
218
235
  organizationCode: scenario.organization?.code ?? null,
@@ -254,7 +271,9 @@ var KindeTestkit = class _KindeTestkit {
254
271
  for (const key of Object.keys(payload)) {
255
272
  if (payload[key] === null || payload[key] === void 0) delete payload[key];
256
273
  }
257
- return this.sign(payload);
274
+ const token = await this.sign(payload);
275
+ for (const observer of this.observers) observer.idToken?.(payload, token);
276
+ return token;
258
277
  }
259
278
  async headersFor(scenario, overrides = {}) {
260
279
  const token = await this.tokenFor(scenario, overrides);
@@ -885,16 +904,18 @@ var OAuthError = class extends Error {
885
904
  error;
886
905
  };
887
906
  var AuthorizationServer = class {
888
- constructor(testkit, seed, emit = () => void 0, directory) {
907
+ constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
889
908
  this.testkit = testkit;
890
909
  this.seed = seed;
891
910
  this.emit = emit;
892
911
  this.directory = directory;
912
+ this.observe = observe;
893
913
  }
894
914
  testkit;
895
915
  seed;
896
916
  emit;
897
917
  directory;
918
+ observe;
898
919
  codes = /* @__PURE__ */ new Map();
899
920
  refreshTokens = /* @__PURE__ */ new Map();
900
921
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -931,6 +952,7 @@ var AuthorizationServer = class {
931
952
  return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
932
953
  }
933
954
  if (params.get("prompt") === "none") {
955
+ this.observe("session.silent");
934
956
  return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
935
957
  }
936
958
  sendHtml(
@@ -944,15 +966,15 @@ var AuthorizationServer = class {
944
966
  })
945
967
  );
946
968
  }
947
- login(res, form) {
969
+ login(res, form2) {
948
970
  let request;
949
971
  try {
950
- request = decodeRequest(form.request ?? "");
972
+ request = decodeRequest(form2.request ?? "");
951
973
  } catch {
952
974
  return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
953
975
  }
954
976
  const encoded = encodeRequest(request);
955
- const ref = (form.user || form.email || "").trim();
977
+ const ref = (form2.user || form2.email || "").trim();
956
978
  if (!ref) {
957
979
  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." }));
958
980
  }
@@ -961,6 +983,7 @@ var AuthorizationServer = class {
961
983
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
962
984
  }
963
985
  if (this.directory?.isSuspended(user.id)) {
986
+ this.observe("identity.suspended");
964
987
  return sendHtml(
965
988
  res,
966
989
  403,
@@ -973,10 +996,11 @@ var AuthorizationServer = class {
973
996
  );
974
997
  }
975
998
  const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
976
- const wanted = request.orgCode ?? form.org ?? null;
999
+ const wanted = request.orgCode ?? form2.org ?? null;
977
1000
  let organizationCode = null;
978
1001
  if (wanted) {
979
1002
  if (!memberships.some((m) => m.organizationCode === wanted)) {
1003
+ this.observe("organization.non-member");
980
1004
  return sendHtml(
981
1005
  res,
982
1006
  403,
@@ -1031,18 +1055,20 @@ var AuthorizationServer = class {
1031
1055
  if (request.state !== null) target.searchParams.set("state", request.state);
1032
1056
  redirect(res, target.toString());
1033
1057
  }
1034
- async token(req, res, form) {
1058
+ async token(req, res, form2) {
1035
1059
  try {
1036
- const clientId = clientIdFrom(req, form);
1037
- const grantType = form.grant_type;
1060
+ const clientId = clientIdFrom(req, form2);
1061
+ const grantType = form2.grant_type;
1038
1062
  if (grantType === "client_credentials") {
1039
- return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
1063
+ return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
1040
1064
  }
1041
1065
  let grant;
1042
1066
  if (grantType === "authorization_code") {
1043
- grant = this.redeemCode(form, clientId);
1067
+ grant = this.redeemCode(form2, clientId);
1068
+ this.observe("session.sign-in");
1044
1069
  } else if (grantType === "refresh_token") {
1045
- grant = this.redeemRefreshToken(form, clientId);
1070
+ grant = this.redeemRefreshToken(form2, clientId);
1071
+ this.observe("session.refresh");
1046
1072
  } else {
1047
1073
  throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
1048
1074
  }
@@ -1054,14 +1080,14 @@ var AuthorizationServer = class {
1054
1080
  throw error;
1055
1081
  }
1056
1082
  }
1057
- async clientCredentials(clientId, clientSecret, form) {
1083
+ async clientCredentials(clientId, clientSecret, form2) {
1058
1084
  const app = this.seed.applications.find((a) => a.clientId === clientId);
1059
1085
  if (app?.clientSecret && app.clientSecret !== clientSecret) {
1060
1086
  throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
1061
1087
  }
1062
- const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
1088
+ const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
1063
1089
  const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
1064
- const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
1090
+ const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
1065
1091
  return {
1066
1092
  access_token: await this.testkit.m2mToken({
1067
1093
  clientId,
@@ -1081,8 +1107,8 @@ var AuthorizationServer = class {
1081
1107
  this.refreshTokens.clear();
1082
1108
  this.signedUpUsers.clear();
1083
1109
  }
1084
- redeemCode(form, clientId) {
1085
- const code = form.code ?? "";
1110
+ redeemCode(form2, clientId) {
1111
+ const code = form2.code ?? "";
1086
1112
  const pending = this.codes.get(code);
1087
1113
  this.codes.delete(code);
1088
1114
  if (!pending || pending.expiresAt < Date.now()) {
@@ -1091,11 +1117,11 @@ var AuthorizationServer = class {
1091
1117
  if (pending.clientId !== clientId) {
1092
1118
  throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
1093
1119
  }
1094
- if (form.redirect_uri !== pending.redirectUri) {
1120
+ if (form2.redirect_uri !== pending.redirectUri) {
1095
1121
  throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
1096
1122
  }
1097
1123
  if (pending.codeChallenge) {
1098
- const verifier = form.code_verifier ?? "";
1124
+ const verifier = form2.code_verifier ?? "";
1099
1125
  const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
1100
1126
  if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
1101
1127
  throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
@@ -1103,8 +1129,8 @@ var AuthorizationServer = class {
1103
1129
  }
1104
1130
  return pending;
1105
1131
  }
1106
- redeemRefreshToken(form, clientId) {
1107
- const token = form.refresh_token ?? "";
1132
+ redeemRefreshToken(form2, clientId) {
1133
+ const token = form2.refresh_token ?? "";
1108
1134
  const grant = this.refreshTokens.get(token);
1109
1135
  this.refreshTokens.delete(token);
1110
1136
  if (!grant) {
@@ -1178,11 +1204,13 @@ var AuthorizationServer = class {
1178
1204
  phone: null
1179
1205
  });
1180
1206
  }
1181
- revoke(res, form) {
1182
- if (form.token) this.refreshTokens.delete(form.token);
1207
+ revoke(res, form2) {
1208
+ if (form2.token) this.refreshTokens.delete(form2.token);
1209
+ this.observe("session.revoke");
1183
1210
  sendJson(res, 200, {});
1184
1211
  }
1185
1212
  logout(res, params) {
1213
+ this.observe("session.sign-out");
1186
1214
  const target = params.get("redirect");
1187
1215
  if (target && isHttpUrl(target)) return redirect(res, target);
1188
1216
  sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
@@ -1194,6 +1222,7 @@ var AuthorizationServer = class {
1194
1222
  const user = createKindeUser({ email: ref.toLowerCase() });
1195
1223
  if (!this.signedUpUsers.has(user.id)) {
1196
1224
  this.signedUpUsers.set(user.id, user);
1225
+ this.observe("identity.unseeded");
1197
1226
  if (this.directory) this.seed.users.push(user);
1198
1227
  this.emit("user.created", user);
1199
1228
  }
@@ -1247,24 +1276,24 @@ function decodeRequest(value) {
1247
1276
  }
1248
1277
  return request;
1249
1278
  }
1250
- function clientIdFrom(req, form) {
1279
+ function clientIdFrom(req, form2) {
1251
1280
  const header = req.headers.authorization ?? "";
1252
1281
  if (header.startsWith("Basic ")) {
1253
1282
  const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
1254
1283
  const id = decodeURIComponent(decoded.split(":")[0] ?? "");
1255
1284
  if (id) return id;
1256
1285
  }
1257
- if (form.client_id) return form.client_id;
1286
+ if (form2.client_id) return form2.client_id;
1258
1287
  throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
1259
1288
  }
1260
- function clientSecretFrom(req, form) {
1289
+ function clientSecretFrom(req, form2) {
1261
1290
  const header = req.headers.authorization ?? "";
1262
1291
  if (header.startsWith("Basic ")) {
1263
1292
  const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
1264
1293
  const index = decoded.indexOf(":");
1265
1294
  if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
1266
1295
  }
1267
- return form.client_secret ?? null;
1296
+ return form2.client_secret ?? null;
1268
1297
  }
1269
1298
  function redirectWithError(res, request, error, description) {
1270
1299
  const target = new URL(request.redirectUri);
@@ -1451,6 +1480,22 @@ var Directory = class {
1451
1480
  this.userMeta.clear();
1452
1481
  this.orgMeta.clear();
1453
1482
  }
1483
+ /** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
1484
+ load(next) {
1485
+ for (const key of Object.keys(next)) {
1486
+ const current = this.seed[key];
1487
+ if (Array.isArray(current)) {
1488
+ current.splice(0, current.length, ...next[key]);
1489
+ } else {
1490
+ const record = current;
1491
+ for (const name of Object.keys(record)) delete record[name];
1492
+ Object.assign(record, next[key]);
1493
+ }
1494
+ }
1495
+ this.snapshot = JSON.stringify(this.seed);
1496
+ this.userMeta.clear();
1497
+ this.orgMeta.clear();
1498
+ }
1454
1499
  user(id) {
1455
1500
  return this.seed.users.find((user) => user.id === id);
1456
1501
  }
@@ -2117,6 +2162,8 @@ var WebhookDispatcher = class {
2117
2162
  nextEndpoint = 1;
2118
2163
  retryDelaysMs;
2119
2164
  timeoutMs;
2165
+ /** Set by the server to record coverage. */
2166
+ observe = () => void 0;
2120
2167
  addEndpoint(input) {
2121
2168
  if (!isHttpUrl2(input.url)) {
2122
2169
  throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
@@ -2128,6 +2175,14 @@ var WebhookDispatcher = class {
2128
2175
  this.endpoints.push(endpoint);
2129
2176
  return { ...endpoint };
2130
2177
  }
2178
+ /** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
2179
+ replaceSeededEndpoints(endpoints) {
2180
+ const seeded = new Set(this.seededEndpoints.map((e) => e.id));
2181
+ this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
2182
+ const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
2183
+ const ids = new Set(added.map((e) => e.id));
2184
+ this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
2185
+ }
2131
2186
  removeEndpoint(id) {
2132
2187
  const before = this.endpoints.length;
2133
2188
  this.endpoints = this.endpoints.filter((e) => e.id !== id);
@@ -2178,6 +2233,9 @@ var WebhookDispatcher = class {
2178
2233
  `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
2179
2234
  );
2180
2235
  }
2236
+ if (copies > 1) this.observe("webhook.duplicate");
2237
+ if (options.invalid === "stale") this.observe("webhook.stale");
2238
+ else if (options.invalid) this.observe("webhook.forged");
2181
2239
  if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
2182
2240
  const signed = await this.testkit.signPayload(
2183
2241
  event,
@@ -2187,7 +2245,11 @@ var WebhookDispatcher = class {
2187
2245
  const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
2188
2246
  return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
2189
2247
  });
2190
- return Promise.all(jobs);
2248
+ const deliveries = await Promise.all(jobs);
2249
+ if (!options.invalid) {
2250
+ for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
2251
+ }
2252
+ return deliveries;
2191
2253
  }
2192
2254
  async deliver(url, webhookId, body, event, copy) {
2193
2255
  const delivery = {
@@ -2336,7 +2398,463 @@ function isHttpUrl2(value) {
2336
2398
  }
2337
2399
  }
2338
2400
  function sleep(ms) {
2339
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2401
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
2402
+ }
2403
+
2404
+ // src/activity.ts
2405
+ var LIMIT = 200;
2406
+ var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
2407
+ var ActivityLog = class {
2408
+ requestLog = [];
2409
+ tokenLog = [];
2410
+ request(entry) {
2411
+ const query = new URLSearchParams(entry.query);
2412
+ for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
2413
+ const search = query.toString();
2414
+ push(this.requestLog, {
2415
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2416
+ method: entry.method,
2417
+ path: search ? `${entry.path}?${search}` : entry.path,
2418
+ status: entry.status,
2419
+ durationMs: entry.durationMs,
2420
+ injected: entry.injected
2421
+ });
2422
+ }
2423
+ token(kind, claims, invalid2, token) {
2424
+ const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
2425
+ push(this.tokenLog, {
2426
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2427
+ kind,
2428
+ subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
2429
+ organization: typeof claims.org_code === "string" ? claims.org_code : null,
2430
+ permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
2431
+ roles,
2432
+ invalid: invalid2 ?? null,
2433
+ expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
2434
+ claims,
2435
+ token
2436
+ });
2437
+ }
2438
+ requests() {
2439
+ return [...this.requestLog];
2440
+ }
2441
+ tokens() {
2442
+ return [...this.tokenLog];
2443
+ }
2444
+ reset() {
2445
+ this.requestLog = [];
2446
+ this.tokenLog = [];
2447
+ }
2448
+ };
2449
+ function push(list, entry) {
2450
+ list.push(entry);
2451
+ if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
2452
+ }
2453
+
2454
+ // src/coverage.ts
2455
+ import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
2456
+ import { join as join2, resolve as resolve2 } from "path";
2457
+ var COVERAGE_GROUPS = [
2458
+ {
2459
+ name: "Identity",
2460
+ items: [
2461
+ { id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
2462
+ { id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
2463
+ { id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
2464
+ { id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
2465
+ { id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
2466
+ { id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
2467
+ ]
2468
+ },
2469
+ {
2470
+ name: "Organizations",
2471
+ items: [
2472
+ { id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
2473
+ { id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
2474
+ { id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
2475
+ { 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." },
2476
+ { id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
2477
+ ]
2478
+ },
2479
+ {
2480
+ name: "Permissions",
2481
+ items: [
2482
+ { id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
2483
+ { 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." },
2484
+ { id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
2485
+ { id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
2486
+ { id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
2487
+ ]
2488
+ },
2489
+ {
2490
+ name: "Token validation",
2491
+ items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
2492
+ (kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
2493
+ )
2494
+ },
2495
+ {
2496
+ name: "Sessions",
2497
+ items: [
2498
+ { id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
2499
+ { id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
2500
+ { id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
2501
+ { id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
2502
+ { id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
2503
+ ]
2504
+ },
2505
+ {
2506
+ name: "Machine-to-machine",
2507
+ items: [
2508
+ { id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
2509
+ { id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
2510
+ { id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
2511
+ { id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
2512
+ ]
2513
+ },
2514
+ {
2515
+ name: "Kinde APIs",
2516
+ items: [
2517
+ { id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
2518
+ { id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
2519
+ { id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
2520
+ { id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
2521
+ ]
2522
+ },
2523
+ {
2524
+ name: "Webhooks",
2525
+ items: [
2526
+ { id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
2527
+ { id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
2528
+ { id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
2529
+ { id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
2530
+ { id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
2531
+ ]
2532
+ },
2533
+ {
2534
+ name: "Outages",
2535
+ items: [
2536
+ { id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
2537
+ { id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
2538
+ { id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
2539
+ { id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
2540
+ ]
2541
+ }
2542
+ ];
2543
+ var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
2544
+ function tokenLabel(kind) {
2545
+ return {
2546
+ expired: "Expired token",
2547
+ "future-iat": "Token issued in the future",
2548
+ "wrong-issuer": "Wrong issuer",
2549
+ "wrong-audience": "Wrong audience",
2550
+ "bad-signature": "Tampered signature",
2551
+ "unknown-key": "Unknown signing key",
2552
+ unsigned: "Unsigned token",
2553
+ "missing-subject": "No subject"
2554
+ }[kind];
2555
+ }
2556
+ var CoverageRecorder = class {
2557
+ hits = /* @__PURE__ */ new Map();
2558
+ userOrganizations = /* @__PURE__ */ new Map();
2559
+ organizationUsers = /* @__PURE__ */ new Map();
2560
+ organizationPermissionSets = /* @__PURE__ */ new Map();
2561
+ hit(id) {
2562
+ if (!ALL_IDS.has(id)) return;
2563
+ this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
2564
+ }
2565
+ /** Called for every access token the testkit signs. */
2566
+ observeAccessToken(payload, invalid2) {
2567
+ if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
2568
+ this.hit("m2m.token");
2569
+ if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
2570
+ if (typeof payload.org_code === "string") this.hit("m2m.organization");
2571
+ if (invalid2) this.hit("m2m.invalid");
2572
+ return;
2573
+ }
2574
+ if (invalid2 === "missing-organization") return this.hit("organization.missing");
2575
+ if (invalid2 === "missing-permissions") return this.hit("permission.none");
2576
+ if (invalid2) return this.hit(`token.${invalid2}`);
2577
+ const subject = typeof payload.sub === "string" ? payload.sub : null;
2578
+ const organization = typeof payload.org_code === "string" ? payload.org_code : null;
2579
+ const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
2580
+ if (subject) this.hit("identity.user");
2581
+ if (!organization) this.hit("identity.no-organization");
2582
+ if (permissions.length > 0) this.hit("permission.granted");
2583
+ else this.hit("permission.none");
2584
+ if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
2585
+ if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
2586
+ if (!organization) return;
2587
+ this.hit("organization.token");
2588
+ if (subject) {
2589
+ const organizations = add(this.userOrganizations, subject, organization);
2590
+ if (organizations.size > 1) this.hit("organization.two-for-one-user");
2591
+ add(this.organizationUsers, organization, subject);
2592
+ const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
2593
+ const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
2594
+ if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
2595
+ }
2596
+ const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
2597
+ if (sets.size > 1) this.hit("permission.different-sets");
2598
+ }
2599
+ report() {
2600
+ return buildReport(Object.fromEntries(this.hits));
2601
+ }
2602
+ snapshot() {
2603
+ return { version: 1, hits: Object.fromEntries(this.hits) };
2604
+ }
2605
+ reset() {
2606
+ this.hits.clear();
2607
+ this.userOrganizations.clear();
2608
+ this.organizationUsers.clear();
2609
+ this.organizationPermissionSets.clear();
2610
+ }
2611
+ /** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
2612
+ write(directory = DEFAULT_COVERAGE_DIRECTORY) {
2613
+ const folder = resolve2(directory);
2614
+ mkdirSync2(folder, { recursive: true });
2615
+ const file = join2(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
2616
+ writeFileSync2(file, `${JSON.stringify(this.snapshot())}
2617
+ `);
2618
+ return file;
2619
+ }
2620
+ };
2621
+ var DEFAULT_COVERAGE_DIRECTORY = join2(".kinde-testkit", "coverage");
2622
+ function add(map, key, value) {
2623
+ let set2 = map.get(key);
2624
+ if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
2625
+ set2.add(value);
2626
+ return set2;
2627
+ }
2628
+ function buildReport(hits) {
2629
+ const groups = COVERAGE_GROUPS.map((group) => {
2630
+ const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
2631
+ return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
2632
+ });
2633
+ return {
2634
+ covered: groups.reduce((sum, g) => sum + g.covered, 0),
2635
+ total: groups.reduce((sum, g) => sum + g.total, 0),
2636
+ groups
2637
+ };
2638
+ }
2639
+
2640
+ // src/dashboard.ts
2641
+ var STYLE2 = `
2642
+ :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}
2643
+ @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}}
2644
+ *{box-sizing:border-box}
2645
+ body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
2646
+ 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)}
2647
+ header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
2648
+ header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
2649
+ nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
2650
+ nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
2651
+ main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
2652
+ section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
2653
+ h2{margin:0 0 4px;font-size:16px;font-weight:600}
2654
+ .sub{margin:0 0 14px;color:var(--muted);font-size:13px}
2655
+ table{width:100%;border-collapse:collapse;font-size:13px}
2656
+ th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
2657
+ td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
2658
+ tr:last-child td{border-bottom:0}
2659
+ code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
2660
+ .chips{display:flex;flex-wrap:wrap;gap:4px}
2661
+ .chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
2662
+ .ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
2663
+ .empty{color:var(--muted);font-size:13px;margin:0}
2664
+ .row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
2665
+ label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
2666
+ 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}
2667
+ input[type=checkbox]{height:auto}
2668
+ 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}
2669
+ button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
2670
+ button:hover{border-color:var(--muted)}
2671
+ details summary{cursor:pointer;color:var(--muted)}
2672
+ 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}
2673
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
2674
+ .group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
2675
+ .group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
2676
+ .notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
2677
+ .split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
2678
+ `;
2679
+ function renderDashboard(data) {
2680
+ const e = escapeHtml;
2681
+ const { seed } = data;
2682
+ const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
2683
+ const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
2684
+ const users = seed.users.length ? table(
2685
+ ["User", "ID", "Organizations", "Sign-ins", "Status"],
2686
+ seed.users.map((user) => [
2687
+ e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
2688
+ `<code>${e(user.id)}</code>`,
2689
+ chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
2690
+ String(data.signIns(user.id)),
2691
+ data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
2692
+ ])
2693
+ ) : empty("No users yet. Seed some, or sign in with any email.");
2694
+ const organizations = seed.organizations.length ? table(
2695
+ ["Organization", "Code", "Members"],
2696
+ seed.organizations.map((org) => [
2697
+ e(org.name),
2698
+ `<code>${e(org.code)}</code>`,
2699
+ String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
2700
+ ])
2701
+ ) : empty("No organizations.");
2702
+ const memberships = seed.memberships.length ? table(
2703
+ ["User", "Organization", "Roles", "Permissions in the token"],
2704
+ seed.memberships.map((m) => [
2705
+ e(userLabel(m.userId)),
2706
+ e(orgName(m.organizationCode)),
2707
+ chips(m.roles),
2708
+ chips(effectivePermissions(seed, m))
2709
+ ])
2710
+ ) : empty("No memberships.");
2711
+ const applications = seed.applications.length ? table(
2712
+ ["Client ID", "Organization", "Scopes"],
2713
+ seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
2714
+ ) : "";
2715
+ const tokens = data.tokens.length ? table(
2716
+ ["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
2717
+ [...data.tokens].reverse().slice(0, 50).map((t) => [
2718
+ time(t.at),
2719
+ t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
2720
+ `<code>${e(t.subject ?? "none")}</code>`,
2721
+ e(t.organization ?? "none"),
2722
+ chips(t.permissions),
2723
+ `<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
2724
+ ])
2725
+ ) : empty("No tokens issued yet.");
2726
+ const requests = data.requests.length ? table(
2727
+ ["Time", "Request", "Status", "Time taken"],
2728
+ [...data.requests].reverse().slice(0, 100).map((r) => [
2729
+ time(r.at),
2730
+ `<code>${e(r.method)} ${e(r.path)}</code>`,
2731
+ `<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
2732
+ `${r.durationMs} ms`
2733
+ ])
2734
+ ) : empty("No requests yet.");
2735
+ const deliveries = data.deliveries.length ? table(
2736
+ ["Event", "Endpoint", "Copy", "Result"],
2737
+ [...data.deliveries].reverse().slice(0, 50).map((d) => [
2738
+ `<code>${e(d.type)}</code>`,
2739
+ `<code>${e(d.url)}</code>`,
2740
+ String(d.copy),
2741
+ 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>`
2742
+ ])
2743
+ ) : empty("No webhooks sent yet.");
2744
+ 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>`;
2745
+ const webhookForm = data.endpoints.length ? form(
2746
+ "/dashboard/webhooks",
2747
+ `<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
2748
+ <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>
2749
+ <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>
2750
+ <label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
2751
+ <button class="primary">Send</button>`
2752
+ ) : "";
2753
+ const failures = data.failures.length ? table(
2754
+ ["Path", "Method", "Effect", "Remaining", "Hits", ""],
2755
+ data.failures.map((f) => [
2756
+ `<code>${e(f.path)}</code>`,
2757
+ e(f.method ?? "any"),
2758
+ e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
2759
+ f.remaining === null ? "Until removed" : String(f.remaining),
2760
+ String(f.hits),
2761
+ form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
2762
+ ])
2763
+ ) : empty("No failure rules.");
2764
+ const coverage = `<div class="grid">${data.coverage.groups.map(
2765
+ (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>`
2766
+ ).join("")}</div>`;
2767
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
2768
+ ${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
2769
+ <title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
2770
+ <header>
2771
+ <div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
2772
+ <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>
2773
+ <div class="row">
2774
+ <a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
2775
+ ${form("/dashboard/reset", `<button>Reset state</button>`)}
2776
+ </div>
2777
+ </header>
2778
+ <main>
2779
+ ${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
2780
+ <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>
2781
+ <div class="split">
2782
+ <section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
2783
+ <section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
2784
+ </div>
2785
+ ${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
2786
+ <section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
2787
+ <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>
2788
+ <section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
2789
+ <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>
2790
+ ${form(
2791
+ "/dashboard/failures",
2792
+ `<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
2793
+ <label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
2794
+ <label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
2795
+ <label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
2796
+ <label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
2797
+ <label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
2798
+ <button class="primary">Add rule</button>`
2799
+ )}
2800
+ <div style="margin-top:14px">${failures}</div>
2801
+ ${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
2802
+ </section>
2803
+ <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}
2804
+ <div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
2805
+ </main></body></html>`;
2806
+ }
2807
+ function table(headers, rows) {
2808
+ 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>`;
2809
+ }
2810
+ function chips(values) {
2811
+ if (values.length === 0) return `<span class="muted">none</span>`;
2812
+ return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
2813
+ }
2814
+ function empty(text) {
2815
+ return `<p class="empty">${escapeHtml(text)}</p>`;
2816
+ }
2817
+ function time(iso) {
2818
+ return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
2819
+ }
2820
+ function form(action, body) {
2821
+ return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
2822
+ }
2823
+
2824
+ // src/seed-file.ts
2825
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
2826
+ import { extname, resolve as resolve3 } from "path";
2827
+ import { pathToFileURL } from "url";
2828
+ import { parse as parseYaml } from "yaml";
2829
+ async function loadSeedFile(path) {
2830
+ const file = resolve3(path);
2831
+ const extension = extname(file).toLowerCase();
2832
+ let value;
2833
+ try {
2834
+ if (extension === ".yaml" || extension === ".yml") {
2835
+ value = parseYaml(readFileSync3(file, "utf8"));
2836
+ } else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
2837
+ const module = await import(pathToFileURL(file).href);
2838
+ value = module.seed ?? module.default;
2839
+ if (value && typeof value === "object" && "default" in value && !("users" in value)) {
2840
+ value = value.default;
2841
+ }
2842
+ } else {
2843
+ value = JSON.parse(readFileSync3(file, "utf8"));
2844
+ }
2845
+ } catch (error) {
2846
+ const message = error instanceof Error ? error.message : String(error);
2847
+ const details = [message];
2848
+ if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message)) {
2849
+ details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
2850
+ }
2851
+ throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
2852
+ }
2853
+ if (value === null || value === void 0) value = {};
2854
+ if (typeof value !== "object" || Array.isArray(value)) {
2855
+ throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
2856
+ }
2857
+ return value;
2340
2858
  }
2341
2859
 
2342
2860
  // src/server.ts
@@ -2351,30 +2869,49 @@ async function startKindeTestkit(options = {}) {
2351
2869
  `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).`
2352
2870
  );
2353
2871
  }
2354
- const seed = resolveSeed(options.seed ?? {});
2872
+ const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
2873
+ const seed = resolveSeed(seedInput);
2355
2874
  const failures = new FailureInjector();
2356
2875
  let ready;
2357
- const testkitReady = new Promise((resolve2) => ready = resolve2);
2876
+ const testkitReady = new Promise((resolve4) => ready = resolve4);
2358
2877
  const listener = (req, res) => {
2359
2878
  testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
2360
2879
  };
2361
2880
  const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
2362
2881
  const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
2363
- await new Promise((resolve2, reject) => {
2882
+ await new Promise((resolve4, reject) => {
2364
2883
  server.once("error", reject);
2365
- server.listen(options.port ?? 4400, host, () => resolve2());
2884
+ server.listen(options.port ?? 4400, host, () => resolve4());
2366
2885
  });
2367
2886
  const { port } = server.address();
2368
- const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
2887
+ const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
2369
2888
  const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
2370
2889
  const testkit = await KindeTestkit.create({
2371
- issuer: options.issuer ?? options.seed?.issuer ?? url,
2372
- audience: options.audience ?? options.seed?.audience,
2373
- clientId: options.clientId ?? options.seed?.clientId
2890
+ issuer: options.issuer ?? seedInput.issuer ?? url,
2891
+ audience: options.audience ?? seedInput.audience,
2892
+ clientId: options.clientId ?? seedInput.clientId
2374
2893
  });
2894
+ const coverage = new CoverageRecorder();
2895
+ const activity = new ActivityLog();
2896
+ testkit.observe({
2897
+ accessToken(payload, invalid2, token) {
2898
+ coverage.observeAccessToken(payload, invalid2);
2899
+ const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
2900
+ activity.token(m2m ? "m2m" : "access", payload, invalid2, token);
2901
+ },
2902
+ idToken(payload, token) {
2903
+ coverage.hit("identity.id-token");
2904
+ activity.token("id", payload, void 0, token);
2905
+ },
2906
+ anonymous() {
2907
+ coverage.hit("identity.anonymous");
2908
+ }
2909
+ });
2910
+ const observe = (id) => coverage.hit(id);
2375
2911
  const directory = new Directory(seed);
2376
2912
  const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
2377
- const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
2913
+ webhooks.observe = observe;
2914
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
2378
2915
  const management = new ManagementApi(testkit, directory, webhooks);
2379
2916
  const account = new AccountApi(testkit, directory);
2380
2917
  const reset = () => {
@@ -2383,7 +2920,23 @@ async function startKindeTestkit(options = {}) {
2383
2920
  webhooks.reset();
2384
2921
  directory.restore();
2385
2922
  };
2386
- ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
2923
+ const loadSeed = (input) => {
2924
+ const next = resolveSeed(input);
2925
+ directory.load(next);
2926
+ webhooks.replaceSeededEndpoints(next.webhooks);
2927
+ reset();
2928
+ };
2929
+ let closed = false;
2930
+ const close = () => new Promise((resolve4, reject) => {
2931
+ if (closed) return resolve4();
2932
+ closed = true;
2933
+ if (options.coverage) {
2934
+ coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
2935
+ }
2936
+ server.closeAllConnections();
2937
+ server.close((error) => error ? reject(error) : resolve4());
2938
+ });
2939
+ ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
2387
2940
  return {
2388
2941
  url,
2389
2942
  issuer: testkit.issuer,
@@ -2395,23 +2948,37 @@ async function startKindeTestkit(options = {}) {
2395
2948
  webhooks,
2396
2949
  directory,
2397
2950
  certificatePath: certificate?.certPath ?? null,
2951
+ coverage,
2952
+ activity,
2953
+ loadSeed,
2398
2954
  reset,
2399
- close: () => new Promise((resolve2, reject) => {
2400
- server.closeAllConnections();
2401
- server.close((error) => error ? reject(error) : resolve2());
2402
- })
2955
+ close
2403
2956
  };
2404
2957
  }
2405
2958
  async function handle(req, res, context) {
2406
- const { testkit, auth, seed, failures, webhooks } = context;
2959
+ const { testkit, auth, seed, failures, webhooks, coverage } = context;
2407
2960
  const url = new URL(req.url ?? "/", "http://localhost");
2408
2961
  const { pathname } = url;
2409
2962
  const method = req.method ?? "GET";
2410
- if (!pathname.startsWith("/testkit/")) {
2963
+ const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
2964
+ let injected = false;
2965
+ if (!internal && pathname !== "/favicon.ico") {
2966
+ const started = Date.now();
2967
+ res.once("close", () => {
2968
+ context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
2969
+ });
2970
+ }
2971
+ if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
2972
+ if (!internal) {
2411
2973
  const failure = failures.take(method, pathname);
2412
2974
  if (failure) {
2975
+ injected = true;
2976
+ if (failure.hang) coverage.hit("outage.timeout");
2977
+ else if (failure.status === 429) coverage.hit("outage.rate-limit");
2978
+ else if (failure.status !== null) coverage.hit("outage.error");
2979
+ if (failure.delayMs > 0) coverage.hit("outage.slow");
2413
2980
  if (failure.hang) return;
2414
- if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
2981
+ if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
2415
2982
  if (failure.status !== null) {
2416
2983
  const headers = {};
2417
2984
  if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
@@ -2420,8 +2987,15 @@ async function handle(req, res, context) {
2420
2987
  }
2421
2988
  }
2422
2989
  if (await auth.handle(req, res, url, () => readForm(req))) return;
2423
- if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
2424
- if (await context.account.handle(req, res, url)) return;
2990
+ if (await context.management.handle(req, res, url, async () => await readJson(req))) {
2991
+ if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
2992
+ else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
2993
+ return;
2994
+ }
2995
+ if (await context.account.handle(req, res, url)) {
2996
+ if (res.statusCode < 400) coverage.hit("api.account");
2997
+ return;
2998
+ }
2425
2999
  if (method === "GET" && pathname === "/testkit/portal") {
2426
3000
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2427
3001
  res.end(
@@ -2478,11 +3052,119 @@ async function handle(req, res, context) {
2478
3052
  }
2479
3053
  if (method === "POST" && pathname === "/testkit/token") {
2480
3054
  const body = await readJson(req);
2481
- const accessToken = await issueToken(testkit, seed, body);
3055
+ let accessToken;
3056
+ try {
3057
+ accessToken = await issueToken(testkit, seed, body);
3058
+ } catch (error) {
3059
+ if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
3060
+ throw error;
3061
+ }
2482
3062
  return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
2483
3063
  }
3064
+ if (method === "GET" && pathname === "/testkit/coverage") {
3065
+ return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
3066
+ }
3067
+ if (method === "DELETE" && pathname === "/testkit/coverage") {
3068
+ coverage.reset();
3069
+ return sendJson4(res, 200, { ok: true });
3070
+ }
3071
+ if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
3072
+ if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
3073
+ if (method === "POST" && pathname === "/testkit/seed") {
3074
+ const body = await readJson(req);
3075
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
3076
+ throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
3077
+ }
3078
+ context.loadSeed(body);
3079
+ return sendJson4(res, 200, {
3080
+ ok: true,
3081
+ users: seed.users.length,
3082
+ organizations: seed.organizations.length,
3083
+ memberships: seed.memberships.length
3084
+ });
3085
+ }
3086
+ if (method === "POST" && pathname === "/testkit/stop") {
3087
+ sendJson4(res, 200, { ok: true });
3088
+ res.once("finish", () => void context.close().catch(() => void 0));
3089
+ return;
3090
+ }
2484
3091
  return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
2485
3092
  }
3093
+ async function dashboard(req, res, url, context) {
3094
+ const method = req.method ?? "GET";
3095
+ const { pathname } = url;
3096
+ if (method === "GET" && pathname === "/dashboard") {
3097
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
3098
+ res.end(
3099
+ renderDashboard({
3100
+ issuer: context.testkit.issuer,
3101
+ seed: context.seed,
3102
+ suspended: (id) => context.directory.isSuspended(id),
3103
+ signIns: (id) => {
3104
+ const user = context.directory.user(id);
3105
+ return user ? context.directory.meta(user).totalSignIns : 0;
3106
+ },
3107
+ tokens: context.activity.tokens(),
3108
+ requests: context.activity.requests(),
3109
+ deliveries: context.webhooks.deliveries(),
3110
+ endpoints: context.webhooks.listEndpoints(),
3111
+ failures: context.failures.list(),
3112
+ coverage: context.coverage.report(),
3113
+ webhookTypes: WEBHOOK_EVENT_TYPES,
3114
+ live: url.searchParams.has("live"),
3115
+ notice: url.searchParams.get("notice")
3116
+ })
3117
+ );
3118
+ return;
3119
+ }
3120
+ if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
3121
+ const origin = req.headers.origin;
3122
+ if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
3123
+ return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
3124
+ }
3125
+ const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
3126
+ let notice = "Done.";
3127
+ try {
3128
+ if (pathname === "/dashboard/reset") {
3129
+ context.reset();
3130
+ notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
3131
+ } else if (pathname === "/dashboard/coverage/reset") {
3132
+ context.coverage.reset();
3133
+ notice = "Cleared coverage.";
3134
+ } else if (pathname === "/dashboard/failures/clear") {
3135
+ context.failures.clear();
3136
+ notice = "Removed every failure rule.";
3137
+ } else if (pathname === "/dashboard/failures") {
3138
+ const rule = { path: form2.path ?? "" };
3139
+ if (form2.method) rule.method = form2.method;
3140
+ if (form2.status) rule.status = Number(form2.status);
3141
+ if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
3142
+ if (form2.times) rule.times = Number(form2.times);
3143
+ if (form2.hang) rule.hang = true;
3144
+ const added = context.failures.add(rule);
3145
+ notice = `Added ${added.id} for ${added.path}.`;
3146
+ } else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
3147
+ const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
3148
+ notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
3149
+ } else if (pathname === "/dashboard/webhooks") {
3150
+ const deliveries = await context.webhooks.send({
3151
+ type: form2.type ?? "",
3152
+ user: form2.user || void 0,
3153
+ invalid: form2.invalid || void 0,
3154
+ duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
3155
+ });
3156
+ const delivered = deliveries.filter((d) => d.delivered).length;
3157
+ notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
3158
+ } else {
3159
+ return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
3160
+ }
3161
+ } catch (error) {
3162
+ notice = error.message.replace(/\s+/g, " ").trim();
3163
+ }
3164
+ const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
3165
+ res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
3166
+ res.end();
3167
+ }
2486
3168
  function discovery(testkit) {
2487
3169
  const base = testkit.issuer;
2488
3170
  return {
@@ -2632,7 +3314,7 @@ function sendError(res, error) {
2632
3314
  });
2633
3315
  }
2634
3316
 
2635
- // src/vitest.ts
3317
+ // src/handle.ts
2636
3318
  async function kindeTest(options) {
2637
3319
  const testkit = options.testkit ?? await getDefaultTestkit();
2638
3320
  const token = await testkit.tokenFor(options.scenario, options.token);
@@ -2644,17 +3326,17 @@ async function kindeTest(options) {
2644
3326
  request: { headers }
2645
3327
  };
2646
3328
  }
2647
- function useKindeTestkit(options = {}) {
3329
+ function createKindeTestkitHandle(hooks, options, name) {
2648
3330
  let running = null;
2649
- beforeAll(async () => {
3331
+ hooks.beforeAll(async () => {
2650
3332
  running = await startKindeTestkit({ port: 0, ...options });
2651
3333
  });
2652
- afterAll(async () => {
3334
+ hooks.afterAll(async () => {
2653
3335
  await running?.close();
2654
3336
  running = null;
2655
3337
  });
2656
3338
  const current = () => {
2657
- if (!running) throw new Error("useKindeTestkit() is only ready inside tests and hooks, after beforeAll runs.");
3339
+ if (!running) throw new Error(`${name}() is only ready inside tests and hooks, after beforeAll runs.`);
2658
3340
  return running;
2659
3341
  };
2660
3342
  return {
@@ -2676,10 +3358,28 @@ function useKindeTestkit(options = {}) {
2676
3358
  get webhooks() {
2677
3359
  return current().webhooks;
2678
3360
  },
3361
+ get directory() {
3362
+ return current().directory;
3363
+ },
3364
+ get coverage() {
3365
+ return current().coverage;
3366
+ },
3367
+ get activity() {
3368
+ return current().activity;
3369
+ },
3370
+ get certificatePath() {
3371
+ return current().certificatePath;
3372
+ },
2679
3373
  auth: (scenario, token) => kindeTest({ scenario, testkit: current().testkit, token }),
3374
+ loadSeed: (seed) => current().loadSeed(seed),
2680
3375
  reset: () => current().reset()
2681
3376
  };
2682
3377
  }
3378
+
3379
+ // src/vitest.ts
3380
+ function useKindeTestkit(options = {}) {
3381
+ return createKindeTestkitHandle({ beforeAll, afterAll }, options, "useKindeTestkit");
3382
+ }
2683
3383
  export {
2684
3384
  kindeTest,
2685
3385
  useKindeTestkit