kinde-testkit 0.2.1 → 0.3.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
@@ -118,6 +118,7 @@ function invalid(value) {
118
118
  // src/testkit.ts
119
119
  var DEFAULT_ISSUER = "http://localhost:4400";
120
120
  var DEFAULT_CLIENT_ID = "kinde_testkit_client";
121
+ var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
121
122
  var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
122
123
  var DEFAULT_AUTH_METHODS = ["email"];
123
124
  var INVALID_TOKEN_KINDS = [
@@ -196,6 +197,27 @@ var KindeTestkit = class _KindeTestkit {
196
197
  Object.assign(payload, options.claims ?? {});
197
198
  return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
198
199
  }
200
+ async m2mToken(options = {}) {
201
+ const now = this.clock();
202
+ const requested = [...options.scopes ?? []];
203
+ const granted = [...options.grantedScopes ?? requested];
204
+ const payload = {
205
+ aud: [...options.audience ?? this.audience],
206
+ azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
207
+ exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
208
+ gty: ["client_credentials"],
209
+ iat: now,
210
+ iss: this.issuer,
211
+ jti: randomUUID(),
212
+ scope: granted.join(" "),
213
+ scp: requested,
214
+ v: "2"
215
+ };
216
+ if (options.organizationCode) payload.org_code = options.organizationCode;
217
+ if (options.permissions !== void 0) payload.permissions = [...options.permissions];
218
+ Object.assign(payload, options.claims ?? {});
219
+ return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
220
+ }
199
221
  async tokenFor(scenario, overrides = {}) {
200
222
  if (scenario.kind === "unauthenticated") return null;
201
223
  return this.token({
@@ -265,6 +287,7 @@ var KindeTestkit = class _KindeTestkit {
265
287
  };
266
288
  function scenarioPrincipal(scenario, issuer) {
267
289
  return {
290
+ type: "user",
268
291
  subject: scenario.user.id,
269
292
  issuer,
270
293
  organization: scenario.organization ? { code: scenario.organization.code } : null,
@@ -341,6 +364,7 @@ function resolveSeed(input) {
341
364
  const rawUsers = listOf(input.users, "users", problems);
342
365
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
343
366
  const rawMemberships = listOf(input.memberships, "memberships", problems);
367
+ const rawApplications = listOf(input.applications, "applications", problems);
344
368
  const users = [];
345
369
  rawUsers.forEach((raw, index) => {
346
370
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -396,10 +420,43 @@ function resolveSeed(input) {
396
420
  })
397
421
  );
398
422
  });
423
+ const applications = [];
424
+ rawApplications.forEach((raw, index) => {
425
+ if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
426
+ problems.push(`applications[${index}] needs a string "clientId".`);
427
+ return;
428
+ }
429
+ if (applications.some((app) => app.clientId === raw.clientId)) {
430
+ problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
431
+ return;
432
+ }
433
+ if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
434
+ problems.push(`applications[${index}].clientSecret must be a string.`);
435
+ }
436
+ if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
437
+ problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
438
+ }
439
+ for (const field of ["scopes", "permissions"]) {
440
+ const value = raw[field];
441
+ if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
442
+ problems.push(`applications[${index}].${field} must be a list of strings.`);
443
+ }
444
+ }
445
+ const audience = raw.audience;
446
+ applications.push({
447
+ clientId: raw.clientId,
448
+ clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
449
+ name: typeof raw.name === "string" ? raw.name : raw.clientId,
450
+ organizationCode: typeof raw.organization === "string" ? raw.organization : null,
451
+ scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
452
+ permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
453
+ audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
454
+ });
455
+ });
399
456
  if (problems.length > 0) {
400
457
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
401
458
  }
402
- return { users, organizations, memberships };
459
+ return { users, organizations, memberships, applications };
403
460
  }
404
461
  function findUser(users, ref) {
405
462
  const needle = ref.toLowerCase();
@@ -668,13 +725,16 @@ var AuthorizationServer = class {
668
725
  try {
669
726
  const clientId = clientIdFrom(req, form);
670
727
  const grantType = form.grant_type;
728
+ if (grantType === "client_credentials") {
729
+ return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
730
+ }
671
731
  let grant;
672
732
  if (grantType === "authorization_code") {
673
733
  grant = this.redeemCode(form, clientId);
674
734
  } else if (grantType === "refresh_token") {
675
735
  grant = this.redeemRefreshToken(form, clientId);
676
736
  } else {
677
- throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and refresh_token, not "${grantType ?? ""}".`);
737
+ throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
678
738
  }
679
739
  sendJson(res, 200, await this.issueTokens(grant));
680
740
  } catch (error) {
@@ -684,6 +744,33 @@ var AuthorizationServer = class {
684
744
  throw error;
685
745
  }
686
746
  }
747
+ async clientCredentials(clientId, clientSecret, form) {
748
+ const app = this.seed.applications.find((a) => a.clientId === clientId);
749
+ if (app?.clientSecret && app.clientSecret !== clientSecret) {
750
+ throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
751
+ }
752
+ const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
753
+ const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
754
+ const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
755
+ return {
756
+ access_token: await this.testkit.m2mToken({
757
+ clientId,
758
+ organizationCode: app?.organizationCode ?? null,
759
+ scopes: requested,
760
+ grantedScopes: granted,
761
+ audience: audience.length > 0 ? audience : app?.audience ?? void 0,
762
+ permissions: app?.permissions ?? void 0
763
+ }),
764
+ expires_in: this.testkit.accessTokenLifetime,
765
+ scope: granted.join(" "),
766
+ token_type: "bearer"
767
+ };
768
+ }
769
+ reset() {
770
+ this.codes.clear();
771
+ this.refreshTokens.clear();
772
+ this.signedUpUsers.clear();
773
+ }
687
774
  redeemCode(form, clientId) {
688
775
  const code = form.code ?? "";
689
776
  const pending = this.codes.get(code);
@@ -855,6 +942,15 @@ function clientIdFrom(req, form) {
855
942
  if (form.client_id) return form.client_id;
856
943
  throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
857
944
  }
945
+ function clientSecretFrom(req, form) {
946
+ const header = req.headers.authorization ?? "";
947
+ if (header.startsWith("Basic ")) {
948
+ const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
949
+ const index = decoded.indexOf(":");
950
+ if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
951
+ }
952
+ return form.client_secret ?? null;
953
+ }
858
954
  function redirectWithError(res, request2, error, description) {
859
955
  const target = new URL(request2.redirectUri);
860
956
  target.searchParams.set("error", error);
@@ -895,6 +991,86 @@ function sendJson(res, status, body) {
895
991
  res.end(JSON.stringify(body));
896
992
  }
897
993
 
994
+ // src/failures.ts
995
+ var MAX_DELAY_MS = 6e4;
996
+ var FailureInjector = class {
997
+ rules = [];
998
+ nextId = 1;
999
+ add(rule) {
1000
+ const problems = validate(rule);
1001
+ if (problems.length > 0) {
1002
+ throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
1003
+ }
1004
+ const active = {
1005
+ id: `failure_${this.nextId++}`,
1006
+ path: rule.path,
1007
+ method: rule.method ? rule.method.toUpperCase() : null,
1008
+ status: rule.status ?? null,
1009
+ delayMs: rule.delayMs ?? 0,
1010
+ hang: rule.hang ?? false,
1011
+ remaining: rule.times ?? null,
1012
+ retryAfter: rule.retryAfter ?? 1,
1013
+ hits: 0
1014
+ };
1015
+ this.rules.push(active);
1016
+ return { ...active };
1017
+ }
1018
+ remove(id) {
1019
+ const before = this.rules.length;
1020
+ this.rules = this.rules.filter((rule) => rule.id !== id);
1021
+ return this.rules.length < before;
1022
+ }
1023
+ clear() {
1024
+ this.rules = [];
1025
+ }
1026
+ list() {
1027
+ return this.rules.map((rule) => ({ ...rule }));
1028
+ }
1029
+ take(method, path) {
1030
+ const rule = this.rules.find((r) => matches(r, method, path));
1031
+ if (!rule) return null;
1032
+ rule.hits += 1;
1033
+ if (rule.remaining !== null) {
1034
+ rule.remaining -= 1;
1035
+ if (rule.remaining <= 0) this.remove(rule.id);
1036
+ }
1037
+ return { ...rule };
1038
+ }
1039
+ };
1040
+ function failureBody(status) {
1041
+ const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
1042
+ return { error, error_description: `kinde-testkit injected a ${status} response.` };
1043
+ }
1044
+ function matches(rule, method, path) {
1045
+ if (rule.method && rule.method !== method.toUpperCase()) return false;
1046
+ if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
1047
+ return rule.path === path;
1048
+ }
1049
+ function validate(rule) {
1050
+ const problems = [];
1051
+ if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
1052
+ problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
1053
+ } else if (rule.path.startsWith("/testkit/")) {
1054
+ problems.push("Failures cannot target /testkit/ control endpoints.");
1055
+ }
1056
+ if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
1057
+ problems.push('"status" must be an HTTP error status between 400 and 599.');
1058
+ }
1059
+ if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
1060
+ problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
1061
+ }
1062
+ if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
1063
+ problems.push('"times" must be a whole number of 1 or more.');
1064
+ }
1065
+ if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
1066
+ problems.push('"retryAfter" must be a whole number of seconds.');
1067
+ }
1068
+ if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
1069
+ problems.push('Set at least one of "status", "delayMs" or "hang".');
1070
+ }
1071
+ return problems;
1072
+ }
1073
+
898
1074
  // src/server.ts
899
1075
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
900
1076
  var MAX_BODY_BYTES = 64 * 1024;
@@ -908,12 +1084,11 @@ async function startKindeTestkit(options = {}) {
908
1084
  );
909
1085
  }
910
1086
  const seed = resolveSeed(options.seed ?? {});
1087
+ const failures = new FailureInjector();
911
1088
  let ready;
912
- const testkitReady = new Promise(
913
- (resolve2) => ready = resolve2
914
- );
1089
+ const testkitReady = new Promise((resolve2) => ready = resolve2);
915
1090
  const server = createServer((req, res) => {
916
- testkitReady.then(({ testkit: testkit2, auth }) => handle(req, res, testkit2, auth, seed)).catch((error) => sendError(res, error));
1091
+ testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
917
1092
  });
918
1093
  await new Promise((resolve2, reject) => {
919
1094
  server.once("error", reject);
@@ -927,7 +1102,12 @@ async function startKindeTestkit(options = {}) {
927
1102
  audience: options.audience ?? options.seed?.audience,
928
1103
  clientId: options.clientId ?? options.seed?.clientId
929
1104
  });
930
- ready({ testkit, auth: new AuthorizationServer(testkit, seed) });
1105
+ const auth = new AuthorizationServer(testkit, seed);
1106
+ const reset2 = () => {
1107
+ auth.reset();
1108
+ failures.clear();
1109
+ };
1110
+ ready({ testkit, auth, seed, failures, reset: reset2 });
931
1111
  return {
932
1112
  url,
933
1113
  issuer: testkit.issuer,
@@ -935,16 +1115,31 @@ async function startKindeTestkit(options = {}) {
935
1115
  jwksUri: `${url}/.well-known/jwks`,
936
1116
  testkit,
937
1117
  seed,
1118
+ failures,
1119
+ reset: reset2,
938
1120
  close: () => new Promise((resolve2, reject) => {
939
1121
  server.closeAllConnections();
940
1122
  server.close((error) => error ? reject(error) : resolve2());
941
1123
  })
942
1124
  };
943
1125
  }
944
- async function handle(req, res, testkit, auth, seed) {
1126
+ async function handle(req, res, context) {
1127
+ const { testkit, auth, seed, failures } = context;
945
1128
  const url = new URL(req.url ?? "/", "http://localhost");
946
1129
  const { pathname } = url;
947
1130
  const method = req.method ?? "GET";
1131
+ if (!pathname.startsWith("/testkit/")) {
1132
+ const failure = failures.take(method, pathname);
1133
+ if (failure) {
1134
+ if (failure.hang) return;
1135
+ if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
1136
+ if (failure.status !== null) {
1137
+ const headers = {};
1138
+ if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
1139
+ return sendJson2(res, failure.status, failureBody(failure.status), headers);
1140
+ }
1141
+ }
1142
+ }
948
1143
  if (await auth.handle(req, res, url, () => readForm(req))) return;
949
1144
  if (method === "GET" && pathname === "/.well-known/openid-configuration") {
950
1145
  return sendJson2(res, 200, discovery(testkit));
@@ -962,6 +1157,22 @@ async function handle(req, res, testkit, auth, seed) {
962
1157
  if (method === "GET" && pathname === "/testkit/memberships") {
963
1158
  return sendJson2(res, 200, seed.memberships);
964
1159
  }
1160
+ if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
1161
+ if (method === "POST" && pathname === "/testkit/failures") {
1162
+ return sendJson2(res, 201, failures.add(await readJson(req)));
1163
+ }
1164
+ if (method === "DELETE" && pathname === "/testkit/failures") {
1165
+ failures.clear();
1166
+ return sendJson2(res, 200, { ok: true });
1167
+ }
1168
+ if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
1169
+ const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1170
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1171
+ }
1172
+ if (method === "POST" && pathname === "/testkit/reset") {
1173
+ context.reset();
1174
+ return sendJson2(res, 200, { ok: true });
1175
+ }
965
1176
  if (method === "POST" && pathname === "/testkit/token") {
966
1177
  const body = await readJson(req);
967
1178
  const accessToken = await issueToken(testkit, seed, body);
@@ -1001,6 +1212,21 @@ async function issueToken(testkit, seed, body) {
1001
1212
  ]);
1002
1213
  }
1003
1214
  const expiresIn = input.expiresIn;
1215
+ if (input.m2m === true) {
1216
+ const clientId = optionalString(input, "clientId");
1217
+ const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
1218
+ const scopes = optionalStrings(input, "scopes") ?? [];
1219
+ return testkit.m2mToken({
1220
+ clientId,
1221
+ organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
1222
+ scopes,
1223
+ grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
1224
+ audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
1225
+ permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
1226
+ expiresIn,
1227
+ invalid: invalid2
1228
+ });
1229
+ }
1004
1230
  const permissions = optionalStrings(input, "permissions");
1005
1231
  const roles = optionalStrings(input, "roles");
1006
1232
  const userRef = optionalString(input, "user");
@@ -1076,10 +1302,11 @@ async function readText(req) {
1076
1302
  }
1077
1303
  return Buffer.concat(chunks).toString("utf8").trim();
1078
1304
  }
1079
- function sendJson2(res, status, body) {
1305
+ function sendJson2(res, status, body, headers = {}) {
1080
1306
  res.writeHead(status, {
1081
1307
  "content-type": "application/json; charset=utf-8",
1082
- "cache-control": "no-store"
1308
+ "cache-control": "no-store",
1309
+ ...headers
1083
1310
  });
1084
1311
  res.end(JSON.stringify(body));
1085
1312
  }
@@ -1098,6 +1325,173 @@ function sendError(res, error) {
1098
1325
  });
1099
1326
  }
1100
1327
 
1328
+ // src/inspect.ts
1329
+ import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, jwtVerify as jwtVerify2 } from "jose";
1330
+ async function inspectToken(token2, options = {}) {
1331
+ const checks = [];
1332
+ const trimmed = token2.trim();
1333
+ let header = null;
1334
+ let payload = null;
1335
+ if (trimmed.split(".").length !== 3) {
1336
+ checks.push({ name: "Format", status: "fail", detail: "A JWT has three parts separated by dots." });
1337
+ return { kind: "unknown", header, payload, checks };
1338
+ }
1339
+ try {
1340
+ header = decodeProtectedHeader(trimmed);
1341
+ payload = decodeJwt(trimmed);
1342
+ } catch {
1343
+ checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
1344
+ return { kind: "unknown", header, payload, checks };
1345
+ }
1346
+ checks.push({ name: "Format", status: "pass", detail: "Three base64url parts with JSON header and payload." });
1347
+ checks.push(
1348
+ header.alg === "RS256" ? { name: "Algorithm", status: "pass", detail: "RS256, the algorithm Kinde signs with." } : { name: "Algorithm", status: "fail", detail: `${String(header.alg)} is not RS256. Kinde tokens are always RS256.` }
1349
+ );
1350
+ const signer = typeof header.kid === "string" && header.kid.startsWith("kinde-testkit") ? "kinde-testkit" : "another issuer";
1351
+ checks.push({ name: "Key", status: "pass", detail: `kid ${String(header.kid ?? "missing")} (${signer}).` });
1352
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
1353
+ if (typeof payload.exp !== "number") {
1354
+ checks.push({ name: "Expiry", status: "fail", detail: "No exp claim." });
1355
+ } else if (payload.exp <= now) {
1356
+ checks.push({ name: "Expiry", status: "fail", detail: `Expired ${formatSpan(now - payload.exp)} ago.` });
1357
+ } else {
1358
+ checks.push({ name: "Expiry", status: "pass", detail: `Expires in ${formatSpan(payload.exp - now)}.` });
1359
+ }
1360
+ if (typeof payload.iat === "number" && payload.iat > now + 60) {
1361
+ checks.push({ name: "Issued at", status: "fail", detail: `iat is ${formatSpan(payload.iat - now)} in the future.` });
1362
+ }
1363
+ if (options.issuerUrl) {
1364
+ const issuer = options.issuerUrl.replace(/\/+$/, "");
1365
+ if (payload.iss !== issuer) {
1366
+ checks.push({ name: "Issuer", status: "fail", detail: `iss is ${String(payload.iss)}, not ${issuer}.` });
1367
+ } else {
1368
+ checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
1369
+ }
1370
+ try {
1371
+ await jwtVerify2(trimmed, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
1372
+ checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
1373
+ } catch (error) {
1374
+ const code = error.code ?? "";
1375
+ if (code === "ERR_JWT_EXPIRED" || code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
1376
+ checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
1377
+ } else {
1378
+ checks.push({ name: "Signature", status: "fail", detail: describeVerifyError(code, issuer) });
1379
+ }
1380
+ }
1381
+ } else {
1382
+ checks.push({ name: "Signature", status: "warn", detail: "Not checked. Pass --url to verify against a running issuer." });
1383
+ }
1384
+ return { kind: kindOf(payload), header, payload, checks };
1385
+ }
1386
+ function kindOf(payload) {
1387
+ if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) return "m2m";
1388
+ if ("email" in payload || "org_codes" in payload || "at_hash" in payload || "nonce" in payload) return "id";
1389
+ if ("scp" in payload || "permissions" in payload || "org_code" in payload) return "access";
1390
+ return "unknown";
1391
+ }
1392
+ function describeVerifyError(code, issuer) {
1393
+ if (code === "ERR_JWKS_NO_MATCHING_KEY") return `No key in ${issuer}'s JWKS matches this token's kid.`;
1394
+ if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "The signature does not match the token. It was changed after signing.";
1395
+ if (code === "ERR_JOSE_ALG_NOT_ALLOWED" || code === "ERR_JOSE_NOT_SUPPORTED") return "The token is not signed with RS256.";
1396
+ if (code === "ERR_JWKS_TIMEOUT" || code === "ERR_JOSE_GENERIC") return `Could not fetch keys from ${issuer}.`;
1397
+ return `Verification failed (${code || "unknown error"}).`;
1398
+ }
1399
+ function formatSpan(seconds) {
1400
+ const s = Math.max(0, Math.round(seconds));
1401
+ if (s < 60) return `${s}s`;
1402
+ if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
1403
+ if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor(s % 3600 / 60)}m`;
1404
+ return `${Math.floor(s / 86400)}d ${Math.floor(s % 86400 / 3600)}h`;
1405
+ }
1406
+
1407
+ // src/doctor.ts
1408
+ var SECRET_FORMAT = /^[a-zA-Z0-9]{40,60}$/;
1409
+ async function runDoctor(options) {
1410
+ const url = options.url.replace(/\/+$/, "");
1411
+ const checks = [];
1412
+ let issuer = null;
1413
+ try {
1414
+ const health = await (await fetch(`${url}/testkit/health`)).json();
1415
+ issuer = health.issuer ?? null;
1416
+ checks.push({ name: "Issuer running", status: "pass", detail: `${url} answers, issuer ${issuer}.` });
1417
+ } catch {
1418
+ checks.push({ name: "Issuer running", status: "fail", detail: `Nothing answers at ${url}. Start it with "kinde-testkit start".` });
1419
+ }
1420
+ if (issuer) {
1421
+ try {
1422
+ const discovery2 = await (await fetch(`${url}/.well-known/openid-configuration`)).json();
1423
+ checks.push(
1424
+ discovery2.issuer === issuer ? { name: "Discovery", status: "pass", detail: "The discovery document names the same issuer." } : { name: "Discovery", status: "fail", detail: `Discovery says ${String(discovery2.issuer)}, health says ${issuer}.` }
1425
+ );
1426
+ } catch {
1427
+ checks.push({ name: "Discovery", status: "fail", detail: "Could not read /.well-known/openid-configuration." });
1428
+ }
1429
+ try {
1430
+ const jwks = await (await fetch(`${url}/.well-known/jwks.json`)).json();
1431
+ const usable = (jwks.keys ?? []).filter((key) => key.kty === "RSA" && key.use === "sig");
1432
+ checks.push(
1433
+ usable.length > 0 ? { name: "JWKS", status: "pass", detail: `${usable.length} RS256 signing key at /.well-known/jwks.json.` } : { name: "JWKS", status: "fail", detail: "No RSA signing key at /.well-known/jwks.json." }
1434
+ );
1435
+ } catch {
1436
+ checks.push({ name: "JWKS", status: "fail", detail: "Could not read /.well-known/jwks.json." });
1437
+ }
1438
+ try {
1439
+ const users = await (await fetch(`${url}/testkit/users`)).json();
1440
+ checks.push(
1441
+ users.length > 0 ? { name: "Seed", status: "pass", detail: `${users.length} seeded ${users.length === 1 ? "user" : "users"}.` } : { name: "Seed", status: "warn", detail: "No seeded users. The sign-in page still accepts any email, but those users have no organization." }
1442
+ );
1443
+ } catch {
1444
+ checks.push({ name: "Seed", status: "warn", detail: "Could not read /testkit/users." });
1445
+ }
1446
+ }
1447
+ const env = options.env;
1448
+ const configured = env.KINDE_ISSUER_URL?.trim().replace(/\/+$/, "");
1449
+ if (!configured) {
1450
+ checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: "Not set. Set it to the testkit's issuer for test runs." });
1451
+ } else if (/\.kinde\.com$/i.test(new URL(configured, "http://x").hostname)) {
1452
+ checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} is a real Kinde domain. Tests would sign in against Kinde, not the testkit.` });
1453
+ } else if (issuer && configured !== issuer) {
1454
+ checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} does not match the testkit issuer ${issuer}. Token checks compare iss exactly.` });
1455
+ } else {
1456
+ checks.push({ name: "KINDE_ISSUER_URL", status: "pass", detail: `${configured}.` });
1457
+ }
1458
+ checks.push(
1459
+ env.KINDE_CLIENT_ID ? { name: "KINDE_CLIENT_ID", status: "pass", detail: "Set. The testkit accepts any client ID." } : { name: "KINDE_CLIENT_ID", status: "fail", detail: "Not set. Kinde's SDKs refuse to start without it." }
1460
+ );
1461
+ const secret = env.KINDE_CLIENT_SECRET;
1462
+ if (!secret) {
1463
+ checks.push({ name: "KINDE_CLIENT_SECRET", status: "warn", detail: "Not set. Server-side SDKs, such as the Next.js SDK, need it." });
1464
+ } else if (!SECRET_FORMAT.test(secret)) {
1465
+ checks.push({ name: "KINDE_CLIENT_SECRET", status: "fail", detail: "The Next.js SDK only accepts 40 to 60 letters and digits." });
1466
+ } else {
1467
+ checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
1468
+ }
1469
+ const site = env.KINDE_SITE_URL;
1470
+ if (!site) {
1471
+ checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
1472
+ } else if (!/^https?:\/\//.test(site)) {
1473
+ checks.push({ name: "KINDE_SITE_URL", status: "fail", detail: `${site} is not an http or https URL.` });
1474
+ } else {
1475
+ checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
1476
+ }
1477
+ return { url, checks, ok: checks.every((check) => check.status !== "fail") };
1478
+ }
1479
+ function parseEnvFile(text) {
1480
+ const values = {};
1481
+ for (const line of text.split(/\r?\n/)) {
1482
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
1483
+ if (!match) continue;
1484
+ let value = match[2];
1485
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1486
+ value = value.slice(1, -1);
1487
+ } else {
1488
+ value = value.replace(/\s+#.*$/, "");
1489
+ }
1490
+ values[match[1]] = value;
1491
+ }
1492
+ return values;
1493
+ }
1494
+
1101
1495
  // src/cli.ts
1102
1496
  var DEFAULT_URL = process.env.KINDE_TESTKIT_URL ?? "http://localhost:4400";
1103
1497
  var DEFAULT_SEED_FILE = "kinde-testkit.json";
@@ -1108,6 +1502,10 @@ Usage
1108
1502
  kinde-testkit token [options] Print a signed test access token
1109
1503
  kinde-testkit users [--json] List seeded users
1110
1504
  kinde-testkit organizations [--json] List seeded organizations
1505
+ kinde-testkit inspect [token] Decode a token and check it (reads stdin when no token)
1506
+ kinde-testkit doctor [options] Check your app's Kinde settings against the issuer
1507
+ kinde-testkit fail <path> [options] Make an endpoint fail, slow down or hang
1508
+ kinde-testkit reset Clear sign-in sessions and failure rules
1111
1509
 
1112
1510
  start
1113
1511
  --port <n> Port to listen on (default 4400)
@@ -1129,7 +1527,29 @@ token
1129
1527
  --invalid <kind> expired, wrong-issuer, wrong-audience, missing-subject,
1130
1528
  missing-organization, missing-permissions, future-iat,
1131
1529
  bad-signature, unknown-key, unsigned
1530
+ --m2m Machine-to-machine token (client_credentials shape)
1531
+ --client-id <id> M2M client ID, matched against seeded applications
1532
+ --scope <a,b> M2M scopes requested
1132
1533
  --json Print JSON instead of the raw token
1534
+
1535
+ inspect
1536
+ --url <url> Also verify the issuer and signature against a running issuer
1537
+ --json Print JSON
1538
+
1539
+ doctor
1540
+ --url <url> Running issuer (default ${DEFAULT_URL})
1541
+ --env-file <file> Read settings from this file (repeatable). Defaults to .env,
1542
+ .env.local, .env.test and .env.test.local when they exist
1543
+ --json Print JSON
1544
+
1545
+ fail <path> An exact path such as /oauth2/token, or a prefix such as /oauth2/*
1546
+ --status <code> Answer with this status, such as 429, 500 or 503
1547
+ --delay <ms> Wait before answering
1548
+ --hang Never answer
1549
+ --times <n> Apply to the next n requests only
1550
+ --method <verb> Only match this method
1551
+ --list Show active rules
1552
+ --clear Remove all rules
1133
1553
  `;
1134
1554
  async function main(argv) {
1135
1555
  const [command, ...rest] = argv;
@@ -1143,6 +1563,14 @@ async function main(argv) {
1143
1563
  case "organizations":
1144
1564
  case "orgs":
1145
1565
  return list(rest, "organizations");
1566
+ case "inspect":
1567
+ return inspect(rest);
1568
+ case "doctor":
1569
+ return doctor(rest);
1570
+ case "fail":
1571
+ return fail(rest);
1572
+ case "reset":
1573
+ return reset(rest);
1146
1574
  case void 0:
1147
1575
  case "help":
1148
1576
  case "--help":
@@ -1231,10 +1659,21 @@ async function token(args) {
1231
1659
  roles: { type: "string" },
1232
1660
  "expires-in": { type: "string" },
1233
1661
  invalid: { type: "string" },
1662
+ m2m: { type: "boolean" },
1663
+ "client-id": { type: "string" },
1664
+ scope: { type: "string" },
1234
1665
  json: { type: "boolean" }
1235
1666
  }
1236
1667
  });
1237
- const body = {
1668
+ const body = values.m2m ? {
1669
+ m2m: true,
1670
+ clientId: values["client-id"],
1671
+ organization: values.org,
1672
+ scopes: values.scope !== void 0 ? csv(values.scope) : void 0,
1673
+ permissions: values.permissions !== void 0 ? csv(values.permissions) : void 0,
1674
+ expiresIn: values["expires-in"],
1675
+ invalid: values.invalid
1676
+ } : {
1238
1677
  user: values.user,
1239
1678
  organization: values.org,
1240
1679
  subject: values.sub,
@@ -1253,6 +1692,157 @@ async function token(args) {
1253
1692
  ` : `${accessToken}
1254
1693
  `);
1255
1694
  }
1695
+ async function inspect(args) {
1696
+ const { values, positionals } = parseArgs({
1697
+ args,
1698
+ allowPositionals: true,
1699
+ options: { url: { type: "string" }, json: { type: "boolean" } }
1700
+ });
1701
+ const raw = positionals[0] ?? (process.stdin.isTTY ? "" : await readStdin());
1702
+ const token2 = raw.trim().replace(/^Bearer\s+/i, "");
1703
+ if (!token2) {
1704
+ throw new TestkitError("INVALID_REQUEST", "Pass a token, or pipe one in: kinde-testkit token | kinde-testkit inspect");
1705
+ }
1706
+ const result = await inspectToken(token2, { issuerUrl: values.url });
1707
+ if (values.json) {
1708
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
1709
+ `);
1710
+ } else {
1711
+ const lines = [`${result.kind === "m2m" ? "Machine-to-machine access token" : result.kind === "id" ? "ID token" : result.kind === "access" ? "Access token" : "Token"}`, ""];
1712
+ if (result.payload) {
1713
+ const p = result.payload;
1714
+ const show = (label, value) => {
1715
+ if (value !== void 0) lines.push(`${label.padEnd(14)} ${typeof value === "string" ? value : JSON.stringify(value)}`);
1716
+ };
1717
+ show("Subject", p.sub);
1718
+ show("Client", p.azp);
1719
+ show("Issuer", p.iss);
1720
+ show("Audience", p.aud);
1721
+ show("Organization", p.org_code ?? p.org_codes);
1722
+ show("Roles", Array.isArray(p.roles) ? p.roles.map((r) => typeof r === "string" ? r : r.key) : void 0);
1723
+ show("Permissions", p.permissions);
1724
+ show(result.kind === "m2m" ? "Requested" : "Scopes", p.scp);
1725
+ if (result.kind === "m2m") show("Granted", p.scope === "" ? "none" : p.scope);
1726
+ if (typeof p.exp === "number" && typeof p.iat === "number") show("Lifetime", formatSpan(p.exp - p.iat));
1727
+ lines.push("");
1728
+ }
1729
+ lines.push(...result.checks.map(formatCheck), "");
1730
+ process.stdout.write(lines.join("\n"));
1731
+ }
1732
+ if (result.checks.some((check) => check.status === "fail")) process.exitCode = 1;
1733
+ }
1734
+ async function doctor(args) {
1735
+ const { values } = parseArgs({
1736
+ args,
1737
+ options: {
1738
+ url: { type: "string" },
1739
+ "env-file": { type: "string", multiple: true },
1740
+ json: { type: "boolean" }
1741
+ }
1742
+ });
1743
+ const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) => existsSync(file));
1744
+ const env = {};
1745
+ for (const file of files) {
1746
+ if (!existsSync(file)) throw new TestkitError("INVALID_REQUEST", `No env file at ${resolve(file)}.`);
1747
+ Object.assign(env, parseEnvFile(readFileSync(file, "utf8")));
1748
+ }
1749
+ for (const [key, value] of Object.entries(process.env)) {
1750
+ if (key.startsWith("KINDE_") && value !== void 0) env[key] = value;
1751
+ }
1752
+ const report = await runDoctor({ url: values.url ?? DEFAULT_URL, env });
1753
+ if (values.json) {
1754
+ process.stdout.write(`${JSON.stringify({ ...report, envFiles: files }, null, 2)}
1755
+ `);
1756
+ } else {
1757
+ process.stdout.write(
1758
+ [
1759
+ "",
1760
+ "kinde-testkit doctor",
1761
+ "",
1762
+ `Settings read from: ${files.length > 0 ? files.join(", ") : "environment only"}`,
1763
+ "",
1764
+ ...report.checks.map(formatCheck),
1765
+ "",
1766
+ report.ok ? "Ready to test." : "Fix the failed checks above, then run doctor again.",
1767
+ ""
1768
+ ].join("\n")
1769
+ );
1770
+ }
1771
+ if (!report.ok) process.exitCode = 1;
1772
+ }
1773
+ async function fail(args) {
1774
+ const { values, positionals } = parseArgs({
1775
+ args,
1776
+ allowPositionals: true,
1777
+ options: {
1778
+ url: { type: "string" },
1779
+ status: { type: "string" },
1780
+ delay: { type: "string" },
1781
+ hang: { type: "boolean" },
1782
+ times: { type: "string" },
1783
+ method: { type: "string" },
1784
+ list: { type: "boolean" },
1785
+ clear: { type: "boolean" },
1786
+ json: { type: "boolean" }
1787
+ }
1788
+ });
1789
+ const base = values.url ?? DEFAULT_URL;
1790
+ if (values.clear) {
1791
+ await request(base, "/testkit/failures", { method: "DELETE" });
1792
+ process.stdout.write("Removed all failure rules.\n");
1793
+ return;
1794
+ }
1795
+ if (values.list || positionals.length === 0) {
1796
+ const rules = await request(base, "/testkit/failures");
1797
+ if (values.json) {
1798
+ process.stdout.write(`${JSON.stringify(rules)}
1799
+ `);
1800
+ } else if (rules.length === 0) {
1801
+ process.stdout.write("No failure rules.\n");
1802
+ } else {
1803
+ for (const rule2 of rules) process.stdout.write(`${describeRule(rule2)}
1804
+ `);
1805
+ }
1806
+ return;
1807
+ }
1808
+ const rule = await request(base, "/testkit/failures", {
1809
+ method: "POST",
1810
+ headers: { "content-type": "application/json" },
1811
+ body: JSON.stringify({
1812
+ path: positionals[0],
1813
+ method: values.method,
1814
+ status: values.status !== void 0 ? Number(values.status) : void 0,
1815
+ delayMs: values.delay !== void 0 ? Number(values.delay) : void 0,
1816
+ hang: values.hang,
1817
+ times: values.times !== void 0 ? Number(values.times) : void 0
1818
+ })
1819
+ });
1820
+ process.stdout.write(values.json ? `${JSON.stringify(rule)}
1821
+ ` : `Added ${describeRule(rule)}
1822
+ `);
1823
+ }
1824
+ async function reset(args) {
1825
+ const { values } = parseArgs({ args, options: { url: { type: "string" } } });
1826
+ await request(values.url ?? DEFAULT_URL, "/testkit/reset", { method: "POST" });
1827
+ process.stdout.write("Cleared sign-in codes, refresh tokens, signed-up users and failure rules.\n");
1828
+ }
1829
+ async function readStdin() {
1830
+ const chunks = [];
1831
+ for await (const chunk of process.stdin) chunks.push(chunk);
1832
+ return Buffer.concat(chunks).toString("utf8");
1833
+ }
1834
+ function describeRule(rule) {
1835
+ const parts = [`${String(rule.id)}: ${rule.method ? `${String(rule.method)} ` : ""}${String(rule.path)}`];
1836
+ if (rule.status !== null) parts.push(`answers ${String(rule.status)}`);
1837
+ if (rule.delayMs) parts.push(`after ${String(rule.delayMs)}ms`);
1838
+ if (rule.hang) parts.push("never answers");
1839
+ parts.push(rule.remaining === null ? "until removed" : `for the next ${String(rule.remaining)} requests`);
1840
+ return parts.join(", ");
1841
+ }
1842
+ function formatCheck(check) {
1843
+ const mark = check.status === "pass" ? "\u2713" : check.status === "warn" ? "!" : "\u2717";
1844
+ return `${mark} ${check.name.padEnd(20)} ${check.detail}`;
1845
+ }
1256
1846
  async function list(args, kind) {
1257
1847
  const { values } = parseArgs({
1258
1848
  args,