kinde-testkit 0.3.0 → 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/index.d.cts CHANGED
@@ -180,6 +180,7 @@ declare class KindeTestkit {
180
180
  idTokenFor(scenario: Scenario, options?: IdTokenOptions): Promise<string | null>;
181
181
  headersFor(scenario: Scenario, overrides?: ScenarioTokenOverrides): Promise<Record<string, string>>;
182
182
  principalFor(scenario: Scenario): KindePrincipal | null;
183
+ signPayload(payload: Record<string, unknown>, invalid?: "bad-signature" | "unknown-key" | "unsigned"): Promise<string>;
183
184
  private sign;
184
185
  private stranger;
185
186
  }
@@ -211,6 +212,10 @@ interface TestkitSeed {
211
212
  roles?: string[];
212
213
  permissions?: string[];
213
214
  }>;
215
+ webhooks?: Array<{
216
+ url: string;
217
+ events?: string[];
218
+ }>;
214
219
  applications?: Array<{
215
220
  clientId: string;
216
221
  clientSecret?: string;
@@ -226,6 +231,10 @@ interface ResolvedSeed {
226
231
  organizations: KindeOrganization[];
227
232
  memberships: KindeMembership[];
228
233
  applications: KindeApplication[];
234
+ webhooks: Array<{
235
+ url: string;
236
+ events?: string[];
237
+ }>;
229
238
  }
230
239
  declare function resolveSeed(input: unknown): ResolvedSeed;
231
240
  declare function seedScenario(seed: ResolvedSeed, ref: {
@@ -263,6 +272,80 @@ declare class FailureInjector {
263
272
  take(method: string, path: string): ActiveFailure | null;
264
273
  }
265
274
 
275
+ declare const WEBHOOK_EVENT_TYPES: readonly ["user.created", "user.updated", "user.deleted", "user.authenticated", "user.authentication_failed", "organization.created", "organization.updated", "organization.deleted", "role.created", "role.updated", "role.deleted", "permission.created", "permission.updated", "permission.deleted", "subscriber.created", "access_request.created"];
276
+ declare const BILLING_EVENT_TYPES: readonly ["customer.agreement_cancelled", "customer.agreement_created", "customer.invoice_overdue", "customer.meter_usage_updated", "customer.payment_failed", "customer.payment_succeeded", "customer.plan_assigned", "customer.plan_changed"];
277
+ type WebhookInvalidKind = "bad-signature" | "unknown-key" | "unsigned" | "stale";
278
+ type WebhookSource = "admin" | "api" | "user";
279
+ interface WebhookEndpointInput {
280
+ url: string;
281
+ events?: string[];
282
+ }
283
+ interface WebhookEndpoint {
284
+ id: string;
285
+ url: string;
286
+ events: string[] | null;
287
+ }
288
+ interface SendWebhookOptions {
289
+ type: string;
290
+ data?: Record<string, unknown>;
291
+ user?: string;
292
+ organization?: string;
293
+ role?: string;
294
+ permission?: string;
295
+ source?: WebhookSource;
296
+ ipAddress?: string;
297
+ to?: string;
298
+ duplicate?: number;
299
+ delayMs?: number;
300
+ invalid?: WebhookInvalidKind;
301
+ }
302
+ interface WebhookAttempt {
303
+ attempt: number;
304
+ status: number | null;
305
+ error: string | null;
306
+ durationMs: number;
307
+ }
308
+ interface WebhookDelivery {
309
+ webhookId: string;
310
+ eventId: string;
311
+ type: string;
312
+ url: string;
313
+ copy: number;
314
+ delivered: boolean;
315
+ attempts: WebhookAttempt[];
316
+ payload: Record<string, unknown>;
317
+ }
318
+ interface WebhookOptions {
319
+ retryDelaysMs?: number[];
320
+ timeoutMs?: number;
321
+ }
322
+ declare class WebhookDispatcher {
323
+ private readonly testkit;
324
+ private readonly seed;
325
+ private endpoints;
326
+ private seededEndpoints;
327
+ private log;
328
+ private nextEndpoint;
329
+ private readonly retryDelaysMs;
330
+ private readonly timeoutMs;
331
+ constructor(testkit: KindeTestkit, seed: ResolvedSeed, endpoints?: WebhookEndpointInput[], options?: WebhookOptions);
332
+ addEndpoint(input: WebhookEndpointInput): WebhookEndpoint;
333
+ removeEndpoint(id: string): boolean;
334
+ listEndpoints(): WebhookEndpoint[];
335
+ deliveries(): WebhookDelivery[];
336
+ reset(): void;
337
+ buildEvent(options: SendWebhookOptions): Record<string, unknown>;
338
+ send(options: SendWebhookOptions): Promise<WebhookDelivery[]>;
339
+ private deliver;
340
+ private buildData;
341
+ emitForUser(type: "user.created" | "user.authenticated", user: KindeUser): void;
342
+ private userData;
343
+ private userPayload;
344
+ private organizationData;
345
+ private namedData;
346
+ private requireUser;
347
+ }
348
+
266
349
  interface StartKindeTestkitOptions {
267
350
  port?: number;
268
351
  host?: string;
@@ -271,6 +354,7 @@ interface StartKindeTestkitOptions {
271
354
  clientId?: string;
272
355
  seed?: TestkitSeed;
273
356
  allowPublic?: boolean;
357
+ webhooks?: WebhookOptions;
274
358
  }
275
359
  interface RunningKindeTestkit {
276
360
  url: string;
@@ -280,6 +364,7 @@ interface RunningKindeTestkit {
280
364
  testkit: KindeTestkit;
281
365
  seed: ResolvedSeed;
282
366
  failures: FailureInjector;
367
+ webhooks: WebhookDispatcher;
283
368
  reset(): void;
284
369
  close(): Promise<void>;
285
370
  }
@@ -321,4 +406,4 @@ declare function runDoctor(options: {
321
406
  }): Promise<DoctorReport>;
322
407
  declare function parseEnvFile(text: string): Record<string, string>;
323
408
 
324
- export { type ActiveFailure, type AuthenticatedScenario, type Check, type CheckStatus, type CreateKindeOrganizationOptions, type CreateKindeUserOptions, type CreateMembershipOptions, DEFAULT_AUTH_METHODS, DEFAULT_CLIENT_ID, DEFAULT_ISSUER, DEFAULT_M2M_CLIENT_ID, DEFAULT_SCOPES, type DoctorReport, type Duration, FailureInjector, type FailureRule, INVALID_TOKEN_KINDS, type IdTokenOptions, type InvalidTokenKind, type KindeApplication, type KindeMembership, type KindeOrganization, type KindePrincipal, type KindeRole, KindeTestkit, type KindeTestkitOptions, type KindeTokenOptions, type KindeUser, type M2MTokenOptions, type ResolvedSeed, type RunningKindeTestkit, type Scenario, ScenarioBuilder, type ScenarioTokenOverrides, type StartKindeTestkitOptions, TestkitError, type TestkitErrorCode, type TestkitSeed, type TokenInspection, type UnauthenticatedScenario, createKindeOrganization, createKindeToken, createKindeUser, createMembership, getDefaultTestkit, inspectToken, isAuthenticated, parseEnvFile, principalFromClaims, resetFactories, resolveSeed, runDoctor, scenario, seedScenario, startKindeTestkit, toKindeRole };
409
+ export { type ActiveFailure, type AuthenticatedScenario, BILLING_EVENT_TYPES, type Check, type CheckStatus, type CreateKindeOrganizationOptions, type CreateKindeUserOptions, type CreateMembershipOptions, DEFAULT_AUTH_METHODS, DEFAULT_CLIENT_ID, DEFAULT_ISSUER, DEFAULT_M2M_CLIENT_ID, DEFAULT_SCOPES, type DoctorReport, type Duration, FailureInjector, type FailureRule, INVALID_TOKEN_KINDS, type IdTokenOptions, type InvalidTokenKind, type KindeApplication, type KindeMembership, type KindeOrganization, type KindePrincipal, type KindeRole, KindeTestkit, type KindeTestkitOptions, type KindeTokenOptions, type KindeUser, type M2MTokenOptions, type ResolvedSeed, type RunningKindeTestkit, type Scenario, ScenarioBuilder, type ScenarioTokenOverrides, type SendWebhookOptions, type StartKindeTestkitOptions, TestkitError, type TestkitErrorCode, type TestkitSeed, type TokenInspection, type UnauthenticatedScenario, WEBHOOK_EVENT_TYPES, type WebhookAttempt, type WebhookDelivery, WebhookDispatcher, type WebhookEndpoint, type WebhookEndpointInput, type WebhookInvalidKind, type WebhookOptions, type WebhookSource, createKindeOrganization, createKindeToken, createKindeUser, createMembership, getDefaultTestkit, inspectToken, isAuthenticated, parseEnvFile, principalFromClaims, resetFactories, resolveSeed, runDoctor, scenario, seedScenario, startKindeTestkit, toKindeRole };
package/dist/index.d.ts CHANGED
@@ -180,6 +180,7 @@ declare class KindeTestkit {
180
180
  idTokenFor(scenario: Scenario, options?: IdTokenOptions): Promise<string | null>;
181
181
  headersFor(scenario: Scenario, overrides?: ScenarioTokenOverrides): Promise<Record<string, string>>;
182
182
  principalFor(scenario: Scenario): KindePrincipal | null;
183
+ signPayload(payload: Record<string, unknown>, invalid?: "bad-signature" | "unknown-key" | "unsigned"): Promise<string>;
183
184
  private sign;
184
185
  private stranger;
185
186
  }
@@ -211,6 +212,10 @@ interface TestkitSeed {
211
212
  roles?: string[];
212
213
  permissions?: string[];
213
214
  }>;
215
+ webhooks?: Array<{
216
+ url: string;
217
+ events?: string[];
218
+ }>;
214
219
  applications?: Array<{
215
220
  clientId: string;
216
221
  clientSecret?: string;
@@ -226,6 +231,10 @@ interface ResolvedSeed {
226
231
  organizations: KindeOrganization[];
227
232
  memberships: KindeMembership[];
228
233
  applications: KindeApplication[];
234
+ webhooks: Array<{
235
+ url: string;
236
+ events?: string[];
237
+ }>;
229
238
  }
230
239
  declare function resolveSeed(input: unknown): ResolvedSeed;
231
240
  declare function seedScenario(seed: ResolvedSeed, ref: {
@@ -263,6 +272,80 @@ declare class FailureInjector {
263
272
  take(method: string, path: string): ActiveFailure | null;
264
273
  }
265
274
 
275
+ declare const WEBHOOK_EVENT_TYPES: readonly ["user.created", "user.updated", "user.deleted", "user.authenticated", "user.authentication_failed", "organization.created", "organization.updated", "organization.deleted", "role.created", "role.updated", "role.deleted", "permission.created", "permission.updated", "permission.deleted", "subscriber.created", "access_request.created"];
276
+ declare const BILLING_EVENT_TYPES: readonly ["customer.agreement_cancelled", "customer.agreement_created", "customer.invoice_overdue", "customer.meter_usage_updated", "customer.payment_failed", "customer.payment_succeeded", "customer.plan_assigned", "customer.plan_changed"];
277
+ type WebhookInvalidKind = "bad-signature" | "unknown-key" | "unsigned" | "stale";
278
+ type WebhookSource = "admin" | "api" | "user";
279
+ interface WebhookEndpointInput {
280
+ url: string;
281
+ events?: string[];
282
+ }
283
+ interface WebhookEndpoint {
284
+ id: string;
285
+ url: string;
286
+ events: string[] | null;
287
+ }
288
+ interface SendWebhookOptions {
289
+ type: string;
290
+ data?: Record<string, unknown>;
291
+ user?: string;
292
+ organization?: string;
293
+ role?: string;
294
+ permission?: string;
295
+ source?: WebhookSource;
296
+ ipAddress?: string;
297
+ to?: string;
298
+ duplicate?: number;
299
+ delayMs?: number;
300
+ invalid?: WebhookInvalidKind;
301
+ }
302
+ interface WebhookAttempt {
303
+ attempt: number;
304
+ status: number | null;
305
+ error: string | null;
306
+ durationMs: number;
307
+ }
308
+ interface WebhookDelivery {
309
+ webhookId: string;
310
+ eventId: string;
311
+ type: string;
312
+ url: string;
313
+ copy: number;
314
+ delivered: boolean;
315
+ attempts: WebhookAttempt[];
316
+ payload: Record<string, unknown>;
317
+ }
318
+ interface WebhookOptions {
319
+ retryDelaysMs?: number[];
320
+ timeoutMs?: number;
321
+ }
322
+ declare class WebhookDispatcher {
323
+ private readonly testkit;
324
+ private readonly seed;
325
+ private endpoints;
326
+ private seededEndpoints;
327
+ private log;
328
+ private nextEndpoint;
329
+ private readonly retryDelaysMs;
330
+ private readonly timeoutMs;
331
+ constructor(testkit: KindeTestkit, seed: ResolvedSeed, endpoints?: WebhookEndpointInput[], options?: WebhookOptions);
332
+ addEndpoint(input: WebhookEndpointInput): WebhookEndpoint;
333
+ removeEndpoint(id: string): boolean;
334
+ listEndpoints(): WebhookEndpoint[];
335
+ deliveries(): WebhookDelivery[];
336
+ reset(): void;
337
+ buildEvent(options: SendWebhookOptions): Record<string, unknown>;
338
+ send(options: SendWebhookOptions): Promise<WebhookDelivery[]>;
339
+ private deliver;
340
+ private buildData;
341
+ emitForUser(type: "user.created" | "user.authenticated", user: KindeUser): void;
342
+ private userData;
343
+ private userPayload;
344
+ private organizationData;
345
+ private namedData;
346
+ private requireUser;
347
+ }
348
+
266
349
  interface StartKindeTestkitOptions {
267
350
  port?: number;
268
351
  host?: string;
@@ -271,6 +354,7 @@ interface StartKindeTestkitOptions {
271
354
  clientId?: string;
272
355
  seed?: TestkitSeed;
273
356
  allowPublic?: boolean;
357
+ webhooks?: WebhookOptions;
274
358
  }
275
359
  interface RunningKindeTestkit {
276
360
  url: string;
@@ -280,6 +364,7 @@ interface RunningKindeTestkit {
280
364
  testkit: KindeTestkit;
281
365
  seed: ResolvedSeed;
282
366
  failures: FailureInjector;
367
+ webhooks: WebhookDispatcher;
283
368
  reset(): void;
284
369
  close(): Promise<void>;
285
370
  }
@@ -321,4 +406,4 @@ declare function runDoctor(options: {
321
406
  }): Promise<DoctorReport>;
322
407
  declare function parseEnvFile(text: string): Record<string, string>;
323
408
 
324
- export { type ActiveFailure, type AuthenticatedScenario, type Check, type CheckStatus, type CreateKindeOrganizationOptions, type CreateKindeUserOptions, type CreateMembershipOptions, DEFAULT_AUTH_METHODS, DEFAULT_CLIENT_ID, DEFAULT_ISSUER, DEFAULT_M2M_CLIENT_ID, DEFAULT_SCOPES, type DoctorReport, type Duration, FailureInjector, type FailureRule, INVALID_TOKEN_KINDS, type IdTokenOptions, type InvalidTokenKind, type KindeApplication, type KindeMembership, type KindeOrganization, type KindePrincipal, type KindeRole, KindeTestkit, type KindeTestkitOptions, type KindeTokenOptions, type KindeUser, type M2MTokenOptions, type ResolvedSeed, type RunningKindeTestkit, type Scenario, ScenarioBuilder, type ScenarioTokenOverrides, type StartKindeTestkitOptions, TestkitError, type TestkitErrorCode, type TestkitSeed, type TokenInspection, type UnauthenticatedScenario, createKindeOrganization, createKindeToken, createKindeUser, createMembership, getDefaultTestkit, inspectToken, isAuthenticated, parseEnvFile, principalFromClaims, resetFactories, resolveSeed, runDoctor, scenario, seedScenario, startKindeTestkit, toKindeRole };
409
+ export { type ActiveFailure, type AuthenticatedScenario, BILLING_EVENT_TYPES, type Check, type CheckStatus, type CreateKindeOrganizationOptions, type CreateKindeUserOptions, type CreateMembershipOptions, DEFAULT_AUTH_METHODS, DEFAULT_CLIENT_ID, DEFAULT_ISSUER, DEFAULT_M2M_CLIENT_ID, DEFAULT_SCOPES, type DoctorReport, type Duration, FailureInjector, type FailureRule, INVALID_TOKEN_KINDS, type IdTokenOptions, type InvalidTokenKind, type KindeApplication, type KindeMembership, type KindeOrganization, type KindePrincipal, type KindeRole, KindeTestkit, type KindeTestkitOptions, type KindeTokenOptions, type KindeUser, type M2MTokenOptions, type ResolvedSeed, type RunningKindeTestkit, type Scenario, ScenarioBuilder, type ScenarioTokenOverrides, type SendWebhookOptions, type StartKindeTestkitOptions, TestkitError, type TestkitErrorCode, type TestkitSeed, type TokenInspection, type UnauthenticatedScenario, WEBHOOK_EVENT_TYPES, type WebhookAttempt, type WebhookDelivery, WebhookDispatcher, type WebhookEndpoint, type WebhookEndpointInput, type WebhookInvalidKind, type WebhookOptions, type WebhookSource, createKindeOrganization, createKindeToken, createKindeUser, createMembership, getDefaultTestkit, inspectToken, isAuthenticated, parseEnvFile, principalFromClaims, resetFactories, resolveSeed, runDoctor, scenario, seedScenario, startKindeTestkit, toKindeRole };
package/dist/index.js CHANGED
@@ -324,6 +324,9 @@ var KindeTestkit = class _KindeTestkit {
324
324
  if (scenario2.kind === "unauthenticated") return null;
325
325
  return scenarioPrincipal(scenario2, this.issuer);
326
326
  }
327
+ async signPayload(payload, invalid2) {
328
+ return this.sign(payload, invalid2);
329
+ }
327
330
  async sign(payload, invalid2) {
328
331
  if (invalid2 === "unsigned") {
329
332
  const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
@@ -448,6 +451,19 @@ function resolveSeed(input) {
448
451
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
449
452
  const rawMemberships = listOf(input.memberships, "memberships", problems);
450
453
  const rawApplications = listOf(input.applications, "applications", problems);
454
+ const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
455
+ const webhooks = [];
456
+ rawWebhooks.forEach((raw, index) => {
457
+ if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
458
+ problems.push(`webhooks[${index}] needs an http or https "url".`);
459
+ return;
460
+ }
461
+ if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
462
+ problems.push(`webhooks[${index}].events must be a list of event type names.`);
463
+ return;
464
+ }
465
+ webhooks.push({ url: raw.url, events: raw.events });
466
+ });
451
467
  const users = [];
452
468
  rawUsers.forEach((raw, index) => {
453
469
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -539,7 +555,7 @@ function resolveSeed(input) {
539
555
  if (problems.length > 0) {
540
556
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
541
557
  }
542
- return { users, organizations, memberships, applications };
558
+ return { users, organizations, memberships, applications, webhooks };
543
559
  }
544
560
  function findUser(users, ref) {
545
561
  const needle = ref.toLowerCase();
@@ -676,12 +692,14 @@ var OAuthError = class extends Error {
676
692
  error;
677
693
  };
678
694
  var AuthorizationServer = class {
679
- constructor(testkit, seed) {
695
+ constructor(testkit, seed, emit = () => void 0) {
680
696
  this.testkit = testkit;
681
697
  this.seed = seed;
698
+ this.emit = emit;
682
699
  }
683
700
  testkit;
684
701
  seed;
702
+ emit;
685
703
  codes = /* @__PURE__ */ new Map();
686
704
  refreshTokens = /* @__PURE__ */ new Map();
687
705
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -799,6 +817,7 @@ var AuthorizationServer = class {
799
817
  codeChallengeMethod: request.codeChallengeMethod,
800
818
  expiresAt: Date.now() + CODE_LIFETIME_MS
801
819
  });
820
+ this.emit("user.authenticated", user);
802
821
  const target = new URL(request.redirectUri);
803
822
  target.searchParams.set("code", code);
804
823
  if (request.state !== null) target.searchParams.set("state", request.state);
@@ -964,8 +983,11 @@ var AuthorizationServer = class {
964
983
  if (seeded) return seeded;
965
984
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
966
985
  const user = createKindeUser({ email: ref.toLowerCase() });
967
- this.signedUpUsers.set(user.id, user);
968
- return user;
986
+ if (!this.signedUpUsers.has(user.id)) {
987
+ this.signedUpUsers.set(user.id, user);
988
+ this.emit("user.created", user);
989
+ }
990
+ return this.signedUpUsers.get(user.id);
969
991
  }
970
992
  organization(code) {
971
993
  return this.seed.organizations.find((org) => org.code === code) ?? null;
@@ -1154,6 +1176,271 @@ function validate(rule) {
1154
1176
  return problems;
1155
1177
  }
1156
1178
 
1179
+ // src/webhooks.ts
1180
+ import { randomBytes as randomBytes2 } from "crypto";
1181
+ var WEBHOOK_EVENT_TYPES = [
1182
+ "user.created",
1183
+ "user.updated",
1184
+ "user.deleted",
1185
+ "user.authenticated",
1186
+ "user.authentication_failed",
1187
+ "organization.created",
1188
+ "organization.updated",
1189
+ "organization.deleted",
1190
+ "role.created",
1191
+ "role.updated",
1192
+ "role.deleted",
1193
+ "permission.created",
1194
+ "permission.updated",
1195
+ "permission.deleted",
1196
+ "subscriber.created",
1197
+ "access_request.created"
1198
+ ];
1199
+ var BILLING_EVENT_TYPES = [
1200
+ "customer.agreement_cancelled",
1201
+ "customer.agreement_created",
1202
+ "customer.invoice_overdue",
1203
+ "customer.meter_usage_updated",
1204
+ "customer.payment_failed",
1205
+ "customer.payment_succeeded",
1206
+ "customer.plan_assigned",
1207
+ "customer.plan_changed"
1208
+ ];
1209
+ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
1210
+ var DEFAULT_TIMEOUT_MS = 5e3;
1211
+ var MAX_DUPLICATES = 10;
1212
+ var WebhookDispatcher = class {
1213
+ constructor(testkit, seed, endpoints = [], options = {}) {
1214
+ this.testkit = testkit;
1215
+ this.seed = seed;
1216
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
1217
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1218
+ for (const endpoint of endpoints) this.addEndpoint(endpoint);
1219
+ this.seededEndpoints = [...this.endpoints];
1220
+ }
1221
+ testkit;
1222
+ seed;
1223
+ endpoints = [];
1224
+ seededEndpoints = [];
1225
+ log = [];
1226
+ nextEndpoint = 1;
1227
+ retryDelaysMs;
1228
+ timeoutMs;
1229
+ addEndpoint(input) {
1230
+ if (!isHttpUrl2(input.url)) {
1231
+ throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
1232
+ }
1233
+ if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
1234
+ throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
1235
+ }
1236
+ const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
1237
+ this.endpoints.push(endpoint);
1238
+ return { ...endpoint };
1239
+ }
1240
+ removeEndpoint(id) {
1241
+ const before = this.endpoints.length;
1242
+ this.endpoints = this.endpoints.filter((e) => e.id !== id);
1243
+ return this.endpoints.length < before;
1244
+ }
1245
+ listEndpoints() {
1246
+ return this.endpoints.map((e) => ({ ...e }));
1247
+ }
1248
+ deliveries() {
1249
+ return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
1250
+ }
1251
+ reset() {
1252
+ this.log = [];
1253
+ this.endpoints = [...this.seededEndpoints];
1254
+ }
1255
+ buildEvent(options) {
1256
+ if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
1257
+ throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
1258
+ }
1259
+ const now = /* @__PURE__ */ new Date();
1260
+ const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
1261
+ const event = {
1262
+ data: options.data ?? this.buildData(options),
1263
+ event_id: `event_${randomBytes2(16).toString("hex")}`,
1264
+ event_timestamp: timestamp,
1265
+ source: options.source ?? "admin",
1266
+ timestamp,
1267
+ type: options.type
1268
+ };
1269
+ if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
1270
+ event.ip_address = options.ipAddress ?? "127.0.0.1";
1271
+ }
1272
+ return event;
1273
+ }
1274
+ async send(options) {
1275
+ const event = this.buildEvent(options);
1276
+ const copies = options.duplicate ?? 1;
1277
+ if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
1278
+ throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
1279
+ }
1280
+ const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
1281
+ if (options.to && !isHttpUrl2(options.to)) {
1282
+ throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
1283
+ }
1284
+ if (targets.length === 0) {
1285
+ throw new TestkitError(
1286
+ "INVALID_REQUEST",
1287
+ `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
1288
+ );
1289
+ }
1290
+ if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
1291
+ const signed = await this.testkit.signPayload(
1292
+ event,
1293
+ options.invalid === "stale" ? void 0 : options.invalid
1294
+ );
1295
+ const jobs = targets.flatMap((target) => {
1296
+ const webhookId = `wh_${randomBytes2(12).toString("hex")}`;
1297
+ return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
1298
+ });
1299
+ return Promise.all(jobs);
1300
+ }
1301
+ async deliver(url, webhookId, body, event, copy) {
1302
+ const delivery = {
1303
+ webhookId,
1304
+ eventId: String(event.event_id),
1305
+ type: String(event.type),
1306
+ url,
1307
+ copy,
1308
+ delivered: false,
1309
+ attempts: [],
1310
+ payload: event
1311
+ };
1312
+ this.log.push(delivery);
1313
+ for (const [index, delay] of this.retryDelaysMs.entries()) {
1314
+ if (delay > 0) await sleep(delay);
1315
+ const started = Date.now();
1316
+ try {
1317
+ const response = await fetch(url, {
1318
+ method: "POST",
1319
+ headers: { "content-type": "application/jwt", "webhook-id": webhookId },
1320
+ body,
1321
+ signal: AbortSignal.timeout(this.timeoutMs)
1322
+ });
1323
+ await response.arrayBuffer().catch(() => void 0);
1324
+ delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
1325
+ if (response.status === 200) {
1326
+ delivery.delivered = true;
1327
+ break;
1328
+ }
1329
+ } catch (error) {
1330
+ const name = error.name;
1331
+ delivery.attempts.push({
1332
+ attempt: index + 1,
1333
+ status: null,
1334
+ error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
1335
+ durationMs: Date.now() - started
1336
+ });
1337
+ }
1338
+ }
1339
+ return { ...delivery, attempts: [...delivery.attempts] };
1340
+ }
1341
+ buildData(options) {
1342
+ const [subject] = options.type.split(".");
1343
+ switch (subject) {
1344
+ case "user":
1345
+ return { user: this.userData(options) };
1346
+ case "organization":
1347
+ return { organization: this.organizationData(options) };
1348
+ case "role":
1349
+ return { role: this.namedData(options, "role") };
1350
+ case "permission":
1351
+ return { permission: this.namedData(options, "permission") };
1352
+ case "subscriber": {
1353
+ const user = this.requireUser(options);
1354
+ return {
1355
+ subscriber: {
1356
+ email: user.email,
1357
+ first_name: user.givenName,
1358
+ id: stableId("sub", user.id),
1359
+ last_name: user.familyName,
1360
+ user_id: user.id
1361
+ }
1362
+ };
1363
+ }
1364
+ case "access_request": {
1365
+ const user = this.requireUser(options);
1366
+ return {
1367
+ access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
1368
+ };
1369
+ }
1370
+ default:
1371
+ throw new TestkitError(
1372
+ "INVALID_REQUEST",
1373
+ `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
1374
+ );
1375
+ }
1376
+ }
1377
+ emitForUser(type, user) {
1378
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
1379
+ const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
1380
+ void this.send({ type, data, source: "user" }).catch(() => void 0);
1381
+ }
1382
+ userData(options) {
1383
+ const user = this.requireUser(options);
1384
+ if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
1385
+ return this.userPayload(user);
1386
+ }
1387
+ userPayload(user) {
1388
+ return {
1389
+ email: user.email,
1390
+ first_name: user.givenName,
1391
+ id: user.id,
1392
+ is_password_reset_requested: false,
1393
+ is_suspended: false,
1394
+ last_name: user.familyName,
1395
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
1396
+ code: m.organizationCode,
1397
+ permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
1398
+ roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
1399
+ })),
1400
+ phone: null,
1401
+ username: typeof user.claims.username === "string" ? user.claims.username : null
1402
+ };
1403
+ }
1404
+ organizationData(options) {
1405
+ if (!options.organization) {
1406
+ throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
1407
+ }
1408
+ const org = this.seed.organizations.find((o) => o.code === options.organization);
1409
+ if (options.type === "organization.deleted") return { code: options.organization };
1410
+ const name = org?.name ?? titleCase(options.organization);
1411
+ const data = { code: options.organization, external_id: null, handle: slug(name), name };
1412
+ if (options.type === "organization.updated") data.is_allow_registrations = false;
1413
+ return data;
1414
+ }
1415
+ namedData(options, kind) {
1416
+ const key = kind === "role" ? options.role : options.permission;
1417
+ if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
1418
+ const id = stableId(kind === "role" ? "role" : "perm", key);
1419
+ if (options.type.endsWith(".deleted")) return { id };
1420
+ const data = { description: "", id, key, name: titleCase(key) };
1421
+ if (kind === "role") data.is_default_role = false;
1422
+ return data;
1423
+ }
1424
+ requireUser(options) {
1425
+ if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
1426
+ const user = findUser(this.seed.users, options.user);
1427
+ if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
1428
+ return user;
1429
+ }
1430
+ };
1431
+ function isHttpUrl2(value) {
1432
+ if (typeof value !== "string") return false;
1433
+ try {
1434
+ const { protocol } = new URL(value);
1435
+ return protocol === "http:" || protocol === "https:";
1436
+ } catch {
1437
+ return false;
1438
+ }
1439
+ }
1440
+ function sleep(ms) {
1441
+ return new Promise((resolve) => setTimeout(resolve, ms));
1442
+ }
1443
+
1157
1444
  // src/server.ts
1158
1445
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
1159
1446
  var MAX_BODY_BYTES = 64 * 1024;
@@ -1185,12 +1472,14 @@ async function startKindeTestkit(options = {}) {
1185
1472
  audience: options.audience ?? options.seed?.audience,
1186
1473
  clientId: options.clientId ?? options.seed?.clientId
1187
1474
  });
1188
- const auth = new AuthorizationServer(testkit, seed);
1475
+ const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
1476
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
1189
1477
  const reset = () => {
1190
1478
  auth.reset();
1191
1479
  failures.clear();
1480
+ webhooks.reset();
1192
1481
  };
1193
- ready({ testkit, auth, seed, failures, reset });
1482
+ ready({ testkit, auth, seed, failures, webhooks, reset });
1194
1483
  return {
1195
1484
  url,
1196
1485
  issuer: testkit.issuer,
@@ -1199,6 +1488,7 @@ async function startKindeTestkit(options = {}) {
1199
1488
  testkit,
1200
1489
  seed,
1201
1490
  failures,
1491
+ webhooks,
1202
1492
  reset,
1203
1493
  close: () => new Promise((resolve, reject) => {
1204
1494
  server.closeAllConnections();
@@ -1207,7 +1497,7 @@ async function startKindeTestkit(options = {}) {
1207
1497
  };
1208
1498
  }
1209
1499
  async function handle(req, res, context) {
1210
- const { testkit, auth, seed, failures } = context;
1500
+ const { testkit, auth, seed, failures, webhooks } = context;
1211
1501
  const url = new URL(req.url ?? "/", "http://localhost");
1212
1502
  const { pathname } = url;
1213
1503
  const method = req.method ?? "GET";
@@ -1252,6 +1542,21 @@ async function handle(req, res, context) {
1252
1542
  const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1253
1543
  return sendJson2(res, removed ? 200 : 404, { ok: removed });
1254
1544
  }
1545
+ if (method === "POST" && pathname === "/testkit/webhooks") {
1546
+ return sendJson2(res, 200, await webhooks.send(await readJson(req)));
1547
+ }
1548
+ if (method === "GET" && pathname === "/testkit/webhooks/types") {
1549
+ return sendJson2(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
1550
+ }
1551
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson2(res, 200, webhooks.deliveries());
1552
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson2(res, 200, webhooks.listEndpoints());
1553
+ if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
1554
+ return sendJson2(res, 201, webhooks.addEndpoint(await readJson(req)));
1555
+ }
1556
+ if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
1557
+ const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
1558
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1559
+ }
1255
1560
  if (method === "POST" && pathname === "/testkit/reset") {
1256
1561
  context.reset();
1257
1562
  return sendJson2(res, 200, { ok: true });
@@ -1575,6 +1880,7 @@ function parseEnvFile(text) {
1575
1880
  return values;
1576
1881
  }
1577
1882
  export {
1883
+ BILLING_EVENT_TYPES,
1578
1884
  DEFAULT_AUTH_METHODS,
1579
1885
  DEFAULT_CLIENT_ID,
1580
1886
  DEFAULT_ISSUER,
@@ -1585,6 +1891,8 @@ export {
1585
1891
  KindeTestkit,
1586
1892
  ScenarioBuilder,
1587
1893
  TestkitError,
1894
+ WEBHOOK_EVENT_TYPES,
1895
+ WebhookDispatcher,
1588
1896
  createKindeOrganization,
1589
1897
  createKindeToken,
1590
1898
  createKindeUser,