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/vitest.js CHANGED
@@ -111,6 +111,7 @@ function invalid(value) {
111
111
  // src/testkit.ts
112
112
  var DEFAULT_ISSUER = "http://localhost:4400";
113
113
  var DEFAULT_CLIENT_ID = "kinde_testkit_client";
114
+ var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
114
115
  var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
115
116
  var DEFAULT_AUTH_METHODS = ["email"];
116
117
  var INVALID_TOKEN_KINDS = [
@@ -189,6 +190,27 @@ var KindeTestkit = class _KindeTestkit {
189
190
  Object.assign(payload, options.claims ?? {});
190
191
  return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
191
192
  }
193
+ async m2mToken(options = {}) {
194
+ const now = this.clock();
195
+ const requested = [...options.scopes ?? []];
196
+ const granted = [...options.grantedScopes ?? requested];
197
+ const payload = {
198
+ aud: [...options.audience ?? this.audience],
199
+ azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
200
+ exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
201
+ gty: ["client_credentials"],
202
+ iat: now,
203
+ iss: this.issuer,
204
+ jti: randomUUID(),
205
+ scope: granted.join(" "),
206
+ scp: requested,
207
+ v: "2"
208
+ };
209
+ if (options.organizationCode) payload.org_code = options.organizationCode;
210
+ if (options.permissions !== void 0) payload.permissions = [...options.permissions];
211
+ Object.assign(payload, options.claims ?? {});
212
+ return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
213
+ }
192
214
  async tokenFor(scenario, overrides = {}) {
193
215
  if (scenario.kind === "unauthenticated") return null;
194
216
  return this.token({
@@ -242,6 +264,9 @@ var KindeTestkit = class _KindeTestkit {
242
264
  if (scenario.kind === "unauthenticated") return null;
243
265
  return scenarioPrincipal(scenario, this.issuer);
244
266
  }
267
+ async signPayload(payload, invalid2) {
268
+ return this.sign(payload, invalid2);
269
+ }
245
270
  async sign(payload, invalid2) {
246
271
  if (invalid2 === "unsigned") {
247
272
  const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
@@ -258,6 +283,7 @@ var KindeTestkit = class _KindeTestkit {
258
283
  };
259
284
  function scenarioPrincipal(scenario, issuer) {
260
285
  return {
286
+ type: "user",
261
287
  subject: scenario.user.id,
262
288
  issuer,
263
289
  organization: scenario.organization ? { code: scenario.organization.code } : null,
@@ -345,6 +371,20 @@ function resolveSeed(input) {
345
371
  const rawUsers = listOf(input.users, "users", problems);
346
372
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
347
373
  const rawMemberships = listOf(input.memberships, "memberships", problems);
374
+ const rawApplications = listOf(input.applications, "applications", problems);
375
+ const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
376
+ const webhooks = [];
377
+ rawWebhooks.forEach((raw, index) => {
378
+ if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
379
+ problems.push(`webhooks[${index}] needs an http or https "url".`);
380
+ return;
381
+ }
382
+ if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
383
+ problems.push(`webhooks[${index}].events must be a list of event type names.`);
384
+ return;
385
+ }
386
+ webhooks.push({ url: raw.url, events: raw.events });
387
+ });
348
388
  const users = [];
349
389
  rawUsers.forEach((raw, index) => {
350
390
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -400,10 +440,43 @@ function resolveSeed(input) {
400
440
  })
401
441
  );
402
442
  });
443
+ const applications = [];
444
+ rawApplications.forEach((raw, index) => {
445
+ if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
446
+ problems.push(`applications[${index}] needs a string "clientId".`);
447
+ return;
448
+ }
449
+ if (applications.some((app) => app.clientId === raw.clientId)) {
450
+ problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
451
+ return;
452
+ }
453
+ if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
454
+ problems.push(`applications[${index}].clientSecret must be a string.`);
455
+ }
456
+ if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
457
+ problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
458
+ }
459
+ for (const field of ["scopes", "permissions"]) {
460
+ const value = raw[field];
461
+ if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
462
+ problems.push(`applications[${index}].${field} must be a list of strings.`);
463
+ }
464
+ }
465
+ const audience = raw.audience;
466
+ applications.push({
467
+ clientId: raw.clientId,
468
+ clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
469
+ name: typeof raw.name === "string" ? raw.name : raw.clientId,
470
+ organizationCode: typeof raw.organization === "string" ? raw.organization : null,
471
+ scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
472
+ permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
473
+ audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
474
+ });
475
+ });
403
476
  if (problems.length > 0) {
404
477
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
405
478
  }
406
- return { users, organizations, memberships };
479
+ return { users, organizations, memberships, applications, webhooks };
407
480
  }
408
481
  function findUser(users, ref) {
409
482
  const needle = ref.toLowerCase();
@@ -540,12 +613,14 @@ var OAuthError = class extends Error {
540
613
  error;
541
614
  };
542
615
  var AuthorizationServer = class {
543
- constructor(testkit, seed) {
616
+ constructor(testkit, seed, emit = () => void 0) {
544
617
  this.testkit = testkit;
545
618
  this.seed = seed;
619
+ this.emit = emit;
546
620
  }
547
621
  testkit;
548
622
  seed;
623
+ emit;
549
624
  codes = /* @__PURE__ */ new Map();
550
625
  refreshTokens = /* @__PURE__ */ new Map();
551
626
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -663,6 +738,7 @@ var AuthorizationServer = class {
663
738
  codeChallengeMethod: request.codeChallengeMethod,
664
739
  expiresAt: Date.now() + CODE_LIFETIME_MS
665
740
  });
741
+ this.emit("user.authenticated", user);
666
742
  const target = new URL(request.redirectUri);
667
743
  target.searchParams.set("code", code);
668
744
  if (request.state !== null) target.searchParams.set("state", request.state);
@@ -672,13 +748,16 @@ var AuthorizationServer = class {
672
748
  try {
673
749
  const clientId = clientIdFrom(req, form);
674
750
  const grantType = form.grant_type;
751
+ if (grantType === "client_credentials") {
752
+ return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
753
+ }
675
754
  let grant;
676
755
  if (grantType === "authorization_code") {
677
756
  grant = this.redeemCode(form, clientId);
678
757
  } else if (grantType === "refresh_token") {
679
758
  grant = this.redeemRefreshToken(form, clientId);
680
759
  } else {
681
- throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and refresh_token, not "${grantType ?? ""}".`);
760
+ throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
682
761
  }
683
762
  sendJson(res, 200, await this.issueTokens(grant));
684
763
  } catch (error) {
@@ -688,6 +767,33 @@ var AuthorizationServer = class {
688
767
  throw error;
689
768
  }
690
769
  }
770
+ async clientCredentials(clientId, clientSecret, form) {
771
+ const app = this.seed.applications.find((a) => a.clientId === clientId);
772
+ if (app?.clientSecret && app.clientSecret !== clientSecret) {
773
+ throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
774
+ }
775
+ const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
776
+ const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
777
+ const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
778
+ return {
779
+ access_token: await this.testkit.m2mToken({
780
+ clientId,
781
+ organizationCode: app?.organizationCode ?? null,
782
+ scopes: requested,
783
+ grantedScopes: granted,
784
+ audience: audience.length > 0 ? audience : app?.audience ?? void 0,
785
+ permissions: app?.permissions ?? void 0
786
+ }),
787
+ expires_in: this.testkit.accessTokenLifetime,
788
+ scope: granted.join(" "),
789
+ token_type: "bearer"
790
+ };
791
+ }
792
+ reset() {
793
+ this.codes.clear();
794
+ this.refreshTokens.clear();
795
+ this.signedUpUsers.clear();
796
+ }
691
797
  redeemCode(form, clientId) {
692
798
  const code = form.code ?? "";
693
799
  const pending = this.codes.get(code);
@@ -798,8 +904,11 @@ var AuthorizationServer = class {
798
904
  if (seeded) return seeded;
799
905
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
800
906
  const user = createKindeUser({ email: ref.toLowerCase() });
801
- this.signedUpUsers.set(user.id, user);
802
- return user;
907
+ if (!this.signedUpUsers.has(user.id)) {
908
+ this.signedUpUsers.set(user.id, user);
909
+ this.emit("user.created", user);
910
+ }
911
+ return this.signedUpUsers.get(user.id);
803
912
  }
804
913
  organization(code) {
805
914
  return this.seed.organizations.find((org) => org.code === code) ?? null;
@@ -859,6 +968,15 @@ function clientIdFrom(req, form) {
859
968
  if (form.client_id) return form.client_id;
860
969
  throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
861
970
  }
971
+ function clientSecretFrom(req, form) {
972
+ const header = req.headers.authorization ?? "";
973
+ if (header.startsWith("Basic ")) {
974
+ const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
975
+ const index = decoded.indexOf(":");
976
+ if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
977
+ }
978
+ return form.client_secret ?? null;
979
+ }
862
980
  function redirectWithError(res, request, error, description) {
863
981
  const target = new URL(request.redirectUri);
864
982
  target.searchParams.set("error", error);
@@ -899,6 +1017,351 @@ function sendJson(res, status, body) {
899
1017
  res.end(JSON.stringify(body));
900
1018
  }
901
1019
 
1020
+ // src/failures.ts
1021
+ var MAX_DELAY_MS = 6e4;
1022
+ var FailureInjector = class {
1023
+ rules = [];
1024
+ nextId = 1;
1025
+ add(rule) {
1026
+ const problems = validate(rule);
1027
+ if (problems.length > 0) {
1028
+ throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
1029
+ }
1030
+ const active = {
1031
+ id: `failure_${this.nextId++}`,
1032
+ path: rule.path,
1033
+ method: rule.method ? rule.method.toUpperCase() : null,
1034
+ status: rule.status ?? null,
1035
+ delayMs: rule.delayMs ?? 0,
1036
+ hang: rule.hang ?? false,
1037
+ remaining: rule.times ?? null,
1038
+ retryAfter: rule.retryAfter ?? 1,
1039
+ hits: 0
1040
+ };
1041
+ this.rules.push(active);
1042
+ return { ...active };
1043
+ }
1044
+ remove(id) {
1045
+ const before = this.rules.length;
1046
+ this.rules = this.rules.filter((rule) => rule.id !== id);
1047
+ return this.rules.length < before;
1048
+ }
1049
+ clear() {
1050
+ this.rules = [];
1051
+ }
1052
+ list() {
1053
+ return this.rules.map((rule) => ({ ...rule }));
1054
+ }
1055
+ take(method, path) {
1056
+ const rule = this.rules.find((r) => matches(r, method, path));
1057
+ if (!rule) return null;
1058
+ rule.hits += 1;
1059
+ if (rule.remaining !== null) {
1060
+ rule.remaining -= 1;
1061
+ if (rule.remaining <= 0) this.remove(rule.id);
1062
+ }
1063
+ return { ...rule };
1064
+ }
1065
+ };
1066
+ function failureBody(status) {
1067
+ const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
1068
+ return { error, error_description: `kinde-testkit injected a ${status} response.` };
1069
+ }
1070
+ function matches(rule, method, path) {
1071
+ if (rule.method && rule.method !== method.toUpperCase()) return false;
1072
+ if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
1073
+ return rule.path === path;
1074
+ }
1075
+ function validate(rule) {
1076
+ const problems = [];
1077
+ if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
1078
+ problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
1079
+ } else if (rule.path.startsWith("/testkit/")) {
1080
+ problems.push("Failures cannot target /testkit/ control endpoints.");
1081
+ }
1082
+ if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
1083
+ problems.push('"status" must be an HTTP error status between 400 and 599.');
1084
+ }
1085
+ if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
1086
+ problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
1087
+ }
1088
+ if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
1089
+ problems.push('"times" must be a whole number of 1 or more.');
1090
+ }
1091
+ if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
1092
+ problems.push('"retryAfter" must be a whole number of seconds.');
1093
+ }
1094
+ if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
1095
+ problems.push('Set at least one of "status", "delayMs" or "hang".');
1096
+ }
1097
+ return problems;
1098
+ }
1099
+
1100
+ // src/webhooks.ts
1101
+ import { randomBytes as randomBytes2 } from "crypto";
1102
+ var WEBHOOK_EVENT_TYPES = [
1103
+ "user.created",
1104
+ "user.updated",
1105
+ "user.deleted",
1106
+ "user.authenticated",
1107
+ "user.authentication_failed",
1108
+ "organization.created",
1109
+ "organization.updated",
1110
+ "organization.deleted",
1111
+ "role.created",
1112
+ "role.updated",
1113
+ "role.deleted",
1114
+ "permission.created",
1115
+ "permission.updated",
1116
+ "permission.deleted",
1117
+ "subscriber.created",
1118
+ "access_request.created"
1119
+ ];
1120
+ var BILLING_EVENT_TYPES = [
1121
+ "customer.agreement_cancelled",
1122
+ "customer.agreement_created",
1123
+ "customer.invoice_overdue",
1124
+ "customer.meter_usage_updated",
1125
+ "customer.payment_failed",
1126
+ "customer.payment_succeeded",
1127
+ "customer.plan_assigned",
1128
+ "customer.plan_changed"
1129
+ ];
1130
+ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
1131
+ var DEFAULT_TIMEOUT_MS = 5e3;
1132
+ var MAX_DUPLICATES = 10;
1133
+ var WebhookDispatcher = class {
1134
+ constructor(testkit, seed, endpoints = [], options = {}) {
1135
+ this.testkit = testkit;
1136
+ this.seed = seed;
1137
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
1138
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1139
+ for (const endpoint of endpoints) this.addEndpoint(endpoint);
1140
+ this.seededEndpoints = [...this.endpoints];
1141
+ }
1142
+ testkit;
1143
+ seed;
1144
+ endpoints = [];
1145
+ seededEndpoints = [];
1146
+ log = [];
1147
+ nextEndpoint = 1;
1148
+ retryDelaysMs;
1149
+ timeoutMs;
1150
+ addEndpoint(input) {
1151
+ if (!isHttpUrl2(input.url)) {
1152
+ throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
1153
+ }
1154
+ if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
1155
+ throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
1156
+ }
1157
+ const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
1158
+ this.endpoints.push(endpoint);
1159
+ return { ...endpoint };
1160
+ }
1161
+ removeEndpoint(id) {
1162
+ const before = this.endpoints.length;
1163
+ this.endpoints = this.endpoints.filter((e) => e.id !== id);
1164
+ return this.endpoints.length < before;
1165
+ }
1166
+ listEndpoints() {
1167
+ return this.endpoints.map((e) => ({ ...e }));
1168
+ }
1169
+ deliveries() {
1170
+ return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
1171
+ }
1172
+ reset() {
1173
+ this.log = [];
1174
+ this.endpoints = [...this.seededEndpoints];
1175
+ }
1176
+ buildEvent(options) {
1177
+ if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
1178
+ throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
1179
+ }
1180
+ const now = /* @__PURE__ */ new Date();
1181
+ const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
1182
+ const event = {
1183
+ data: options.data ?? this.buildData(options),
1184
+ event_id: `event_${randomBytes2(16).toString("hex")}`,
1185
+ event_timestamp: timestamp,
1186
+ source: options.source ?? "admin",
1187
+ timestamp,
1188
+ type: options.type
1189
+ };
1190
+ if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
1191
+ event.ip_address = options.ipAddress ?? "127.0.0.1";
1192
+ }
1193
+ return event;
1194
+ }
1195
+ async send(options) {
1196
+ const event = this.buildEvent(options);
1197
+ const copies = options.duplicate ?? 1;
1198
+ if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
1199
+ throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
1200
+ }
1201
+ const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
1202
+ if (options.to && !isHttpUrl2(options.to)) {
1203
+ throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
1204
+ }
1205
+ if (targets.length === 0) {
1206
+ throw new TestkitError(
1207
+ "INVALID_REQUEST",
1208
+ `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
1209
+ );
1210
+ }
1211
+ if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
1212
+ const signed = await this.testkit.signPayload(
1213
+ event,
1214
+ options.invalid === "stale" ? void 0 : options.invalid
1215
+ );
1216
+ const jobs = targets.flatMap((target) => {
1217
+ const webhookId = `wh_${randomBytes2(12).toString("hex")}`;
1218
+ return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
1219
+ });
1220
+ return Promise.all(jobs);
1221
+ }
1222
+ async deliver(url, webhookId, body, event, copy) {
1223
+ const delivery = {
1224
+ webhookId,
1225
+ eventId: String(event.event_id),
1226
+ type: String(event.type),
1227
+ url,
1228
+ copy,
1229
+ delivered: false,
1230
+ attempts: [],
1231
+ payload: event
1232
+ };
1233
+ this.log.push(delivery);
1234
+ for (const [index, delay] of this.retryDelaysMs.entries()) {
1235
+ if (delay > 0) await sleep(delay);
1236
+ const started = Date.now();
1237
+ try {
1238
+ const response = await fetch(url, {
1239
+ method: "POST",
1240
+ headers: { "content-type": "application/jwt", "webhook-id": webhookId },
1241
+ body,
1242
+ signal: AbortSignal.timeout(this.timeoutMs)
1243
+ });
1244
+ await response.arrayBuffer().catch(() => void 0);
1245
+ delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
1246
+ if (response.status === 200) {
1247
+ delivery.delivered = true;
1248
+ break;
1249
+ }
1250
+ } catch (error) {
1251
+ const name = error.name;
1252
+ delivery.attempts.push({
1253
+ attempt: index + 1,
1254
+ status: null,
1255
+ error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
1256
+ durationMs: Date.now() - started
1257
+ });
1258
+ }
1259
+ }
1260
+ return { ...delivery, attempts: [...delivery.attempts] };
1261
+ }
1262
+ buildData(options) {
1263
+ const [subject] = options.type.split(".");
1264
+ switch (subject) {
1265
+ case "user":
1266
+ return { user: this.userData(options) };
1267
+ case "organization":
1268
+ return { organization: this.organizationData(options) };
1269
+ case "role":
1270
+ return { role: this.namedData(options, "role") };
1271
+ case "permission":
1272
+ return { permission: this.namedData(options, "permission") };
1273
+ case "subscriber": {
1274
+ const user = this.requireUser(options);
1275
+ return {
1276
+ subscriber: {
1277
+ email: user.email,
1278
+ first_name: user.givenName,
1279
+ id: stableId("sub", user.id),
1280
+ last_name: user.familyName,
1281
+ user_id: user.id
1282
+ }
1283
+ };
1284
+ }
1285
+ case "access_request": {
1286
+ const user = this.requireUser(options);
1287
+ return {
1288
+ access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
1289
+ };
1290
+ }
1291
+ default:
1292
+ throw new TestkitError(
1293
+ "INVALID_REQUEST",
1294
+ `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
1295
+ );
1296
+ }
1297
+ }
1298
+ emitForUser(type, user) {
1299
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
1300
+ const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
1301
+ void this.send({ type, data, source: "user" }).catch(() => void 0);
1302
+ }
1303
+ userData(options) {
1304
+ const user = this.requireUser(options);
1305
+ if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
1306
+ return this.userPayload(user);
1307
+ }
1308
+ userPayload(user) {
1309
+ return {
1310
+ email: user.email,
1311
+ first_name: user.givenName,
1312
+ id: user.id,
1313
+ is_password_reset_requested: false,
1314
+ is_suspended: false,
1315
+ last_name: user.familyName,
1316
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
1317
+ code: m.organizationCode,
1318
+ permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
1319
+ roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
1320
+ })),
1321
+ phone: null,
1322
+ username: typeof user.claims.username === "string" ? user.claims.username : null
1323
+ };
1324
+ }
1325
+ organizationData(options) {
1326
+ if (!options.organization) {
1327
+ throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
1328
+ }
1329
+ const org = this.seed.organizations.find((o) => o.code === options.organization);
1330
+ if (options.type === "organization.deleted") return { code: options.organization };
1331
+ const name = org?.name ?? titleCase(options.organization);
1332
+ const data = { code: options.organization, external_id: null, handle: slug(name), name };
1333
+ if (options.type === "organization.updated") data.is_allow_registrations = false;
1334
+ return data;
1335
+ }
1336
+ namedData(options, kind) {
1337
+ const key = kind === "role" ? options.role : options.permission;
1338
+ if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
1339
+ const id = stableId(kind === "role" ? "role" : "perm", key);
1340
+ if (options.type.endsWith(".deleted")) return { id };
1341
+ const data = { description: "", id, key, name: titleCase(key) };
1342
+ if (kind === "role") data.is_default_role = false;
1343
+ return data;
1344
+ }
1345
+ requireUser(options) {
1346
+ if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
1347
+ const user = findUser(this.seed.users, options.user);
1348
+ if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
1349
+ return user;
1350
+ }
1351
+ };
1352
+ function isHttpUrl2(value) {
1353
+ if (typeof value !== "string") return false;
1354
+ try {
1355
+ const { protocol } = new URL(value);
1356
+ return protocol === "http:" || protocol === "https:";
1357
+ } catch {
1358
+ return false;
1359
+ }
1360
+ }
1361
+ function sleep(ms) {
1362
+ return new Promise((resolve) => setTimeout(resolve, ms));
1363
+ }
1364
+
902
1365
  // src/server.ts
903
1366
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
904
1367
  var MAX_BODY_BYTES = 64 * 1024;
@@ -912,12 +1375,11 @@ async function startKindeTestkit(options = {}) {
912
1375
  );
913
1376
  }
914
1377
  const seed = resolveSeed(options.seed ?? {});
1378
+ const failures = new FailureInjector();
915
1379
  let ready;
916
- const testkitReady = new Promise(
917
- (resolve) => ready = resolve
918
- );
1380
+ const testkitReady = new Promise((resolve) => ready = resolve);
919
1381
  const server = createServer((req, res) => {
920
- testkitReady.then(({ testkit: testkit2, auth }) => handle(req, res, testkit2, auth, seed)).catch((error) => sendError(res, error));
1382
+ testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
921
1383
  });
922
1384
  await new Promise((resolve, reject) => {
923
1385
  server.once("error", reject);
@@ -931,7 +1393,14 @@ async function startKindeTestkit(options = {}) {
931
1393
  audience: options.audience ?? options.seed?.audience,
932
1394
  clientId: options.clientId ?? options.seed?.clientId
933
1395
  });
934
- ready({ testkit, auth: new AuthorizationServer(testkit, seed) });
1396
+ const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
1397
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
1398
+ const reset = () => {
1399
+ auth.reset();
1400
+ failures.clear();
1401
+ webhooks.reset();
1402
+ };
1403
+ ready({ testkit, auth, seed, failures, webhooks, reset });
935
1404
  return {
936
1405
  url,
937
1406
  issuer: testkit.issuer,
@@ -939,16 +1408,32 @@ async function startKindeTestkit(options = {}) {
939
1408
  jwksUri: `${url}/.well-known/jwks`,
940
1409
  testkit,
941
1410
  seed,
1411
+ failures,
1412
+ webhooks,
1413
+ reset,
942
1414
  close: () => new Promise((resolve, reject) => {
943
1415
  server.closeAllConnections();
944
1416
  server.close((error) => error ? reject(error) : resolve());
945
1417
  })
946
1418
  };
947
1419
  }
948
- async function handle(req, res, testkit, auth, seed) {
1420
+ async function handle(req, res, context) {
1421
+ const { testkit, auth, seed, failures, webhooks } = context;
949
1422
  const url = new URL(req.url ?? "/", "http://localhost");
950
1423
  const { pathname } = url;
951
1424
  const method = req.method ?? "GET";
1425
+ if (!pathname.startsWith("/testkit/")) {
1426
+ const failure = failures.take(method, pathname);
1427
+ if (failure) {
1428
+ if (failure.hang) return;
1429
+ if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
1430
+ if (failure.status !== null) {
1431
+ const headers = {};
1432
+ if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
1433
+ return sendJson2(res, failure.status, failureBody(failure.status), headers);
1434
+ }
1435
+ }
1436
+ }
952
1437
  if (await auth.handle(req, res, url, () => readForm(req))) return;
953
1438
  if (method === "GET" && pathname === "/.well-known/openid-configuration") {
954
1439
  return sendJson2(res, 200, discovery(testkit));
@@ -966,6 +1451,37 @@ async function handle(req, res, testkit, auth, seed) {
966
1451
  if (method === "GET" && pathname === "/testkit/memberships") {
967
1452
  return sendJson2(res, 200, seed.memberships);
968
1453
  }
1454
+ if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
1455
+ if (method === "POST" && pathname === "/testkit/failures") {
1456
+ return sendJson2(res, 201, failures.add(await readJson(req)));
1457
+ }
1458
+ if (method === "DELETE" && pathname === "/testkit/failures") {
1459
+ failures.clear();
1460
+ return sendJson2(res, 200, { ok: true });
1461
+ }
1462
+ if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
1463
+ const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1464
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1465
+ }
1466
+ if (method === "POST" && pathname === "/testkit/webhooks") {
1467
+ return sendJson2(res, 200, await webhooks.send(await readJson(req)));
1468
+ }
1469
+ if (method === "GET" && pathname === "/testkit/webhooks/types") {
1470
+ return sendJson2(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
1471
+ }
1472
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson2(res, 200, webhooks.deliveries());
1473
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson2(res, 200, webhooks.listEndpoints());
1474
+ if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
1475
+ return sendJson2(res, 201, webhooks.addEndpoint(await readJson(req)));
1476
+ }
1477
+ if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
1478
+ const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
1479
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1480
+ }
1481
+ if (method === "POST" && pathname === "/testkit/reset") {
1482
+ context.reset();
1483
+ return sendJson2(res, 200, { ok: true });
1484
+ }
969
1485
  if (method === "POST" && pathname === "/testkit/token") {
970
1486
  const body = await readJson(req);
971
1487
  const accessToken = await issueToken(testkit, seed, body);
@@ -1005,6 +1521,21 @@ async function issueToken(testkit, seed, body) {
1005
1521
  ]);
1006
1522
  }
1007
1523
  const expiresIn = input.expiresIn;
1524
+ if (input.m2m === true) {
1525
+ const clientId = optionalString(input, "clientId");
1526
+ const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
1527
+ const scopes = optionalStrings(input, "scopes") ?? [];
1528
+ return testkit.m2mToken({
1529
+ clientId,
1530
+ organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
1531
+ scopes,
1532
+ grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
1533
+ audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
1534
+ permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
1535
+ expiresIn,
1536
+ invalid: invalid2
1537
+ });
1538
+ }
1008
1539
  const permissions = optionalStrings(input, "permissions");
1009
1540
  const roles = optionalStrings(input, "roles");
1010
1541
  const userRef = optionalString(input, "user");
@@ -1080,10 +1611,11 @@ async function readText(req) {
1080
1611
  }
1081
1612
  return Buffer.concat(chunks).toString("utf8").trim();
1082
1613
  }
1083
- function sendJson2(res, status, body) {
1614
+ function sendJson2(res, status, body, headers = {}) {
1084
1615
  res.writeHead(status, {
1085
1616
  "content-type": "application/json; charset=utf-8",
1086
- "cache-control": "no-store"
1617
+ "cache-control": "no-store",
1618
+ ...headers
1087
1619
  });
1088
1620
  res.end(JSON.stringify(body));
1089
1621
  }
@@ -1140,7 +1672,14 @@ function useKindeTestkit(options = {}) {
1140
1672
  get testkit() {
1141
1673
  return current().testkit;
1142
1674
  },
1143
- auth: (scenario, token) => kindeTest({ scenario, testkit: current().testkit, token })
1675
+ get failures() {
1676
+ return current().failures;
1677
+ },
1678
+ get webhooks() {
1679
+ return current().webhooks;
1680
+ },
1681
+ auth: (scenario, token) => kindeTest({ scenario, testkit: current().testkit, token }),
1682
+ reset: () => current().reset()
1144
1683
  };
1145
1684
  }
1146
1685
  export {