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.cjs CHANGED
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
+ BILLING_EVENT_TYPES: () => BILLING_EVENT_TYPES,
23
24
  DEFAULT_AUTH_METHODS: () => DEFAULT_AUTH_METHODS,
24
25
  DEFAULT_CLIENT_ID: () => DEFAULT_CLIENT_ID,
25
26
  DEFAULT_ISSUER: () => DEFAULT_ISSUER,
@@ -30,6 +31,8 @@ __export(src_exports, {
30
31
  KindeTestkit: () => KindeTestkit,
31
32
  ScenarioBuilder: () => ScenarioBuilder,
32
33
  TestkitError: () => TestkitError,
34
+ WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
35
+ WebhookDispatcher: () => WebhookDispatcher,
33
36
  createKindeOrganization: () => createKindeOrganization,
34
37
  createKindeToken: () => createKindeToken,
35
38
  createKindeUser: () => createKindeUser,
@@ -368,6 +371,9 @@ var KindeTestkit = class _KindeTestkit {
368
371
  if (scenario2.kind === "unauthenticated") return null;
369
372
  return scenarioPrincipal(scenario2, this.issuer);
370
373
  }
374
+ async signPayload(payload, invalid2) {
375
+ return this.sign(payload, invalid2);
376
+ }
371
377
  async sign(payload, invalid2) {
372
378
  if (invalid2 === "unsigned") {
373
379
  const header = import_jose.base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
@@ -492,6 +498,19 @@ function resolveSeed(input) {
492
498
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
493
499
  const rawMemberships = listOf(input.memberships, "memberships", problems);
494
500
  const rawApplications = listOf(input.applications, "applications", problems);
501
+ const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
502
+ const webhooks = [];
503
+ rawWebhooks.forEach((raw, index) => {
504
+ if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
505
+ problems.push(`webhooks[${index}] needs an http or https "url".`);
506
+ return;
507
+ }
508
+ if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
509
+ problems.push(`webhooks[${index}].events must be a list of event type names.`);
510
+ return;
511
+ }
512
+ webhooks.push({ url: raw.url, events: raw.events });
513
+ });
495
514
  const users = [];
496
515
  rawUsers.forEach((raw, index) => {
497
516
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -583,7 +602,7 @@ function resolveSeed(input) {
583
602
  if (problems.length > 0) {
584
603
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
585
604
  }
586
- return { users, organizations, memberships, applications };
605
+ return { users, organizations, memberships, applications, webhooks };
587
606
  }
588
607
  function findUser(users, ref) {
589
608
  const needle = ref.toLowerCase();
@@ -720,12 +739,14 @@ var OAuthError = class extends Error {
720
739
  error;
721
740
  };
722
741
  var AuthorizationServer = class {
723
- constructor(testkit, seed) {
742
+ constructor(testkit, seed, emit = () => void 0) {
724
743
  this.testkit = testkit;
725
744
  this.seed = seed;
745
+ this.emit = emit;
726
746
  }
727
747
  testkit;
728
748
  seed;
749
+ emit;
729
750
  codes = /* @__PURE__ */ new Map();
730
751
  refreshTokens = /* @__PURE__ */ new Map();
731
752
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -843,6 +864,7 @@ var AuthorizationServer = class {
843
864
  codeChallengeMethod: request.codeChallengeMethod,
844
865
  expiresAt: Date.now() + CODE_LIFETIME_MS
845
866
  });
867
+ this.emit("user.authenticated", user);
846
868
  const target = new URL(request.redirectUri);
847
869
  target.searchParams.set("code", code);
848
870
  if (request.state !== null) target.searchParams.set("state", request.state);
@@ -1008,8 +1030,11 @@ var AuthorizationServer = class {
1008
1030
  if (seeded) return seeded;
1009
1031
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
1010
1032
  const user = createKindeUser({ email: ref.toLowerCase() });
1011
- this.signedUpUsers.set(user.id, user);
1012
- return user;
1033
+ if (!this.signedUpUsers.has(user.id)) {
1034
+ this.signedUpUsers.set(user.id, user);
1035
+ this.emit("user.created", user);
1036
+ }
1037
+ return this.signedUpUsers.get(user.id);
1013
1038
  }
1014
1039
  organization(code) {
1015
1040
  return this.seed.organizations.find((org) => org.code === code) ?? null;
@@ -1198,6 +1223,271 @@ function validate(rule) {
1198
1223
  return problems;
1199
1224
  }
1200
1225
 
1226
+ // src/webhooks.ts
1227
+ var import_node_crypto4 = require("crypto");
1228
+ var WEBHOOK_EVENT_TYPES = [
1229
+ "user.created",
1230
+ "user.updated",
1231
+ "user.deleted",
1232
+ "user.authenticated",
1233
+ "user.authentication_failed",
1234
+ "organization.created",
1235
+ "organization.updated",
1236
+ "organization.deleted",
1237
+ "role.created",
1238
+ "role.updated",
1239
+ "role.deleted",
1240
+ "permission.created",
1241
+ "permission.updated",
1242
+ "permission.deleted",
1243
+ "subscriber.created",
1244
+ "access_request.created"
1245
+ ];
1246
+ var BILLING_EVENT_TYPES = [
1247
+ "customer.agreement_cancelled",
1248
+ "customer.agreement_created",
1249
+ "customer.invoice_overdue",
1250
+ "customer.meter_usage_updated",
1251
+ "customer.payment_failed",
1252
+ "customer.payment_succeeded",
1253
+ "customer.plan_assigned",
1254
+ "customer.plan_changed"
1255
+ ];
1256
+ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
1257
+ var DEFAULT_TIMEOUT_MS = 5e3;
1258
+ var MAX_DUPLICATES = 10;
1259
+ var WebhookDispatcher = class {
1260
+ constructor(testkit, seed, endpoints = [], options = {}) {
1261
+ this.testkit = testkit;
1262
+ this.seed = seed;
1263
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
1264
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1265
+ for (const endpoint of endpoints) this.addEndpoint(endpoint);
1266
+ this.seededEndpoints = [...this.endpoints];
1267
+ }
1268
+ testkit;
1269
+ seed;
1270
+ endpoints = [];
1271
+ seededEndpoints = [];
1272
+ log = [];
1273
+ nextEndpoint = 1;
1274
+ retryDelaysMs;
1275
+ timeoutMs;
1276
+ addEndpoint(input) {
1277
+ if (!isHttpUrl2(input.url)) {
1278
+ throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
1279
+ }
1280
+ if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
1281
+ throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
1282
+ }
1283
+ const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
1284
+ this.endpoints.push(endpoint);
1285
+ return { ...endpoint };
1286
+ }
1287
+ removeEndpoint(id) {
1288
+ const before = this.endpoints.length;
1289
+ this.endpoints = this.endpoints.filter((e) => e.id !== id);
1290
+ return this.endpoints.length < before;
1291
+ }
1292
+ listEndpoints() {
1293
+ return this.endpoints.map((e) => ({ ...e }));
1294
+ }
1295
+ deliveries() {
1296
+ return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
1297
+ }
1298
+ reset() {
1299
+ this.log = [];
1300
+ this.endpoints = [...this.seededEndpoints];
1301
+ }
1302
+ buildEvent(options) {
1303
+ if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
1304
+ throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
1305
+ }
1306
+ const now = /* @__PURE__ */ new Date();
1307
+ const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
1308
+ const event = {
1309
+ data: options.data ?? this.buildData(options),
1310
+ event_id: `event_${(0, import_node_crypto4.randomBytes)(16).toString("hex")}`,
1311
+ event_timestamp: timestamp,
1312
+ source: options.source ?? "admin",
1313
+ timestamp,
1314
+ type: options.type
1315
+ };
1316
+ if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
1317
+ event.ip_address = options.ipAddress ?? "127.0.0.1";
1318
+ }
1319
+ return event;
1320
+ }
1321
+ async send(options) {
1322
+ const event = this.buildEvent(options);
1323
+ const copies = options.duplicate ?? 1;
1324
+ if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
1325
+ throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
1326
+ }
1327
+ const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
1328
+ if (options.to && !isHttpUrl2(options.to)) {
1329
+ throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
1330
+ }
1331
+ if (targets.length === 0) {
1332
+ throw new TestkitError(
1333
+ "INVALID_REQUEST",
1334
+ `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
1335
+ );
1336
+ }
1337
+ if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
1338
+ const signed = await this.testkit.signPayload(
1339
+ event,
1340
+ options.invalid === "stale" ? void 0 : options.invalid
1341
+ );
1342
+ const jobs = targets.flatMap((target) => {
1343
+ const webhookId = `wh_${(0, import_node_crypto4.randomBytes)(12).toString("hex")}`;
1344
+ return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
1345
+ });
1346
+ return Promise.all(jobs);
1347
+ }
1348
+ async deliver(url, webhookId, body, event, copy) {
1349
+ const delivery = {
1350
+ webhookId,
1351
+ eventId: String(event.event_id),
1352
+ type: String(event.type),
1353
+ url,
1354
+ copy,
1355
+ delivered: false,
1356
+ attempts: [],
1357
+ payload: event
1358
+ };
1359
+ this.log.push(delivery);
1360
+ for (const [index, delay] of this.retryDelaysMs.entries()) {
1361
+ if (delay > 0) await sleep(delay);
1362
+ const started = Date.now();
1363
+ try {
1364
+ const response = await fetch(url, {
1365
+ method: "POST",
1366
+ headers: { "content-type": "application/jwt", "webhook-id": webhookId },
1367
+ body,
1368
+ signal: AbortSignal.timeout(this.timeoutMs)
1369
+ });
1370
+ await response.arrayBuffer().catch(() => void 0);
1371
+ delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
1372
+ if (response.status === 200) {
1373
+ delivery.delivered = true;
1374
+ break;
1375
+ }
1376
+ } catch (error) {
1377
+ const name = error.name;
1378
+ delivery.attempts.push({
1379
+ attempt: index + 1,
1380
+ status: null,
1381
+ error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
1382
+ durationMs: Date.now() - started
1383
+ });
1384
+ }
1385
+ }
1386
+ return { ...delivery, attempts: [...delivery.attempts] };
1387
+ }
1388
+ buildData(options) {
1389
+ const [subject] = options.type.split(".");
1390
+ switch (subject) {
1391
+ case "user":
1392
+ return { user: this.userData(options) };
1393
+ case "organization":
1394
+ return { organization: this.organizationData(options) };
1395
+ case "role":
1396
+ return { role: this.namedData(options, "role") };
1397
+ case "permission":
1398
+ return { permission: this.namedData(options, "permission") };
1399
+ case "subscriber": {
1400
+ const user = this.requireUser(options);
1401
+ return {
1402
+ subscriber: {
1403
+ email: user.email,
1404
+ first_name: user.givenName,
1405
+ id: stableId("sub", user.id),
1406
+ last_name: user.familyName,
1407
+ user_id: user.id
1408
+ }
1409
+ };
1410
+ }
1411
+ case "access_request": {
1412
+ const user = this.requireUser(options);
1413
+ return {
1414
+ access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
1415
+ };
1416
+ }
1417
+ default:
1418
+ throw new TestkitError(
1419
+ "INVALID_REQUEST",
1420
+ `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
1421
+ );
1422
+ }
1423
+ }
1424
+ emitForUser(type, user) {
1425
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
1426
+ const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
1427
+ void this.send({ type, data, source: "user" }).catch(() => void 0);
1428
+ }
1429
+ userData(options) {
1430
+ const user = this.requireUser(options);
1431
+ if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
1432
+ return this.userPayload(user);
1433
+ }
1434
+ userPayload(user) {
1435
+ return {
1436
+ email: user.email,
1437
+ first_name: user.givenName,
1438
+ id: user.id,
1439
+ is_password_reset_requested: false,
1440
+ is_suspended: false,
1441
+ last_name: user.familyName,
1442
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
1443
+ code: m.organizationCode,
1444
+ permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
1445
+ roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
1446
+ })),
1447
+ phone: null,
1448
+ username: typeof user.claims.username === "string" ? user.claims.username : null
1449
+ };
1450
+ }
1451
+ organizationData(options) {
1452
+ if (!options.organization) {
1453
+ throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
1454
+ }
1455
+ const org = this.seed.organizations.find((o) => o.code === options.organization);
1456
+ if (options.type === "organization.deleted") return { code: options.organization };
1457
+ const name = org?.name ?? titleCase(options.organization);
1458
+ const data = { code: options.organization, external_id: null, handle: slug(name), name };
1459
+ if (options.type === "organization.updated") data.is_allow_registrations = false;
1460
+ return data;
1461
+ }
1462
+ namedData(options, kind) {
1463
+ const key = kind === "role" ? options.role : options.permission;
1464
+ if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
1465
+ const id = stableId(kind === "role" ? "role" : "perm", key);
1466
+ if (options.type.endsWith(".deleted")) return { id };
1467
+ const data = { description: "", id, key, name: titleCase(key) };
1468
+ if (kind === "role") data.is_default_role = false;
1469
+ return data;
1470
+ }
1471
+ requireUser(options) {
1472
+ if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
1473
+ const user = findUser(this.seed.users, options.user);
1474
+ if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
1475
+ return user;
1476
+ }
1477
+ };
1478
+ function isHttpUrl2(value) {
1479
+ if (typeof value !== "string") return false;
1480
+ try {
1481
+ const { protocol } = new URL(value);
1482
+ return protocol === "http:" || protocol === "https:";
1483
+ } catch {
1484
+ return false;
1485
+ }
1486
+ }
1487
+ function sleep(ms) {
1488
+ return new Promise((resolve) => setTimeout(resolve, ms));
1489
+ }
1490
+
1201
1491
  // src/server.ts
1202
1492
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
1203
1493
  var MAX_BODY_BYTES = 64 * 1024;
@@ -1229,12 +1519,14 @@ async function startKindeTestkit(options = {}) {
1229
1519
  audience: options.audience ?? options.seed?.audience,
1230
1520
  clientId: options.clientId ?? options.seed?.clientId
1231
1521
  });
1232
- const auth = new AuthorizationServer(testkit, seed);
1522
+ const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
1523
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
1233
1524
  const reset = () => {
1234
1525
  auth.reset();
1235
1526
  failures.clear();
1527
+ webhooks.reset();
1236
1528
  };
1237
- ready({ testkit, auth, seed, failures, reset });
1529
+ ready({ testkit, auth, seed, failures, webhooks, reset });
1238
1530
  return {
1239
1531
  url,
1240
1532
  issuer: testkit.issuer,
@@ -1243,6 +1535,7 @@ async function startKindeTestkit(options = {}) {
1243
1535
  testkit,
1244
1536
  seed,
1245
1537
  failures,
1538
+ webhooks,
1246
1539
  reset,
1247
1540
  close: () => new Promise((resolve, reject) => {
1248
1541
  server.closeAllConnections();
@@ -1251,7 +1544,7 @@ async function startKindeTestkit(options = {}) {
1251
1544
  };
1252
1545
  }
1253
1546
  async function handle(req, res, context) {
1254
- const { testkit, auth, seed, failures } = context;
1547
+ const { testkit, auth, seed, failures, webhooks } = context;
1255
1548
  const url = new URL(req.url ?? "/", "http://localhost");
1256
1549
  const { pathname } = url;
1257
1550
  const method = req.method ?? "GET";
@@ -1296,6 +1589,21 @@ async function handle(req, res, context) {
1296
1589
  const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1297
1590
  return sendJson2(res, removed ? 200 : 404, { ok: removed });
1298
1591
  }
1592
+ if (method === "POST" && pathname === "/testkit/webhooks") {
1593
+ return sendJson2(res, 200, await webhooks.send(await readJson(req)));
1594
+ }
1595
+ if (method === "GET" && pathname === "/testkit/webhooks/types") {
1596
+ return sendJson2(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
1597
+ }
1598
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson2(res, 200, webhooks.deliveries());
1599
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson2(res, 200, webhooks.listEndpoints());
1600
+ if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
1601
+ return sendJson2(res, 201, webhooks.addEndpoint(await readJson(req)));
1602
+ }
1603
+ if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
1604
+ const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
1605
+ return sendJson2(res, removed ? 200 : 404, { ok: removed });
1606
+ }
1299
1607
  if (method === "POST" && pathname === "/testkit/reset") {
1300
1608
  context.reset();
1301
1609
  return sendJson2(res, 200, { ok: true });
@@ -1620,6 +1928,7 @@ function parseEnvFile(text) {
1620
1928
  }
1621
1929
  // Annotate the CommonJS export names for ESM import in node:
1622
1930
  0 && (module.exports = {
1931
+ BILLING_EVENT_TYPES,
1623
1932
  DEFAULT_AUTH_METHODS,
1624
1933
  DEFAULT_CLIENT_ID,
1625
1934
  DEFAULT_ISSUER,
@@ -1630,6 +1939,8 @@ function parseEnvFile(text) {
1630
1939
  KindeTestkit,
1631
1940
  ScenarioBuilder,
1632
1941
  TestkitError,
1942
+ WEBHOOK_EVENT_TYPES,
1943
+ WebhookDispatcher,
1633
1944
  createKindeOrganization,
1634
1945
  createKindeToken,
1635
1946
  createKindeUser,