kinde-testkit 0.2.2 → 0.4.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({
@@ -249,6 +271,9 @@ var KindeTestkit = class _KindeTestkit {
249
271
  if (scenario.kind === "unauthenticated") return null;
250
272
  return scenarioPrincipal(scenario, this.issuer);
251
273
  }
274
+ async signPayload(payload, invalid2) {
275
+ return this.sign(payload, invalid2);
276
+ }
252
277
  async sign(payload, invalid2) {
253
278
  if (invalid2 === "unsigned") {
254
279
  const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
@@ -265,6 +290,7 @@ var KindeTestkit = class _KindeTestkit {
265
290
  };
266
291
  function scenarioPrincipal(scenario, issuer) {
267
292
  return {
293
+ type: "user",
268
294
  subject: scenario.user.id,
269
295
  issuer,
270
296
  organization: scenario.organization ? { code: scenario.organization.code } : null,
@@ -341,6 +367,20 @@ function resolveSeed(input) {
341
367
  const rawUsers = listOf(input.users, "users", problems);
342
368
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
343
369
  const rawMemberships = listOf(input.memberships, "memberships", problems);
370
+ const rawApplications = listOf(input.applications, "applications", problems);
371
+ const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
372
+ const webhooks = [];
373
+ rawWebhooks.forEach((raw, index) => {
374
+ if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
375
+ problems.push(`webhooks[${index}] needs an http or https "url".`);
376
+ return;
377
+ }
378
+ if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
379
+ problems.push(`webhooks[${index}].events must be a list of event type names.`);
380
+ return;
381
+ }
382
+ webhooks.push({ url: raw.url, events: raw.events });
383
+ });
344
384
  const users = [];
345
385
  rawUsers.forEach((raw, index) => {
346
386
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -396,10 +436,43 @@ function resolveSeed(input) {
396
436
  })
397
437
  );
398
438
  });
439
+ const applications = [];
440
+ rawApplications.forEach((raw, index) => {
441
+ if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
442
+ problems.push(`applications[${index}] needs a string "clientId".`);
443
+ return;
444
+ }
445
+ if (applications.some((app) => app.clientId === raw.clientId)) {
446
+ problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
447
+ return;
448
+ }
449
+ if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
450
+ problems.push(`applications[${index}].clientSecret must be a string.`);
451
+ }
452
+ if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
453
+ problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
454
+ }
455
+ for (const field of ["scopes", "permissions"]) {
456
+ const value = raw[field];
457
+ if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
458
+ problems.push(`applications[${index}].${field} must be a list of strings.`);
459
+ }
460
+ }
461
+ const audience = raw.audience;
462
+ applications.push({
463
+ clientId: raw.clientId,
464
+ clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
465
+ name: typeof raw.name === "string" ? raw.name : raw.clientId,
466
+ organizationCode: typeof raw.organization === "string" ? raw.organization : null,
467
+ scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
468
+ permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
469
+ audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
470
+ });
471
+ });
399
472
  if (problems.length > 0) {
400
473
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
401
474
  }
402
- return { users, organizations, memberships };
475
+ return { users, organizations, memberships, applications, webhooks };
403
476
  }
404
477
  function findUser(users, ref) {
405
478
  const needle = ref.toLowerCase();
@@ -536,12 +609,14 @@ var OAuthError = class extends Error {
536
609
  error;
537
610
  };
538
611
  var AuthorizationServer = class {
539
- constructor(testkit, seed) {
612
+ constructor(testkit, seed, emit = () => void 0) {
540
613
  this.testkit = testkit;
541
614
  this.seed = seed;
615
+ this.emit = emit;
542
616
  }
543
617
  testkit;
544
618
  seed;
619
+ emit;
545
620
  codes = /* @__PURE__ */ new Map();
546
621
  refreshTokens = /* @__PURE__ */ new Map();
547
622
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -659,6 +734,7 @@ var AuthorizationServer = class {
659
734
  codeChallengeMethod: request2.codeChallengeMethod,
660
735
  expiresAt: Date.now() + CODE_LIFETIME_MS
661
736
  });
737
+ this.emit("user.authenticated", user);
662
738
  const target = new URL(request2.redirectUri);
663
739
  target.searchParams.set("code", code);
664
740
  if (request2.state !== null) target.searchParams.set("state", request2.state);
@@ -668,13 +744,16 @@ var AuthorizationServer = class {
668
744
  try {
669
745
  const clientId = clientIdFrom(req, form);
670
746
  const grantType = form.grant_type;
747
+ if (grantType === "client_credentials") {
748
+ return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
749
+ }
671
750
  let grant;
672
751
  if (grantType === "authorization_code") {
673
752
  grant = this.redeemCode(form, clientId);
674
753
  } else if (grantType === "refresh_token") {
675
754
  grant = this.redeemRefreshToken(form, clientId);
676
755
  } else {
677
- throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and refresh_token, not "${grantType ?? ""}".`);
756
+ throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
678
757
  }
679
758
  sendJson(res, 200, await this.issueTokens(grant));
680
759
  } catch (error) {
@@ -684,6 +763,33 @@ var AuthorizationServer = class {
684
763
  throw error;
685
764
  }
686
765
  }
766
+ async clientCredentials(clientId, clientSecret, form) {
767
+ const app = this.seed.applications.find((a) => a.clientId === clientId);
768
+ if (app?.clientSecret && app.clientSecret !== clientSecret) {
769
+ throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
770
+ }
771
+ const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
772
+ const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
773
+ const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
774
+ return {
775
+ access_token: await this.testkit.m2mToken({
776
+ clientId,
777
+ organizationCode: app?.organizationCode ?? null,
778
+ scopes: requested,
779
+ grantedScopes: granted,
780
+ audience: audience.length > 0 ? audience : app?.audience ?? void 0,
781
+ permissions: app?.permissions ?? void 0
782
+ }),
783
+ expires_in: this.testkit.accessTokenLifetime,
784
+ scope: granted.join(" "),
785
+ token_type: "bearer"
786
+ };
787
+ }
788
+ reset() {
789
+ this.codes.clear();
790
+ this.refreshTokens.clear();
791
+ this.signedUpUsers.clear();
792
+ }
687
793
  redeemCode(form, clientId) {
688
794
  const code = form.code ?? "";
689
795
  const pending = this.codes.get(code);
@@ -794,8 +900,11 @@ var AuthorizationServer = class {
794
900
  if (seeded) return seeded;
795
901
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
796
902
  const user = createKindeUser({ email: ref.toLowerCase() });
797
- this.signedUpUsers.set(user.id, user);
798
- return user;
903
+ if (!this.signedUpUsers.has(user.id)) {
904
+ this.signedUpUsers.set(user.id, user);
905
+ this.emit("user.created", user);
906
+ }
907
+ return this.signedUpUsers.get(user.id);
799
908
  }
800
909
  organization(code) {
801
910
  return this.seed.organizations.find((org) => org.code === code) ?? null;
@@ -855,6 +964,15 @@ function clientIdFrom(req, form) {
855
964
  if (form.client_id) return form.client_id;
856
965
  throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
857
966
  }
967
+ function clientSecretFrom(req, form) {
968
+ const header = req.headers.authorization ?? "";
969
+ if (header.startsWith("Basic ")) {
970
+ const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
971
+ const index = decoded.indexOf(":");
972
+ if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
973
+ }
974
+ return form.client_secret ?? null;
975
+ }
858
976
  function redirectWithError(res, request2, error, description) {
859
977
  const target = new URL(request2.redirectUri);
860
978
  target.searchParams.set("error", error);
@@ -895,6 +1013,351 @@ function sendJson(res, status, body) {
895
1013
  res.end(JSON.stringify(body));
896
1014
  }
897
1015
 
1016
+ // src/failures.ts
1017
+ var MAX_DELAY_MS = 6e4;
1018
+ var FailureInjector = class {
1019
+ rules = [];
1020
+ nextId = 1;
1021
+ add(rule) {
1022
+ const problems = validate(rule);
1023
+ if (problems.length > 0) {
1024
+ throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
1025
+ }
1026
+ const active = {
1027
+ id: `failure_${this.nextId++}`,
1028
+ path: rule.path,
1029
+ method: rule.method ? rule.method.toUpperCase() : null,
1030
+ status: rule.status ?? null,
1031
+ delayMs: rule.delayMs ?? 0,
1032
+ hang: rule.hang ?? false,
1033
+ remaining: rule.times ?? null,
1034
+ retryAfter: rule.retryAfter ?? 1,
1035
+ hits: 0
1036
+ };
1037
+ this.rules.push(active);
1038
+ return { ...active };
1039
+ }
1040
+ remove(id) {
1041
+ const before = this.rules.length;
1042
+ this.rules = this.rules.filter((rule) => rule.id !== id);
1043
+ return this.rules.length < before;
1044
+ }
1045
+ clear() {
1046
+ this.rules = [];
1047
+ }
1048
+ list() {
1049
+ return this.rules.map((rule) => ({ ...rule }));
1050
+ }
1051
+ take(method, path) {
1052
+ const rule = this.rules.find((r) => matches(r, method, path));
1053
+ if (!rule) return null;
1054
+ rule.hits += 1;
1055
+ if (rule.remaining !== null) {
1056
+ rule.remaining -= 1;
1057
+ if (rule.remaining <= 0) this.remove(rule.id);
1058
+ }
1059
+ return { ...rule };
1060
+ }
1061
+ };
1062
+ function failureBody(status) {
1063
+ const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
1064
+ return { error, error_description: `kinde-testkit injected a ${status} response.` };
1065
+ }
1066
+ function matches(rule, method, path) {
1067
+ if (rule.method && rule.method !== method.toUpperCase()) return false;
1068
+ if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
1069
+ return rule.path === path;
1070
+ }
1071
+ function validate(rule) {
1072
+ const problems = [];
1073
+ if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
1074
+ problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
1075
+ } else if (rule.path.startsWith("/testkit/")) {
1076
+ problems.push("Failures cannot target /testkit/ control endpoints.");
1077
+ }
1078
+ if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
1079
+ problems.push('"status" must be an HTTP error status between 400 and 599.');
1080
+ }
1081
+ if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
1082
+ problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
1083
+ }
1084
+ if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
1085
+ problems.push('"times" must be a whole number of 1 or more.');
1086
+ }
1087
+ if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
1088
+ problems.push('"retryAfter" must be a whole number of seconds.');
1089
+ }
1090
+ if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
1091
+ problems.push('Set at least one of "status", "delayMs" or "hang".');
1092
+ }
1093
+ return problems;
1094
+ }
1095
+
1096
+ // src/webhooks.ts
1097
+ import { randomBytes as randomBytes2 } from "crypto";
1098
+ var WEBHOOK_EVENT_TYPES = [
1099
+ "user.created",
1100
+ "user.updated",
1101
+ "user.deleted",
1102
+ "user.authenticated",
1103
+ "user.authentication_failed",
1104
+ "organization.created",
1105
+ "organization.updated",
1106
+ "organization.deleted",
1107
+ "role.created",
1108
+ "role.updated",
1109
+ "role.deleted",
1110
+ "permission.created",
1111
+ "permission.updated",
1112
+ "permission.deleted",
1113
+ "subscriber.created",
1114
+ "access_request.created"
1115
+ ];
1116
+ var BILLING_EVENT_TYPES = [
1117
+ "customer.agreement_cancelled",
1118
+ "customer.agreement_created",
1119
+ "customer.invoice_overdue",
1120
+ "customer.meter_usage_updated",
1121
+ "customer.payment_failed",
1122
+ "customer.payment_succeeded",
1123
+ "customer.plan_assigned",
1124
+ "customer.plan_changed"
1125
+ ];
1126
+ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
1127
+ var DEFAULT_TIMEOUT_MS = 5e3;
1128
+ var MAX_DUPLICATES = 10;
1129
+ var WebhookDispatcher = class {
1130
+ constructor(testkit, seed, endpoints = [], options = {}) {
1131
+ this.testkit = testkit;
1132
+ this.seed = seed;
1133
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
1134
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1135
+ for (const endpoint of endpoints) this.addEndpoint(endpoint);
1136
+ this.seededEndpoints = [...this.endpoints];
1137
+ }
1138
+ testkit;
1139
+ seed;
1140
+ endpoints = [];
1141
+ seededEndpoints = [];
1142
+ log = [];
1143
+ nextEndpoint = 1;
1144
+ retryDelaysMs;
1145
+ timeoutMs;
1146
+ addEndpoint(input) {
1147
+ if (!isHttpUrl2(input.url)) {
1148
+ throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
1149
+ }
1150
+ if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
1151
+ throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
1152
+ }
1153
+ const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
1154
+ this.endpoints.push(endpoint);
1155
+ return { ...endpoint };
1156
+ }
1157
+ removeEndpoint(id) {
1158
+ const before = this.endpoints.length;
1159
+ this.endpoints = this.endpoints.filter((e) => e.id !== id);
1160
+ return this.endpoints.length < before;
1161
+ }
1162
+ listEndpoints() {
1163
+ return this.endpoints.map((e) => ({ ...e }));
1164
+ }
1165
+ deliveries() {
1166
+ return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
1167
+ }
1168
+ reset() {
1169
+ this.log = [];
1170
+ this.endpoints = [...this.seededEndpoints];
1171
+ }
1172
+ buildEvent(options) {
1173
+ if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
1174
+ throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
1175
+ }
1176
+ const now = /* @__PURE__ */ new Date();
1177
+ const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
1178
+ const event = {
1179
+ data: options.data ?? this.buildData(options),
1180
+ event_id: `event_${randomBytes2(16).toString("hex")}`,
1181
+ event_timestamp: timestamp,
1182
+ source: options.source ?? "admin",
1183
+ timestamp,
1184
+ type: options.type
1185
+ };
1186
+ if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
1187
+ event.ip_address = options.ipAddress ?? "127.0.0.1";
1188
+ }
1189
+ return event;
1190
+ }
1191
+ async send(options) {
1192
+ const event = this.buildEvent(options);
1193
+ const copies = options.duplicate ?? 1;
1194
+ if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
1195
+ throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
1196
+ }
1197
+ const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
1198
+ if (options.to && !isHttpUrl2(options.to)) {
1199
+ throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
1200
+ }
1201
+ if (targets.length === 0) {
1202
+ throw new TestkitError(
1203
+ "INVALID_REQUEST",
1204
+ `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
1205
+ );
1206
+ }
1207
+ if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
1208
+ const signed = await this.testkit.signPayload(
1209
+ event,
1210
+ options.invalid === "stale" ? void 0 : options.invalid
1211
+ );
1212
+ const jobs = targets.flatMap((target) => {
1213
+ const webhookId = `wh_${randomBytes2(12).toString("hex")}`;
1214
+ return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
1215
+ });
1216
+ return Promise.all(jobs);
1217
+ }
1218
+ async deliver(url, webhookId, body, event, copy) {
1219
+ const delivery = {
1220
+ webhookId,
1221
+ eventId: String(event.event_id),
1222
+ type: String(event.type),
1223
+ url,
1224
+ copy,
1225
+ delivered: false,
1226
+ attempts: [],
1227
+ payload: event
1228
+ };
1229
+ this.log.push(delivery);
1230
+ for (const [index, delay] of this.retryDelaysMs.entries()) {
1231
+ if (delay > 0) await sleep(delay);
1232
+ const started = Date.now();
1233
+ try {
1234
+ const response = await fetch(url, {
1235
+ method: "POST",
1236
+ headers: { "content-type": "application/jwt", "webhook-id": webhookId },
1237
+ body,
1238
+ signal: AbortSignal.timeout(this.timeoutMs)
1239
+ });
1240
+ await response.arrayBuffer().catch(() => void 0);
1241
+ delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
1242
+ if (response.status === 200) {
1243
+ delivery.delivered = true;
1244
+ break;
1245
+ }
1246
+ } catch (error) {
1247
+ const name = error.name;
1248
+ delivery.attempts.push({
1249
+ attempt: index + 1,
1250
+ status: null,
1251
+ error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
1252
+ durationMs: Date.now() - started
1253
+ });
1254
+ }
1255
+ }
1256
+ return { ...delivery, attempts: [...delivery.attempts] };
1257
+ }
1258
+ buildData(options) {
1259
+ const [subject] = options.type.split(".");
1260
+ switch (subject) {
1261
+ case "user":
1262
+ return { user: this.userData(options) };
1263
+ case "organization":
1264
+ return { organization: this.organizationData(options) };
1265
+ case "role":
1266
+ return { role: this.namedData(options, "role") };
1267
+ case "permission":
1268
+ return { permission: this.namedData(options, "permission") };
1269
+ case "subscriber": {
1270
+ const user = this.requireUser(options);
1271
+ return {
1272
+ subscriber: {
1273
+ email: user.email,
1274
+ first_name: user.givenName,
1275
+ id: stableId("sub", user.id),
1276
+ last_name: user.familyName,
1277
+ user_id: user.id
1278
+ }
1279
+ };
1280
+ }
1281
+ case "access_request": {
1282
+ const user = this.requireUser(options);
1283
+ return {
1284
+ access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
1285
+ };
1286
+ }
1287
+ default:
1288
+ throw new TestkitError(
1289
+ "INVALID_REQUEST",
1290
+ `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
1291
+ );
1292
+ }
1293
+ }
1294
+ emitForUser(type, user) {
1295
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
1296
+ const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
1297
+ void this.send({ type, data, source: "user" }).catch(() => void 0);
1298
+ }
1299
+ userData(options) {
1300
+ const user = this.requireUser(options);
1301
+ if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
1302
+ return this.userPayload(user);
1303
+ }
1304
+ userPayload(user) {
1305
+ return {
1306
+ email: user.email,
1307
+ first_name: user.givenName,
1308
+ id: user.id,
1309
+ is_password_reset_requested: false,
1310
+ is_suspended: false,
1311
+ last_name: user.familyName,
1312
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
1313
+ code: m.organizationCode,
1314
+ permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
1315
+ roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
1316
+ })),
1317
+ phone: null,
1318
+ username: typeof user.claims.username === "string" ? user.claims.username : null
1319
+ };
1320
+ }
1321
+ organizationData(options) {
1322
+ if (!options.organization) {
1323
+ throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
1324
+ }
1325
+ const org = this.seed.organizations.find((o) => o.code === options.organization);
1326
+ if (options.type === "organization.deleted") return { code: options.organization };
1327
+ const name = org?.name ?? titleCase(options.organization);
1328
+ const data = { code: options.organization, external_id: null, handle: slug(name), name };
1329
+ if (options.type === "organization.updated") data.is_allow_registrations = false;
1330
+ return data;
1331
+ }
1332
+ namedData(options, kind) {
1333
+ const key = kind === "role" ? options.role : options.permission;
1334
+ if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
1335
+ const id = stableId(kind === "role" ? "role" : "perm", key);
1336
+ if (options.type.endsWith(".deleted")) return { id };
1337
+ const data = { description: "", id, key, name: titleCase(key) };
1338
+ if (kind === "role") data.is_default_role = false;
1339
+ return data;
1340
+ }
1341
+ requireUser(options) {
1342
+ if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
1343
+ const user = findUser(this.seed.users, options.user);
1344
+ if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
1345
+ return user;
1346
+ }
1347
+ };
1348
+ function isHttpUrl2(value) {
1349
+ if (typeof value !== "string") return false;
1350
+ try {
1351
+ const { protocol } = new URL(value);
1352
+ return protocol === "http:" || protocol === "https:";
1353
+ } catch {
1354
+ return false;
1355
+ }
1356
+ }
1357
+ function sleep(ms) {
1358
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1359
+ }
1360
+
898
1361
  // src/server.ts
899
1362
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
900
1363
  var MAX_BODY_BYTES = 64 * 1024;
@@ -908,12 +1371,11 @@ async function startKindeTestkit(options = {}) {
908
1371
  );
909
1372
  }
910
1373
  const seed = resolveSeed(options.seed ?? {});
1374
+ const failures = new FailureInjector();
911
1375
  let ready;
912
- const testkitReady = new Promise(
913
- (resolve2) => ready = resolve2
914
- );
1376
+ const testkitReady = new Promise((resolve2) => ready = resolve2);
915
1377
  const server = createServer((req, res) => {
916
- testkitReady.then(({ testkit: testkit2, auth }) => handle(req, res, testkit2, auth, seed)).catch((error) => sendError(res, error));
1378
+ testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
917
1379
  });
918
1380
  await new Promise((resolve2, reject) => {
919
1381
  server.once("error", reject);
@@ -927,7 +1389,14 @@ async function startKindeTestkit(options = {}) {
927
1389
  audience: options.audience ?? options.seed?.audience,
928
1390
  clientId: options.clientId ?? options.seed?.clientId
929
1391
  });
930
- ready({ testkit, auth: new AuthorizationServer(testkit, seed) });
1392
+ const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
1393
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
1394
+ const reset2 = () => {
1395
+ auth.reset();
1396
+ failures.clear();
1397
+ webhooks.reset();
1398
+ };
1399
+ ready({ testkit, auth, seed, failures, webhooks, reset: reset2 });
931
1400
  return {
932
1401
  url,
933
1402
  issuer: testkit.issuer,
@@ -935,16 +1404,32 @@ async function startKindeTestkit(options = {}) {
935
1404
  jwksUri: `${url}/.well-known/jwks`,
936
1405
  testkit,
937
1406
  seed,
1407
+ failures,
1408
+ webhooks,
1409
+ reset: reset2,
938
1410
  close: () => new Promise((resolve2, reject) => {
939
1411
  server.closeAllConnections();
940
1412
  server.close((error) => error ? reject(error) : resolve2());
941
1413
  })
942
1414
  };
943
1415
  }
944
- async function handle(req, res, testkit, auth, seed) {
1416
+ async function handle(req, res, context) {
1417
+ const { testkit, auth, seed, failures, webhooks } = context;
945
1418
  const url = new URL(req.url ?? "/", "http://localhost");
946
1419
  const { pathname } = url;
947
1420
  const method = req.method ?? "GET";
1421
+ if (!pathname.startsWith("/testkit/")) {
1422
+ const failure = failures.take(method, pathname);
1423
+ if (failure) {
1424
+ if (failure.hang) return;
1425
+ if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
1426
+ if (failure.status !== null) {
1427
+ const headers = {};
1428
+ if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
1429
+ return sendJson2(res, failure.status, failureBody(failure.status), headers);
1430
+ }
1431
+ }
1432
+ }
948
1433
  if (await auth.handle(req, res, url, () => readForm(req))) return;
949
1434
  if (method === "GET" && pathname === "/.well-known/openid-configuration") {
950
1435
  return sendJson2(res, 200, discovery(testkit));
@@ -962,6 +1447,37 @@ async function handle(req, res, testkit, auth, seed) {
962
1447
  if (method === "GET" && pathname === "/testkit/memberships") {
963
1448
  return sendJson2(res, 200, seed.memberships);
964
1449
  }
1450
+ if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
1451
+ if (method === "POST" && pathname === "/testkit/failures") {
1452
+ return sendJson2(res, 201, failures.add(await readJson(req)));
1453
+ }
1454
+ if (method === "DELETE" && pathname === "/testkit/failures") {
1455
+ failures.clear();
1456
+ return sendJson2(res, 200, { ok: true });
1457
+ }
1458
+ if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
1459
+ const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1460
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1461
+ }
1462
+ if (method === "POST" && pathname === "/testkit/webhooks") {
1463
+ return sendJson2(res, 200, await webhooks.send(await readJson(req)));
1464
+ }
1465
+ if (method === "GET" && pathname === "/testkit/webhooks/types") {
1466
+ return sendJson2(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
1467
+ }
1468
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson2(res, 200, webhooks.deliveries());
1469
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson2(res, 200, webhooks.listEndpoints());
1470
+ if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
1471
+ return sendJson2(res, 201, webhooks.addEndpoint(await readJson(req)));
1472
+ }
1473
+ if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
1474
+ const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
1475
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1476
+ }
1477
+ if (method === "POST" && pathname === "/testkit/reset") {
1478
+ context.reset();
1479
+ return sendJson2(res, 200, { ok: true });
1480
+ }
965
1481
  if (method === "POST" && pathname === "/testkit/token") {
966
1482
  const body = await readJson(req);
967
1483
  const accessToken = await issueToken(testkit, seed, body);
@@ -1001,6 +1517,21 @@ async function issueToken(testkit, seed, body) {
1001
1517
  ]);
1002
1518
  }
1003
1519
  const expiresIn = input.expiresIn;
1520
+ if (input.m2m === true) {
1521
+ const clientId = optionalString(input, "clientId");
1522
+ const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
1523
+ const scopes = optionalStrings(input, "scopes") ?? [];
1524
+ return testkit.m2mToken({
1525
+ clientId,
1526
+ organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
1527
+ scopes,
1528
+ grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
1529
+ audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
1530
+ permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
1531
+ expiresIn,
1532
+ invalid: invalid2
1533
+ });
1534
+ }
1004
1535
  const permissions = optionalStrings(input, "permissions");
1005
1536
  const roles = optionalStrings(input, "roles");
1006
1537
  const userRef = optionalString(input, "user");
@@ -1076,10 +1607,11 @@ async function readText(req) {
1076
1607
  }
1077
1608
  return Buffer.concat(chunks).toString("utf8").trim();
1078
1609
  }
1079
- function sendJson2(res, status, body) {
1610
+ function sendJson2(res, status, body, headers = {}) {
1080
1611
  res.writeHead(status, {
1081
1612
  "content-type": "application/json; charset=utf-8",
1082
- "cache-control": "no-store"
1613
+ "cache-control": "no-store",
1614
+ ...headers
1083
1615
  });
1084
1616
  res.end(JSON.stringify(body));
1085
1617
  }
@@ -1098,6 +1630,173 @@ function sendError(res, error) {
1098
1630
  });
1099
1631
  }
1100
1632
 
1633
+ // src/inspect.ts
1634
+ import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, jwtVerify as jwtVerify2 } from "jose";
1635
+ async function inspectToken(token2, options = {}) {
1636
+ const checks = [];
1637
+ const trimmed = token2.trim();
1638
+ let header = null;
1639
+ let payload = null;
1640
+ if (trimmed.split(".").length !== 3) {
1641
+ checks.push({ name: "Format", status: "fail", detail: "A JWT has three parts separated by dots." });
1642
+ return { kind: "unknown", header, payload, checks };
1643
+ }
1644
+ try {
1645
+ header = decodeProtectedHeader(trimmed);
1646
+ payload = decodeJwt(trimmed);
1647
+ } catch {
1648
+ checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
1649
+ return { kind: "unknown", header, payload, checks };
1650
+ }
1651
+ checks.push({ name: "Format", status: "pass", detail: "Three base64url parts with JSON header and payload." });
1652
+ checks.push(
1653
+ 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.` }
1654
+ );
1655
+ const signer = typeof header.kid === "string" && header.kid.startsWith("kinde-testkit") ? "kinde-testkit" : "another issuer";
1656
+ checks.push({ name: "Key", status: "pass", detail: `kid ${String(header.kid ?? "missing")} (${signer}).` });
1657
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
1658
+ if (typeof payload.exp !== "number") {
1659
+ checks.push({ name: "Expiry", status: "fail", detail: "No exp claim." });
1660
+ } else if (payload.exp <= now) {
1661
+ checks.push({ name: "Expiry", status: "fail", detail: `Expired ${formatSpan(now - payload.exp)} ago.` });
1662
+ } else {
1663
+ checks.push({ name: "Expiry", status: "pass", detail: `Expires in ${formatSpan(payload.exp - now)}.` });
1664
+ }
1665
+ if (typeof payload.iat === "number" && payload.iat > now + 60) {
1666
+ checks.push({ name: "Issued at", status: "fail", detail: `iat is ${formatSpan(payload.iat - now)} in the future.` });
1667
+ }
1668
+ if (options.issuerUrl) {
1669
+ const issuer = options.issuerUrl.replace(/\/+$/, "");
1670
+ if (payload.iss !== issuer) {
1671
+ checks.push({ name: "Issuer", status: "fail", detail: `iss is ${String(payload.iss)}, not ${issuer}.` });
1672
+ } else {
1673
+ checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
1674
+ }
1675
+ try {
1676
+ await jwtVerify2(trimmed, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
1677
+ checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
1678
+ } catch (error) {
1679
+ const code = error.code ?? "";
1680
+ if (code === "ERR_JWT_EXPIRED" || code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
1681
+ checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
1682
+ } else {
1683
+ checks.push({ name: "Signature", status: "fail", detail: describeVerifyError(code, issuer) });
1684
+ }
1685
+ }
1686
+ } else {
1687
+ checks.push({ name: "Signature", status: "warn", detail: "Not checked. Pass --url to verify against a running issuer." });
1688
+ }
1689
+ return { kind: kindOf(payload), header, payload, checks };
1690
+ }
1691
+ function kindOf(payload) {
1692
+ if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) return "m2m";
1693
+ if ("email" in payload || "org_codes" in payload || "at_hash" in payload || "nonce" in payload) return "id";
1694
+ if ("scp" in payload || "permissions" in payload || "org_code" in payload) return "access";
1695
+ return "unknown";
1696
+ }
1697
+ function describeVerifyError(code, issuer) {
1698
+ if (code === "ERR_JWKS_NO_MATCHING_KEY") return `No key in ${issuer}'s JWKS matches this token's kid.`;
1699
+ if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "The signature does not match the token. It was changed after signing.";
1700
+ if (code === "ERR_JOSE_ALG_NOT_ALLOWED" || code === "ERR_JOSE_NOT_SUPPORTED") return "The token is not signed with RS256.";
1701
+ if (code === "ERR_JWKS_TIMEOUT" || code === "ERR_JOSE_GENERIC") return `Could not fetch keys from ${issuer}.`;
1702
+ return `Verification failed (${code || "unknown error"}).`;
1703
+ }
1704
+ function formatSpan(seconds) {
1705
+ const s = Math.max(0, Math.round(seconds));
1706
+ if (s < 60) return `${s}s`;
1707
+ if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
1708
+ if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor(s % 3600 / 60)}m`;
1709
+ return `${Math.floor(s / 86400)}d ${Math.floor(s % 86400 / 3600)}h`;
1710
+ }
1711
+
1712
+ // src/doctor.ts
1713
+ var SECRET_FORMAT = /^[a-zA-Z0-9]{40,60}$/;
1714
+ async function runDoctor(options) {
1715
+ const url = options.url.replace(/\/+$/, "");
1716
+ const checks = [];
1717
+ let issuer = null;
1718
+ try {
1719
+ const health = await (await fetch(`${url}/testkit/health`)).json();
1720
+ issuer = health.issuer ?? null;
1721
+ checks.push({ name: "Issuer running", status: "pass", detail: `${url} answers, issuer ${issuer}.` });
1722
+ } catch {
1723
+ checks.push({ name: "Issuer running", status: "fail", detail: `Nothing answers at ${url}. Start it with "kinde-testkit start".` });
1724
+ }
1725
+ if (issuer) {
1726
+ try {
1727
+ const discovery2 = await (await fetch(`${url}/.well-known/openid-configuration`)).json();
1728
+ checks.push(
1729
+ 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}.` }
1730
+ );
1731
+ } catch {
1732
+ checks.push({ name: "Discovery", status: "fail", detail: "Could not read /.well-known/openid-configuration." });
1733
+ }
1734
+ try {
1735
+ const jwks = await (await fetch(`${url}/.well-known/jwks.json`)).json();
1736
+ const usable = (jwks.keys ?? []).filter((key) => key.kty === "RSA" && key.use === "sig");
1737
+ checks.push(
1738
+ 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." }
1739
+ );
1740
+ } catch {
1741
+ checks.push({ name: "JWKS", status: "fail", detail: "Could not read /.well-known/jwks.json." });
1742
+ }
1743
+ try {
1744
+ const users = await (await fetch(`${url}/testkit/users`)).json();
1745
+ checks.push(
1746
+ 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." }
1747
+ );
1748
+ } catch {
1749
+ checks.push({ name: "Seed", status: "warn", detail: "Could not read /testkit/users." });
1750
+ }
1751
+ }
1752
+ const env = options.env;
1753
+ const configured = env.KINDE_ISSUER_URL?.trim().replace(/\/+$/, "");
1754
+ if (!configured) {
1755
+ checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: "Not set. Set it to the testkit's issuer for test runs." });
1756
+ } else if (/\.kinde\.com$/i.test(new URL(configured, "http://x").hostname)) {
1757
+ checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} is a real Kinde domain. Tests would sign in against Kinde, not the testkit.` });
1758
+ } else if (issuer && configured !== issuer) {
1759
+ checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} does not match the testkit issuer ${issuer}. Token checks compare iss exactly.` });
1760
+ } else {
1761
+ checks.push({ name: "KINDE_ISSUER_URL", status: "pass", detail: `${configured}.` });
1762
+ }
1763
+ checks.push(
1764
+ 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." }
1765
+ );
1766
+ const secret = env.KINDE_CLIENT_SECRET;
1767
+ if (!secret) {
1768
+ checks.push({ name: "KINDE_CLIENT_SECRET", status: "warn", detail: "Not set. Server-side SDKs, such as the Next.js SDK, need it." });
1769
+ } else if (!SECRET_FORMAT.test(secret)) {
1770
+ checks.push({ name: "KINDE_CLIENT_SECRET", status: "fail", detail: "The Next.js SDK only accepts 40 to 60 letters and digits." });
1771
+ } else {
1772
+ checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
1773
+ }
1774
+ const site = env.KINDE_SITE_URL;
1775
+ if (!site) {
1776
+ checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
1777
+ } else if (!/^https?:\/\//.test(site)) {
1778
+ checks.push({ name: "KINDE_SITE_URL", status: "fail", detail: `${site} is not an http or https URL.` });
1779
+ } else {
1780
+ checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
1781
+ }
1782
+ return { url, checks, ok: checks.every((check) => check.status !== "fail") };
1783
+ }
1784
+ function parseEnvFile(text) {
1785
+ const values = {};
1786
+ for (const line of text.split(/\r?\n/)) {
1787
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
1788
+ if (!match) continue;
1789
+ let value = match[2];
1790
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1791
+ value = value.slice(1, -1);
1792
+ } else {
1793
+ value = value.replace(/\s+#.*$/, "");
1794
+ }
1795
+ values[match[1]] = value;
1796
+ }
1797
+ return values;
1798
+ }
1799
+
1101
1800
  // src/cli.ts
1102
1801
  var DEFAULT_URL = process.env.KINDE_TESTKIT_URL ?? "http://localhost:4400";
1103
1802
  var DEFAULT_SEED_FILE = "kinde-testkit.json";
@@ -1108,6 +1807,11 @@ Usage
1108
1807
  kinde-testkit token [options] Print a signed test access token
1109
1808
  kinde-testkit users [--json] List seeded users
1110
1809
  kinde-testkit organizations [--json] List seeded organizations
1810
+ kinde-testkit inspect [token] Decode a token and check it (reads stdin when no token)
1811
+ kinde-testkit doctor [options] Check your app's Kinde settings against the issuer
1812
+ kinde-testkit fail <path> [options] Make an endpoint fail, slow down or hang
1813
+ kinde-testkit reset Clear sign-in sessions and failure rules
1814
+ kinde-testkit webhook <type> [options] Send a signed webhook event
1111
1815
 
1112
1816
  start
1113
1817
  --port <n> Port to listen on (default 4400)
@@ -1117,6 +1821,7 @@ start
1117
1821
  --client-id <id> Value for azp
1118
1822
  --seed <file> Seed file (default ./kinde-testkit.json when it exists)
1119
1823
  --allow-public Allow binding to a non-loopback interface
1824
+ --webhook <url> Send webhooks to this URL (repeatable)
1120
1825
 
1121
1826
  token
1122
1827
  --url <url> Running issuer (default ${DEFAULT_URL})
@@ -1129,7 +1834,41 @@ token
1129
1834
  --invalid <kind> expired, wrong-issuer, wrong-audience, missing-subject,
1130
1835
  missing-organization, missing-permissions, future-iat,
1131
1836
  bad-signature, unknown-key, unsigned
1837
+ --m2m Machine-to-machine token (client_credentials shape)
1838
+ --client-id <id> M2M client ID, matched against seeded applications
1839
+ --scope <a,b> M2M scopes requested
1132
1840
  --json Print JSON instead of the raw token
1841
+
1842
+ inspect
1843
+ --url <url> Also verify the issuer and signature against a running issuer
1844
+ --json Print JSON
1845
+
1846
+ doctor
1847
+ --url <url> Running issuer (default ${DEFAULT_URL})
1848
+ --env-file <file> Read settings from this file (repeatable). Defaults to .env,
1849
+ .env.local, .env.test and .env.test.local when they exist
1850
+ --json Print JSON
1851
+
1852
+ fail <path> An exact path such as /oauth2/token, or a prefix such as /oauth2/*
1853
+ --status <code> Answer with this status, such as 429, 500 or 503
1854
+ --delay <ms> Wait before answering
1855
+ --hang Never answer
1856
+ --times <n> Apply to the next n requests only
1857
+ --method <verb> Only match this method
1858
+ --list Show active rules
1859
+ --clear Remove all rules
1860
+
1861
+ webhook <type> Any event type, such as user.created or customer.plan_assigned
1862
+ --user <id|email> Seeded user, for user.*, subscriber.* and access_request.*
1863
+ --org <code> Organization, for organization.*
1864
+ --role <key> Role, for role.*
1865
+ --permission <key> Permission, for permission.*
1866
+ --data <json> The event's data object. Needed for billing events
1867
+ --to <url> Send to this URL instead of the configured endpoints
1868
+ --duplicate <n> Send n copies with the same webhook-id
1869
+ --invalid <kind> bad-signature, unknown-key, unsigned or stale
1870
+ --types List the event types with built-in payloads
1871
+ --deliveries Show the delivery log
1133
1872
  `;
1134
1873
  async function main(argv) {
1135
1874
  const [command, ...rest] = argv;
@@ -1143,6 +1882,17 @@ async function main(argv) {
1143
1882
  case "organizations":
1144
1883
  case "orgs":
1145
1884
  return list(rest, "organizations");
1885
+ case "inspect":
1886
+ return inspect(rest);
1887
+ case "doctor":
1888
+ return doctor(rest);
1889
+ case "fail":
1890
+ return fail(rest);
1891
+ case "reset":
1892
+ return reset(rest);
1893
+ case "webhook":
1894
+ case "webhooks":
1895
+ return webhook(rest);
1146
1896
  case void 0:
1147
1897
  case "help":
1148
1898
  case "--help":
@@ -1164,11 +1914,13 @@ async function start(args) {
1164
1914
  "client-id": { type: "string" },
1165
1915
  seed: { type: "string" },
1166
1916
  "allow-public": { type: "boolean" },
1917
+ webhook: { type: "string", multiple: true },
1167
1918
  json: { type: "boolean" }
1168
1919
  }
1169
1920
  });
1170
1921
  const seedPath = values.seed ?? (existsSync(DEFAULT_SEED_FILE) ? DEFAULT_SEED_FILE : void 0);
1171
- const seed = seedPath ? readSeed(seedPath) : void 0;
1922
+ const seed = seedPath ? readSeed(seedPath) : values.webhook ? {} : void 0;
1923
+ if (seed && values.webhook) seed.webhooks = [...seed.webhooks ?? [], ...values.webhook.map((url) => ({ url }))];
1172
1924
  const running = await startKindeTestkit({
1173
1925
  port: values.port ? Number(values.port) : void 0,
1174
1926
  host: values.host,
@@ -1207,6 +1959,7 @@ async function start(args) {
1207
1959
  `Seed: ${seedPath ? resolve(seedPath) : "none"}`,
1208
1960
  `Users: ${running.seed.users.length}`,
1209
1961
  `Organizations: ${running.seed.organizations.length}`,
1962
+ `Webhooks: ${running.webhooks.listEndpoints().map((e) => e.url).join(", ") || "none"}`,
1210
1963
  "",
1211
1964
  "Test tokens only. Press Ctrl+C to stop.",
1212
1965
  ""
@@ -1231,10 +1984,21 @@ async function token(args) {
1231
1984
  roles: { type: "string" },
1232
1985
  "expires-in": { type: "string" },
1233
1986
  invalid: { type: "string" },
1987
+ m2m: { type: "boolean" },
1988
+ "client-id": { type: "string" },
1989
+ scope: { type: "string" },
1234
1990
  json: { type: "boolean" }
1235
1991
  }
1236
1992
  });
1237
- const body = {
1993
+ const body = values.m2m ? {
1994
+ m2m: true,
1995
+ clientId: values["client-id"],
1996
+ organization: values.org,
1997
+ scopes: values.scope !== void 0 ? csv(values.scope) : void 0,
1998
+ permissions: values.permissions !== void 0 ? csv(values.permissions) : void 0,
1999
+ expiresIn: values["expires-in"],
2000
+ invalid: values.invalid
2001
+ } : {
1238
2002
  user: values.user,
1239
2003
  organization: values.org,
1240
2004
  subject: values.sub,
@@ -1253,6 +2017,241 @@ async function token(args) {
1253
2017
  ` : `${accessToken}
1254
2018
  `);
1255
2019
  }
2020
+ async function inspect(args) {
2021
+ const { values, positionals } = parseArgs({
2022
+ args,
2023
+ allowPositionals: true,
2024
+ options: { url: { type: "string" }, json: { type: "boolean" } }
2025
+ });
2026
+ const raw = positionals[0] ?? (process.stdin.isTTY ? "" : await readStdin());
2027
+ const token2 = raw.trim().replace(/^Bearer\s+/i, "");
2028
+ if (!token2) {
2029
+ throw new TestkitError("INVALID_REQUEST", "Pass a token, or pipe one in: kinde-testkit token | kinde-testkit inspect");
2030
+ }
2031
+ const result = await inspectToken(token2, { issuerUrl: values.url });
2032
+ if (values.json) {
2033
+ process.stdout.write(`${JSON.stringify(result, null, 2)}
2034
+ `);
2035
+ } else {
2036
+ const lines = [`${result.kind === "m2m" ? "Machine-to-machine access token" : result.kind === "id" ? "ID token" : result.kind === "access" ? "Access token" : "Token"}`, ""];
2037
+ if (result.payload) {
2038
+ const p = result.payload;
2039
+ const show = (label, value) => {
2040
+ if (value !== void 0) lines.push(`${label.padEnd(14)} ${typeof value === "string" ? value : JSON.stringify(value)}`);
2041
+ };
2042
+ show("Subject", p.sub);
2043
+ show("Client", p.azp);
2044
+ show("Issuer", p.iss);
2045
+ show("Audience", p.aud);
2046
+ show("Organization", p.org_code ?? p.org_codes);
2047
+ show("Roles", Array.isArray(p.roles) ? p.roles.map((r) => typeof r === "string" ? r : r.key) : void 0);
2048
+ show("Permissions", p.permissions);
2049
+ show(result.kind === "m2m" ? "Requested" : "Scopes", p.scp);
2050
+ if (result.kind === "m2m") show("Granted", p.scope === "" ? "none" : p.scope);
2051
+ if (typeof p.exp === "number" && typeof p.iat === "number") show("Lifetime", formatSpan(p.exp - p.iat));
2052
+ lines.push("");
2053
+ }
2054
+ lines.push(...result.checks.map(formatCheck), "");
2055
+ process.stdout.write(lines.join("\n"));
2056
+ }
2057
+ if (result.checks.some((check) => check.status === "fail")) process.exitCode = 1;
2058
+ }
2059
+ async function doctor(args) {
2060
+ const { values } = parseArgs({
2061
+ args,
2062
+ options: {
2063
+ url: { type: "string" },
2064
+ "env-file": { type: "string", multiple: true },
2065
+ json: { type: "boolean" }
2066
+ }
2067
+ });
2068
+ const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) => existsSync(file));
2069
+ const env = {};
2070
+ for (const file of files) {
2071
+ if (!existsSync(file)) throw new TestkitError("INVALID_REQUEST", `No env file at ${resolve(file)}.`);
2072
+ Object.assign(env, parseEnvFile(readFileSync(file, "utf8")));
2073
+ }
2074
+ for (const [key, value] of Object.entries(process.env)) {
2075
+ if (key.startsWith("KINDE_") && value !== void 0) env[key] = value;
2076
+ }
2077
+ const report = await runDoctor({ url: values.url ?? DEFAULT_URL, env });
2078
+ if (values.json) {
2079
+ process.stdout.write(`${JSON.stringify({ ...report, envFiles: files }, null, 2)}
2080
+ `);
2081
+ } else {
2082
+ process.stdout.write(
2083
+ [
2084
+ "",
2085
+ "kinde-testkit doctor",
2086
+ "",
2087
+ `Settings read from: ${files.length > 0 ? files.join(", ") : "environment only"}`,
2088
+ "",
2089
+ ...report.checks.map(formatCheck),
2090
+ "",
2091
+ report.ok ? "Ready to test." : "Fix the failed checks above, then run doctor again.",
2092
+ ""
2093
+ ].join("\n")
2094
+ );
2095
+ }
2096
+ if (!report.ok) process.exitCode = 1;
2097
+ }
2098
+ async function fail(args) {
2099
+ const { values, positionals } = parseArgs({
2100
+ args,
2101
+ allowPositionals: true,
2102
+ options: {
2103
+ url: { type: "string" },
2104
+ status: { type: "string" },
2105
+ delay: { type: "string" },
2106
+ hang: { type: "boolean" },
2107
+ times: { type: "string" },
2108
+ method: { type: "string" },
2109
+ list: { type: "boolean" },
2110
+ clear: { type: "boolean" },
2111
+ json: { type: "boolean" }
2112
+ }
2113
+ });
2114
+ const base = values.url ?? DEFAULT_URL;
2115
+ if (values.clear) {
2116
+ await request(base, "/testkit/failures", { method: "DELETE" });
2117
+ process.stdout.write("Removed all failure rules.\n");
2118
+ return;
2119
+ }
2120
+ if (values.list || positionals.length === 0) {
2121
+ const rules = await request(base, "/testkit/failures");
2122
+ if (values.json) {
2123
+ process.stdout.write(`${JSON.stringify(rules)}
2124
+ `);
2125
+ } else if (rules.length === 0) {
2126
+ process.stdout.write("No failure rules.\n");
2127
+ } else {
2128
+ for (const rule2 of rules) process.stdout.write(`${describeRule(rule2)}
2129
+ `);
2130
+ }
2131
+ return;
2132
+ }
2133
+ const rule = await request(base, "/testkit/failures", {
2134
+ method: "POST",
2135
+ headers: { "content-type": "application/json" },
2136
+ body: JSON.stringify({
2137
+ path: positionals[0],
2138
+ method: values.method,
2139
+ status: values.status !== void 0 ? Number(values.status) : void 0,
2140
+ delayMs: values.delay !== void 0 ? Number(values.delay) : void 0,
2141
+ hang: values.hang,
2142
+ times: values.times !== void 0 ? Number(values.times) : void 0
2143
+ })
2144
+ });
2145
+ process.stdout.write(values.json ? `${JSON.stringify(rule)}
2146
+ ` : `Added ${describeRule(rule)}
2147
+ `);
2148
+ }
2149
+ async function reset(args) {
2150
+ const { values } = parseArgs({ args, options: { url: { type: "string" } } });
2151
+ await request(values.url ?? DEFAULT_URL, "/testkit/reset", { method: "POST" });
2152
+ process.stdout.write("Cleared sign-in codes, refresh tokens, signed-up users and failure rules.\n");
2153
+ }
2154
+ async function readStdin() {
2155
+ const chunks = [];
2156
+ for await (const chunk of process.stdin) chunks.push(chunk);
2157
+ return Buffer.concat(chunks).toString("utf8");
2158
+ }
2159
+ async function webhook(args) {
2160
+ const { values, positionals } = parseArgs({
2161
+ args,
2162
+ allowPositionals: true,
2163
+ options: {
2164
+ url: { type: "string" },
2165
+ user: { type: "string" },
2166
+ org: { type: "string" },
2167
+ role: { type: "string" },
2168
+ permission: { type: "string" },
2169
+ data: { type: "string" },
2170
+ to: { type: "string" },
2171
+ duplicate: { type: "string" },
2172
+ invalid: { type: "string" },
2173
+ types: { type: "boolean" },
2174
+ deliveries: { type: "boolean" },
2175
+ json: { type: "boolean" }
2176
+ }
2177
+ });
2178
+ const base = values.url ?? DEFAULT_URL;
2179
+ if (values.types) {
2180
+ const types = await request(base, "/testkit/webhooks/types");
2181
+ process.stdout.write(
2182
+ values.json ? `${JSON.stringify(types)}
2183
+ ` : `Built-in payloads:
2184
+ ${types.built_in.map((t) => ` ${t}`).join("\n")}
2185
+
2186
+ Billing events (pass --data):
2187
+ ${types.billing.map((t) => ` ${t}`).join("\n")}
2188
+ `
2189
+ );
2190
+ return;
2191
+ }
2192
+ if (values.deliveries || positionals.length === 0) {
2193
+ const log = await request(base, "/testkit/webhooks/deliveries");
2194
+ if (values.json) {
2195
+ process.stdout.write(`${JSON.stringify(log)}
2196
+ `);
2197
+ } else if (log.length === 0) {
2198
+ process.stdout.write("No webhooks sent yet.\n");
2199
+ } else {
2200
+ for (const delivery of log) process.stdout.write(`${describeDelivery(delivery)}
2201
+ `);
2202
+ }
2203
+ return;
2204
+ }
2205
+ let data;
2206
+ if (values.data !== void 0) {
2207
+ try {
2208
+ data = JSON.parse(values.data);
2209
+ } catch {
2210
+ throw new TestkitError("INVALID_REQUEST", `--data must be a JSON object, for example '{"customer_id":"c_1"}'.`);
2211
+ }
2212
+ }
2213
+ const deliveries = await request(base, "/testkit/webhooks", {
2214
+ method: "POST",
2215
+ headers: { "content-type": "application/json" },
2216
+ body: JSON.stringify({
2217
+ type: positionals[0],
2218
+ user: values.user,
2219
+ organization: values.org,
2220
+ role: values.role,
2221
+ permission: values.permission,
2222
+ data,
2223
+ to: values.to,
2224
+ duplicate: values.duplicate !== void 0 ? Number(values.duplicate) : void 0,
2225
+ invalid: values.invalid
2226
+ })
2227
+ });
2228
+ if (values.json) {
2229
+ process.stdout.write(`${JSON.stringify(deliveries)}
2230
+ `);
2231
+ return;
2232
+ }
2233
+ for (const delivery of deliveries) process.stdout.write(`${describeDelivery(delivery)}
2234
+ `);
2235
+ if (deliveries.some((d) => !d.delivered)) process.exitCode = 1;
2236
+ }
2237
+ function describeDelivery(delivery) {
2238
+ const attempts = delivery.attempts ?? [];
2239
+ const outcome = attempts.map((a) => a.status === null ? "no answer" : String(a.status)).join(", ");
2240
+ const mark = delivery.delivered ? "\u2713" : "\u2717";
2241
+ return `${mark} ${String(delivery.type)} to ${String(delivery.url)} (${String(delivery.webhookId)}): ${outcome}`;
2242
+ }
2243
+ function describeRule(rule) {
2244
+ const parts = [`${String(rule.id)}: ${rule.method ? `${String(rule.method)} ` : ""}${String(rule.path)}`];
2245
+ if (rule.status !== null) parts.push(`answers ${String(rule.status)}`);
2246
+ if (rule.delayMs) parts.push(`after ${String(rule.delayMs)}ms`);
2247
+ if (rule.hang) parts.push("never answers");
2248
+ parts.push(rule.remaining === null ? "until removed" : `for the next ${String(rule.remaining)} requests`);
2249
+ return parts.join(", ");
2250
+ }
2251
+ function formatCheck(check) {
2252
+ const mark = check.status === "pass" ? "\u2713" : check.status === "warn" ? "!" : "\u2717";
2253
+ return `${mark} ${check.name.padEnd(20)} ${check.detail}`;
2254
+ }
1256
2255
  async function list(args, kind) {
1257
2256
  const { values } = parseArgs({
1258
2257
  args,