kinde-testkit 0.3.0 → 0.5.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
@@ -264,6 +264,9 @@ var KindeTestkit = class _KindeTestkit {
264
264
  if (scenario.kind === "unauthenticated") return null;
265
265
  return scenarioPrincipal(scenario, this.issuer);
266
266
  }
267
+ async signPayload(payload, invalid2) {
268
+ return this.sign(payload, invalid2);
269
+ }
267
270
  async sign(payload, invalid2) {
268
271
  if (invalid2 === "unsigned") {
269
272
  const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
@@ -358,8 +361,230 @@ function getDefaultTestkit() {
358
361
 
359
362
  // src/server.ts
360
363
  import { createServer } from "http";
364
+ import { createServer as createHttpsServer } from "https";
365
+
366
+ // src/certificate.ts
367
+ import { createHash as createHash2, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
368
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
369
+ import { join, resolve } from "path";
370
+ var CERT_FILE = "localhost-cert.pem";
371
+ var KEY_FILE = "localhost-key.pem";
372
+ var VALID_DAYS = 825;
373
+ function ensureLocalCertificate(directory = ".kinde-testkit") {
374
+ const dir = resolve(directory);
375
+ const certPath = join(dir, CERT_FILE);
376
+ const keyPath = join(dir, KEY_FILE);
377
+ if (existsSync(certPath) && existsSync(keyPath)) {
378
+ const cert2 = readFileSync(certPath, "utf8");
379
+ const key2 = readFileSync(keyPath, "utf8");
380
+ try {
381
+ if (new Date(new X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
382
+ return { cert: cert2, key: key2, certPath, keyPath, created: false };
383
+ }
384
+ } catch {
385
+ }
386
+ }
387
+ const { cert, key } = createLocalCertificate();
388
+ mkdirSync(dir, { recursive: true });
389
+ writeFileSync(certPath, cert);
390
+ writeFileSync(keyPath, key, { mode: 384 });
391
+ writeFileSync(join(dir, ".gitignore"), "*\n");
392
+ return { cert, key, certPath, keyPath, created: true };
393
+ }
394
+ function createLocalCertificate() {
395
+ const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
396
+ const spki = publicKey.export({ type: "spki", format: "der" });
397
+ const keyId = createHash2("sha1").update(subjectPublicKeyBits(spki)).digest();
398
+ const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
399
+ const now = Date.now();
400
+ const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
401
+ const serial = randomBytes(16);
402
+ serial[0] &= 127;
403
+ const extensions = seq(
404
+ seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
405
+ seq(oid("2.5.29.14"), octets(octets(keyId))),
406
+ seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
407
+ seq(
408
+ oid("2.5.29.17"),
409
+ octets(
410
+ seq(
411
+ tlv(130, Buffer.from("localhost")),
412
+ tlv(135, Buffer.from([127, 0, 0, 1])),
413
+ tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
414
+ )
415
+ )
416
+ )
417
+ );
418
+ const tbs = seq(
419
+ tlv(160, integer(Buffer.from([2]))),
420
+ integer(serial),
421
+ algorithm,
422
+ name,
423
+ seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
424
+ name,
425
+ spki,
426
+ tlv(163, extensions)
427
+ );
428
+ const signature = sign("sha256", tbs, privateKey);
429
+ const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
430
+ return {
431
+ cert: pem("CERTIFICATE", der),
432
+ key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
433
+ };
434
+ }
435
+ function subjectPublicKeyBits(spki) {
436
+ const outer = readTlv(spki, 0);
437
+ const algorithm = readTlv(spki, outer.start);
438
+ const bits = readTlv(spki, algorithm.end);
439
+ return spki.subarray(bits.start + 1, bits.end);
440
+ }
441
+ function readTlv(buf, offset) {
442
+ let len = buf[offset + 1];
443
+ let header = 2;
444
+ if (len & 128) {
445
+ const n = len & 127;
446
+ len = 0;
447
+ for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
448
+ header += n;
449
+ }
450
+ return { start: offset + header, end: offset + header + len };
451
+ }
452
+ function tlv(tag, content) {
453
+ return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
454
+ }
455
+ function length(n) {
456
+ if (n < 128) return Buffer.from([n]);
457
+ const bytes = [];
458
+ while (n > 0) {
459
+ bytes.unshift(n & 255);
460
+ n >>= 8;
461
+ }
462
+ return Buffer.from([128 | bytes.length, ...bytes]);
463
+ }
464
+ function seq(...items) {
465
+ return tlv(48, Buffer.concat(items));
466
+ }
467
+ function set(...items) {
468
+ return tlv(49, Buffer.concat(items));
469
+ }
470
+ function octets(content) {
471
+ return tlv(4, content);
472
+ }
473
+ function integer(bytes) {
474
+ return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
475
+ }
476
+ function oid(dotted) {
477
+ const parts = dotted.split(".").map(Number);
478
+ const bytes = [parts[0] * 40 + parts[1]];
479
+ for (const part of parts.slice(2)) {
480
+ const chunk = [part & 127];
481
+ let value = part >> 7;
482
+ while (value > 0) {
483
+ chunk.unshift(value & 127 | 128);
484
+ value >>= 7;
485
+ }
486
+ bytes.push(...chunk);
487
+ }
488
+ return tlv(6, Buffer.from(bytes));
489
+ }
490
+ function utcTime(date) {
491
+ const iso = date.toISOString();
492
+ const value = `${iso.slice(2, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`;
493
+ return tlv(23, Buffer.from(value));
494
+ }
495
+ function pem(label, der) {
496
+ const body = der.toString("base64").match(/.{1,64}/g).join("\n");
497
+ return `-----BEGIN ${label}-----
498
+ ${body}
499
+ -----END ${label}-----
500
+ `;
501
+ }
502
+
503
+ // src/login-page.ts
504
+ var STYLE = `
505
+ :root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--warn:#8a5a00;--warn-bg:#fff6e0}
506
+ @media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--warn:#f0c46a;--warn-bg:#2a2210}}
507
+ *{box-sizing:border-box}
508
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;padding:24px}
509
+ main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
510
+ .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
511
+ h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
512
+ p{margin:0;color:var(--muted)}
513
+ .note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
514
+ form{margin:0}
515
+ label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
516
+ input[type=email]{width:100%;height:42px;padding:0 12px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit}
517
+ input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
518
+ .primary{margin-top:12px;width:100%;height:42px;border:0;border-radius:8px;background:var(--accent);color:var(--accent-ink);font-family:inherit;font-size:15px;font-weight:600;cursor:pointer}
519
+ h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
520
+ .list{display:grid;gap:8px}
521
+ .option{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;padding:11px 12px;border:1px solid var(--line);border-radius:8px;background:transparent;color:var(--ink);font:inherit;cursor:pointer}
522
+ .option:hover{border-color:var(--muted)}
523
+ .option strong{display:block;font-weight:500}
524
+ .option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
525
+ .tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
526
+ .error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
527
+ `;
528
+ function escapeHtml(value) {
529
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
530
+ }
531
+ function layout(title, body) {
532
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body><main><div class="brand">kinde-testkit</div>${body}</main></body></html>`;
533
+ }
534
+ function displayName(user) {
535
+ return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
536
+ }
537
+ function renderSignIn(options) {
538
+ const users = options.users.map(({ user, organizations }) => {
539
+ const value = escapeHtml(user.email ?? user.id);
540
+ const hasName = Boolean(user.givenName || user.familyName);
541
+ const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
542
+ const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
543
+ return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag}</span></button>`;
544
+ }).join("");
545
+ const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
546
+ return layout(
547
+ "Sign in",
548
+ `<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}</form>`
549
+ );
550
+ }
551
+ function renderOrganizationPicker(options) {
552
+ const choices = options.organizations.map(
553
+ (org) => `<button class="option" type="submit" name="org" value="${escapeHtml(org.code)}"><span><strong>${escapeHtml(org.name)}</strong><small>${escapeHtml(org.code)}</small></span></button>`
554
+ ).join("");
555
+ return layout(
556
+ "Choose an organization",
557
+ `<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}"><div class="list" style="margin-top:20px">${choices}</div></form>`
558
+ );
559
+ }
560
+ function renderMessage(title, message) {
561
+ return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
562
+ }
361
563
 
362
564
  // src/seed.ts
565
+ function roleRecord(key, extra = {}) {
566
+ return {
567
+ id: stableId("role", key),
568
+ key,
569
+ name: extra.name ?? titleCase(key),
570
+ description: extra.description ?? null,
571
+ isDefault: extra.isDefault ?? false,
572
+ permissions: [...extra.permissions ?? []]
573
+ };
574
+ }
575
+ function permissionRecord(key, extra = {}) {
576
+ return {
577
+ id: stableId("perm", key),
578
+ key,
579
+ name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
580
+ description: extra.description ?? null
581
+ };
582
+ }
583
+ function effectivePermissions(seed, membership) {
584
+ if (!membership) return [];
585
+ const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
586
+ return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
587
+ }
363
588
  function resolveSeed(input) {
364
589
  const problems = [];
365
590
  if (!isRecord(input)) {
@@ -369,6 +594,23 @@ function resolveSeed(input) {
369
594
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
370
595
  const rawMemberships = listOf(input.memberships, "memberships", problems);
371
596
  const rawApplications = listOf(input.applications, "applications", problems);
597
+ const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
598
+ const rawRoles = listOf(input.roles, "roles", problems);
599
+ const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
600
+ const rawPlans = listOf(input.plans, "plans", problems);
601
+ const rawPermissions = listOf(input.permissions, "permissions", problems);
602
+ const webhooks = [];
603
+ rawWebhooks.forEach((raw, index) => {
604
+ if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
605
+ problems.push(`webhooks[${index}] needs an http or https "url".`);
606
+ return;
607
+ }
608
+ if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
609
+ problems.push(`webhooks[${index}].events must be a list of event type names.`);
610
+ return;
611
+ }
612
+ webhooks.push({ url: raw.url, events: raw.events });
613
+ });
372
614
  const users = [];
373
615
  rawUsers.forEach((raw, index) => {
374
616
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -460,7 +702,107 @@ function resolveSeed(input) {
460
702
  if (problems.length > 0) {
461
703
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
462
704
  }
463
- return { users, organizations, memberships, applications };
705
+ const permissions = [];
706
+ rawPermissions.forEach((raw, index) => {
707
+ if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
708
+ problems.push(`permissions[${index}] needs a string "key".`);
709
+ return;
710
+ }
711
+ if (permissions.some((p) => p.key === raw.key)) {
712
+ problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
713
+ return;
714
+ }
715
+ permissions.push(
716
+ permissionRecord(raw.key, {
717
+ name: typeof raw.name === "string" ? raw.name : void 0,
718
+ description: typeof raw.description === "string" ? raw.description : void 0
719
+ })
720
+ );
721
+ });
722
+ const roles = [];
723
+ rawRoles.forEach((raw, index) => {
724
+ if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
725
+ problems.push(`roles[${index}] needs a string "key".`);
726
+ return;
727
+ }
728
+ if (roles.some((r) => r.key === raw.key)) {
729
+ problems.push(`roles[${index}] repeats the key "${raw.key}".`);
730
+ return;
731
+ }
732
+ if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
733
+ problems.push(`roles[${index}].permissions must be a list of permission keys.`);
734
+ return;
735
+ }
736
+ roles.push(
737
+ roleRecord(raw.key, {
738
+ name: typeof raw.name === "string" ? raw.name : void 0,
739
+ description: typeof raw.description === "string" ? raw.description : void 0,
740
+ isDefault: raw.isDefault === true,
741
+ permissions: raw.permissions ?? []
742
+ })
743
+ );
744
+ });
745
+ if (problems.length > 0) {
746
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
747
+ }
748
+ const featureFlags = [];
749
+ rawFlags.forEach((raw, index) => {
750
+ if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
751
+ problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
752
+ return;
753
+ }
754
+ const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
755
+ featureFlags.push({
756
+ id: stableId("flag", raw.key),
757
+ key: raw.key,
758
+ name: typeof raw.name === "string" ? raw.name : raw.key,
759
+ type,
760
+ value: raw.value,
761
+ organizations: isRecord(raw.organizations) ? raw.organizations : {}
762
+ });
763
+ });
764
+ const plans = [];
765
+ rawPlans.forEach((raw, index) => {
766
+ if (!isRecord(raw) || typeof raw.key !== "string") {
767
+ problems.push(`plans[${index}] needs a string "key".`);
768
+ return;
769
+ }
770
+ const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
771
+ plans.push({
772
+ key: raw.key,
773
+ name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
774
+ subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
775
+ subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
776
+ entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
777
+ id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
778
+ featureKey: e.featureKey,
779
+ featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
780
+ priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
781
+ fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
782
+ unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
783
+ limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
784
+ limitMin: typeof e.limitMin === "number" ? e.limitMin : null
785
+ }))
786
+ });
787
+ });
788
+ const userProperties = {};
789
+ rawUsers.forEach((raw) => {
790
+ if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
791
+ userProperties[raw.id] = raw.properties;
792
+ }
793
+ });
794
+ if (problems.length > 0) {
795
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
796
+ }
797
+ const usedRoles = new Set(memberships.flatMap((m) => m.roles));
798
+ for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
799
+ const usedPermissions = /* @__PURE__ */ new Set([
800
+ ...memberships.flatMap((m) => m.permissions),
801
+ ...roles.flatMap((r) => r.permissions),
802
+ ...applications.flatMap((a) => a.permissions ?? [])
803
+ ]);
804
+ for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
805
+ return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
464
806
  }
465
807
  function findUser(users, ref) {
466
808
  const needle = ref.toLowerCase();
@@ -505,7 +847,7 @@ function seedScenario(seed, ref) {
505
847
  user,
506
848
  organization,
507
849
  roles: [...membership?.roles ?? []],
508
- permissions: [...membership?.permissions ?? []],
850
+ permissions: effectivePermissions(seed, membership),
509
851
  claims: {}
510
852
  };
511
853
  }
@@ -520,72 +862,18 @@ function listOf(value, field, problems) {
520
862
  function isRecord(value) {
521
863
  return typeof value === "object" && value !== null && !Array.isArray(value);
522
864
  }
523
-
524
- // src/oauth.ts
525
- import { createHash as createHash2, randomBytes, timingSafeEqual } from "crypto";
526
-
527
- // src/login-page.ts
528
- var STYLE = `
529
- :root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--warn:#8a5a00;--warn-bg:#fff6e0}
530
- @media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--warn:#f0c46a;--warn-bg:#2a2210}}
531
- *{box-sizing:border-box}
532
- body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;padding:24px}
533
- main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
534
- .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
535
- h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
536
- p{margin:0;color:var(--muted)}
537
- .note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
538
- form{margin:0}
539
- label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
540
- input[type=email]{width:100%;height:42px;padding:0 12px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit}
541
- input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
542
- .primary{margin-top:12px;width:100%;height:42px;border:0;border-radius:8px;background:var(--accent);color:var(--accent-ink);font-family:inherit;font-size:15px;font-weight:600;cursor:pointer}
543
- h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
544
- .list{display:grid;gap:8px}
545
- .option{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;padding:11px 12px;border:1px solid var(--line);border-radius:8px;background:transparent;color:var(--ink);font:inherit;cursor:pointer}
546
- .option:hover{border-color:var(--muted)}
547
- .option strong{display:block;font-weight:500}
548
- .option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
549
- .tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
550
- .error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
551
- `;
552
- function escapeHtml(value) {
553
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
554
- }
555
- function layout(title, body) {
556
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body><main><div class="brand">kinde-testkit</div>${body}</main></body></html>`;
557
- }
558
- function displayName(user) {
559
- return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
560
- }
561
- function renderSignIn(options) {
562
- const users = options.users.map(({ user, organizations }) => {
563
- const value = escapeHtml(user.email ?? user.id);
564
- const hasName = Boolean(user.givenName || user.familyName);
565
- const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
566
- const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
567
- return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag}</span></button>`;
568
- }).join("");
569
- const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
570
- return layout(
571
- "Sign in",
572
- `<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}</form>`
573
- );
574
- }
575
- function renderOrganizationPicker(options) {
576
- const choices = options.organizations.map(
577
- (org) => `<button class="option" type="submit" name="org" value="${escapeHtml(org.code)}"><span><strong>${escapeHtml(org.name)}</strong><small>${escapeHtml(org.code)}</small></span></button>`
578
- ).join("");
579
- return layout(
580
- "Choose an organization",
581
- `<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}"><div class="list" style="margin-top:20px">${choices}</div></form>`
582
- );
583
- }
584
- function renderMessage(title, message) {
585
- return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
865
+ function featureFlagsFor(seed, organizationCode) {
866
+ if (seed.featureFlags.length === 0) return void 0;
867
+ const claim = {};
868
+ for (const flag of seed.featureFlags) {
869
+ const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
870
+ claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
871
+ }
872
+ return claim;
586
873
  }
587
874
 
588
875
  // src/oauth.ts
876
+ import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
589
877
  var CODE_LIFETIME_MS = 10 * 60 * 1e3;
590
878
  var OAuthError = class extends Error {
591
879
  constructor(status, error, description) {
@@ -597,12 +885,16 @@ var OAuthError = class extends Error {
597
885
  error;
598
886
  };
599
887
  var AuthorizationServer = class {
600
- constructor(testkit, seed) {
888
+ constructor(testkit, seed, emit = () => void 0, directory) {
601
889
  this.testkit = testkit;
602
890
  this.seed = seed;
891
+ this.emit = emit;
892
+ this.directory = directory;
603
893
  }
604
894
  testkit;
605
895
  seed;
896
+ emit;
897
+ directory;
606
898
  codes = /* @__PURE__ */ new Map();
607
899
  refreshTokens = /* @__PURE__ */ new Map();
608
900
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -668,6 +960,18 @@ var AuthorizationServer = class {
668
960
  if (!user) {
669
961
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
670
962
  }
963
+ if (this.directory?.isSuspended(user.id)) {
964
+ return sendHtml(
965
+ res,
966
+ 403,
967
+ renderSignIn({
968
+ request: encoded,
969
+ users: this.loginPageUsers(),
970
+ requiredOrganization: request.orgCode ?? void 0,
971
+ error: `${user.email ?? user.id} is suspended and cannot sign in.`
972
+ })
973
+ );
974
+ }
671
975
  const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
672
976
  const wanted = request.orgCode ?? form.org ?? null;
673
977
  let organizationCode = null;
@@ -704,7 +1008,7 @@ var AuthorizationServer = class {
704
1008
  user,
705
1009
  organization: organizationCode ? this.organization(organizationCode) : null,
706
1010
  roles: [...membership?.roles ?? []],
707
- permissions: [...membership?.permissions ?? []],
1011
+ permissions: effectivePermissions(this.seed, membership),
708
1012
  claims: {}
709
1013
  };
710
1014
  const code = randomToken();
@@ -720,6 +1024,8 @@ var AuthorizationServer = class {
720
1024
  codeChallengeMethod: request.codeChallengeMethod,
721
1025
  expiresAt: Date.now() + CODE_LIFETIME_MS
722
1026
  });
1027
+ this.directory?.recordSignIn(user, organizationCode);
1028
+ this.emit("user.authenticated", user);
723
1029
  const target = new URL(request.redirectUri);
724
1030
  target.searchParams.set("code", code);
725
1031
  if (request.state !== null) target.searchParams.set("state", request.state);
@@ -754,7 +1060,7 @@ var AuthorizationServer = class {
754
1060
  throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
755
1061
  }
756
1062
  const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
757
- const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
1063
+ const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
758
1064
  const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
759
1065
  return {
760
1066
  access_token: await this.testkit.m2mToken({
@@ -790,7 +1096,7 @@ var AuthorizationServer = class {
790
1096
  }
791
1097
  if (pending.codeChallenge) {
792
1098
  const verifier = form.code_verifier ?? "";
793
- const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash2("sha256").update(verifier).digest("base64url");
1099
+ const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
794
1100
  if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
795
1101
  throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
796
1102
  }
@@ -820,7 +1126,8 @@ var AuthorizationServer = class {
820
1126
  scopes: grant.scope,
821
1127
  clientId: grant.clientId,
822
1128
  audience: grant.audience.length > 0 ? grant.audience : void 0,
823
- authTime: grant.authTime
1129
+ authTime: grant.authTime,
1130
+ featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
824
1131
  }),
825
1132
  expires_in: this.testkit.accessTokenLifetime,
826
1133
  scope: grant.scope.join(" "),
@@ -885,8 +1192,12 @@ var AuthorizationServer = class {
885
1192
  if (seeded) return seeded;
886
1193
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
887
1194
  const user = createKindeUser({ email: ref.toLowerCase() });
888
- this.signedUpUsers.set(user.id, user);
889
- return user;
1195
+ if (!this.signedUpUsers.has(user.id)) {
1196
+ this.signedUpUsers.set(user.id, user);
1197
+ if (this.directory) this.seed.users.push(user);
1198
+ this.emit("user.created", user);
1199
+ }
1200
+ return this.signedUpUsers.get(user.id);
890
1201
  }
891
1202
  organization(code) {
892
1203
  return this.seed.organizations.find((org) => org.code === code) ?? null;
@@ -971,7 +1282,7 @@ function isHttpUrl(value) {
971
1282
  }
972
1283
  }
973
1284
  function randomToken() {
974
- return randomBytes(32).toString("base64url");
1285
+ return randomBytes2(32).toString("base64url");
975
1286
  }
976
1287
  function safeEqual(a, b) {
977
1288
  const left = Buffer.from(a);
@@ -995,6 +1306,687 @@ function sendJson(res, status, body) {
995
1306
  res.end(JSON.stringify(body));
996
1307
  }
997
1308
 
1309
+ // src/account.ts
1310
+ var DEFAULT_PAGE_SIZE = 10;
1311
+ var AccountApi = class {
1312
+ constructor(testkit, directory) {
1313
+ this.testkit = testkit;
1314
+ this.directory = directory;
1315
+ }
1316
+ testkit;
1317
+ directory;
1318
+ async handle(req, res, url) {
1319
+ if (!url.pathname.startsWith("/account_api/v1/")) return false;
1320
+ if ((req.method ?? "GET") !== "GET") {
1321
+ sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
1322
+ return true;
1323
+ }
1324
+ const header = req.headers.authorization ?? "";
1325
+ let token;
1326
+ try {
1327
+ if (!header.startsWith("Bearer ")) throw new Error("missing");
1328
+ token = await this.testkit.verify(header.slice(7));
1329
+ } catch {
1330
+ sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
1331
+ return true;
1332
+ }
1333
+ if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
1334
+ sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
1335
+ return true;
1336
+ }
1337
+ const userId = token.sub;
1338
+ const orgCode = typeof token.org_code === "string" ? token.org_code : null;
1339
+ const path = url.pathname.slice("/account_api/v1/".length);
1340
+ const d = this.directory;
1341
+ const membership = orgCode ? d.membership(userId, orgCode) : void 0;
1342
+ if (path === "permissions") {
1343
+ const items = effectivePermissions(d.seed, membership).map((key) => {
1344
+ const p = d.ensurePermission(key);
1345
+ return { id: p.id, name: p.name, key: p.key };
1346
+ });
1347
+ sendPage(res, url, "permissions", items, { org_code: orgCode });
1348
+ return true;
1349
+ }
1350
+ if (path.startsWith("permission/")) {
1351
+ const key = decodeURIComponent(path.slice("permission/".length));
1352
+ sendJson2(res, 200, {
1353
+ data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
1354
+ });
1355
+ return true;
1356
+ }
1357
+ if (path === "roles") {
1358
+ const items = (membership?.roles ?? []).map((key) => {
1359
+ const r = d.ensureRole(key);
1360
+ return { id: r.id, name: r.name, key: r.key };
1361
+ });
1362
+ sendPage(res, url, "roles", items, { org_code: orgCode });
1363
+ return true;
1364
+ }
1365
+ if (path === "feature_flags") {
1366
+ const items = d.seed.featureFlags.map((flag) => ({
1367
+ id: flag.id,
1368
+ name: flag.name,
1369
+ key: flag.key,
1370
+ type: flag.type,
1371
+ value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
1372
+ }));
1373
+ sendPage(res, url, "feature_flags", items, {});
1374
+ return true;
1375
+ }
1376
+ if (path === "properties") {
1377
+ const values = d.seed.userProperties[userId] ?? {};
1378
+ const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
1379
+ sendPage(res, url, "properties", items, {});
1380
+ return true;
1381
+ }
1382
+ if (path === "entitlements" || path.startsWith("entitlement")) {
1383
+ const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
1384
+ const entitlements = (plan?.entitlements ?? []).map((e) => ({
1385
+ id: e.id,
1386
+ fixed_charge: e.fixedCharge,
1387
+ price_name: e.priceName,
1388
+ unit_amount: e.unitAmount,
1389
+ feature_key: e.featureKey,
1390
+ feature_name: e.featureName,
1391
+ entitlement_limit_max: e.limitMax,
1392
+ entitlement_limit_min: e.limitMin
1393
+ }));
1394
+ if (path === "entitlements") {
1395
+ const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
1396
+ sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
1397
+ return true;
1398
+ }
1399
+ const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
1400
+ const entitlement = entitlements.find((e) => e.feature_key === key);
1401
+ if (!entitlement) {
1402
+ sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
1403
+ } else {
1404
+ sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
1405
+ }
1406
+ return true;
1407
+ }
1408
+ if (path === "portal_link") {
1409
+ sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
1410
+ return true;
1411
+ }
1412
+ sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
1413
+ return true;
1414
+ }
1415
+ };
1416
+ function sendPage(res, url, field, items, extra) {
1417
+ const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
1418
+ const after = url.searchParams.get("starting_after");
1419
+ const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
1420
+ const page = items.slice(start, start + size);
1421
+ const hasMore = start + size < items.length;
1422
+ sendJson2(res, 200, {
1423
+ data: { ...extra, [field]: page },
1424
+ metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
1425
+ });
1426
+ }
1427
+ function errors(code, message) {
1428
+ return { errors: [{ code, message }] };
1429
+ }
1430
+ function sendJson2(res, status, body) {
1431
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1432
+ res.end(JSON.stringify(body));
1433
+ }
1434
+
1435
+ // src/directory.ts
1436
+ import { randomBytes as randomBytes3 } from "crypto";
1437
+ var Directory = class {
1438
+ constructor(seed) {
1439
+ this.seed = seed;
1440
+ this.snapshot = JSON.stringify(seed);
1441
+ }
1442
+ seed;
1443
+ userMeta = /* @__PURE__ */ new Map();
1444
+ orgMeta = /* @__PURE__ */ new Map();
1445
+ snapshot;
1446
+ restore() {
1447
+ const original = JSON.parse(this.snapshot);
1448
+ for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
1449
+ this.seed[key].splice(0, this.seed[key].length, ...original[key]);
1450
+ }
1451
+ this.userMeta.clear();
1452
+ this.orgMeta.clear();
1453
+ }
1454
+ user(id) {
1455
+ return this.seed.users.find((user) => user.id === id);
1456
+ }
1457
+ meta(user) {
1458
+ let meta = this.userMeta.get(user.id);
1459
+ if (!meta) {
1460
+ meta = {
1461
+ providedId: null,
1462
+ isSuspended: false,
1463
+ isPasswordResetRequested: false,
1464
+ createdOn: (/* @__PURE__ */ new Date()).toISOString(),
1465
+ totalSignIns: 0,
1466
+ lastSignedIn: null
1467
+ };
1468
+ this.userMeta.set(user.id, meta);
1469
+ }
1470
+ return meta;
1471
+ }
1472
+ isSuspended(userId) {
1473
+ return this.userMeta.get(userId)?.isSuspended ?? false;
1474
+ }
1475
+ recordSignIn(user, organizationCode) {
1476
+ const meta = this.meta(user);
1477
+ meta.totalSignIns += 1;
1478
+ meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
1479
+ void organizationCode;
1480
+ }
1481
+ createUser(input) {
1482
+ const user = createKindeUser({
1483
+ id: `kp_${randomBytes3(16).toString("hex")}`,
1484
+ email: input.email ?? null,
1485
+ givenName: input.givenName ?? null,
1486
+ familyName: input.familyName ?? null,
1487
+ picture: input.picture ?? null
1488
+ });
1489
+ this.seed.users.push(user);
1490
+ this.meta(user).providedId = input.providedId ?? null;
1491
+ return user;
1492
+ }
1493
+ deleteUser(id) {
1494
+ const index = this.seed.users.findIndex((user) => user.id === id);
1495
+ if (index < 0) return false;
1496
+ this.seed.users.splice(index, 1);
1497
+ for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
1498
+ if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
1499
+ }
1500
+ this.userMeta.delete(id);
1501
+ return true;
1502
+ }
1503
+ organization(code) {
1504
+ return this.seed.organizations.find((org) => org.code === code);
1505
+ }
1506
+ orgInfo(org) {
1507
+ let meta = this.orgMeta.get(org.code);
1508
+ if (!meta) {
1509
+ meta = {
1510
+ externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
1511
+ handle: slug(org.name),
1512
+ createdOn: (/* @__PURE__ */ new Date()).toISOString(),
1513
+ isAllowRegistrations: false
1514
+ };
1515
+ this.orgMeta.set(org.code, meta);
1516
+ }
1517
+ return meta;
1518
+ }
1519
+ createOrganization(input) {
1520
+ const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
1521
+ this.seed.organizations.push(org);
1522
+ const meta = this.orgInfo(org);
1523
+ meta.externalId = input.externalId ?? null;
1524
+ if (input.handle) meta.handle = input.handle;
1525
+ return org;
1526
+ }
1527
+ deleteOrganization(code) {
1528
+ const index = this.seed.organizations.findIndex((org) => org.code === code);
1529
+ if (index < 0) return false;
1530
+ this.seed.organizations.splice(index, 1);
1531
+ for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
1532
+ if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
1533
+ }
1534
+ this.orgMeta.delete(code);
1535
+ return true;
1536
+ }
1537
+ membership(userId, organizationCode) {
1538
+ return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
1539
+ }
1540
+ addMembership(userId, organizationCode, roles = [], permissions = []) {
1541
+ const existing = this.membership(userId, organizationCode);
1542
+ if (existing) return existing;
1543
+ const membership = createMembership({ userId, organizationCode, roles, permissions });
1544
+ this.seed.memberships.push(membership);
1545
+ for (const key of roles) this.ensureRole(key);
1546
+ for (const key of permissions) this.ensurePermission(key);
1547
+ return membership;
1548
+ }
1549
+ removeMembership(userId, organizationCode) {
1550
+ const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
1551
+ if (index < 0) return false;
1552
+ this.seed.memberships.splice(index, 1);
1553
+ return true;
1554
+ }
1555
+ role(idOrKey) {
1556
+ return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
1557
+ }
1558
+ permission(idOrKey) {
1559
+ return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
1560
+ }
1561
+ ensureRole(key, extra = {}) {
1562
+ const existing = this.role(key);
1563
+ if (existing) return existing;
1564
+ const role = roleRecord(key, extra);
1565
+ this.seed.roles.push(role);
1566
+ return role;
1567
+ }
1568
+ ensurePermission(key, extra = {}) {
1569
+ const existing = this.permission(key);
1570
+ if (existing) return existing;
1571
+ const permission = permissionRecord(key, extra);
1572
+ this.seed.permissions.push(permission);
1573
+ return permission;
1574
+ }
1575
+ deleteRole(id) {
1576
+ const role = this.role(id);
1577
+ if (!role) return void 0;
1578
+ this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
1579
+ for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
1580
+ return role;
1581
+ }
1582
+ deletePermission(id) {
1583
+ const permission = this.permission(id);
1584
+ if (!permission) return void 0;
1585
+ this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
1586
+ for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
1587
+ for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
1588
+ return permission;
1589
+ }
1590
+ };
1591
+
1592
+ // src/management.ts
1593
+ var OK = { code: "OK", message: "Success" };
1594
+ var DEFAULT_PAGE_SIZE2 = 10;
1595
+ var MAX_PAGE_SIZE = 500;
1596
+ var ManagementApi = class {
1597
+ constructor(testkit, directory, webhooks) {
1598
+ this.testkit = testkit;
1599
+ this.directory = directory;
1600
+ this.webhooks = webhooks;
1601
+ this.register();
1602
+ }
1603
+ testkit;
1604
+ directory;
1605
+ webhooks;
1606
+ routes = [];
1607
+ async handle(req, res, url, readBody) {
1608
+ if (!url.pathname.startsWith("/api/v1/")) return false;
1609
+ const method = req.method ?? "GET";
1610
+ const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
1611
+ if (!route) {
1612
+ sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
1613
+ return true;
1614
+ }
1615
+ const token = await this.authenticate(req.headers.authorization);
1616
+ if ("error" in token) {
1617
+ sendJson3(res, 403, errors2(token.code, token.error));
1618
+ return true;
1619
+ }
1620
+ const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
1621
+ if (granted.length > 0 && !granted.includes(route.scope)) {
1622
+ sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
1623
+ return true;
1624
+ }
1625
+ const match = route.pattern.exec(url.pathname);
1626
+ const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
1627
+ const body = method === "GET" || method === "DELETE" ? {} : await readBody();
1628
+ const [status, payload] = await route.handler({ params, query: url.searchParams, body });
1629
+ sendJson3(res, status, payload);
1630
+ return true;
1631
+ }
1632
+ async authenticate(header) {
1633
+ if (!header?.startsWith("Bearer ")) {
1634
+ return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
1635
+ }
1636
+ let payload;
1637
+ try {
1638
+ payload = await this.testkit.verify(header.slice(7));
1639
+ } catch {
1640
+ return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
1641
+ }
1642
+ const audience = `${this.testkit.issuer}/api`;
1643
+ const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
1644
+ if (!aud.includes(audience)) {
1645
+ return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
1646
+ }
1647
+ if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
1648
+ return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
1649
+ }
1650
+ return { payload };
1651
+ }
1652
+ route(method, path, scope, handler) {
1653
+ const keys = [];
1654
+ const pattern = new RegExp(
1655
+ `^${path.replace(/\{(\w+)\}/g, (_, key) => {
1656
+ keys.push(key);
1657
+ return "([^/]+)";
1658
+ })}$`
1659
+ );
1660
+ this.routes.push({ method, pattern, keys, scope, handler });
1661
+ }
1662
+ register() {
1663
+ const d = this.directory;
1664
+ this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
1665
+ let users = [...d.seed.users];
1666
+ const userId = query.get("user_id");
1667
+ const email = query.get("email")?.toLowerCase();
1668
+ if (userId) users = users.filter((u) => u.id === userId);
1669
+ if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
1670
+ const page = paginate(users, query);
1671
+ return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
1672
+ });
1673
+ this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
1674
+ const user = d.user(query.get("id") ?? "");
1675
+ return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
1676
+ });
1677
+ this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
1678
+ const profile = body.profile ?? {};
1679
+ const identities = Array.isArray(body.identities) ? body.identities : [];
1680
+ const emailIdentity = identities.find((i) => i.type === "email");
1681
+ const email = (emailIdentity?.details ?? {}).email;
1682
+ if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
1683
+ return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
1684
+ }
1685
+ const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
1686
+ if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
1687
+ const user = d.createUser({
1688
+ email: typeof email === "string" ? email : null,
1689
+ givenName: str(profile.given_name),
1690
+ familyName: str(profile.family_name),
1691
+ picture: str(profile.picture),
1692
+ providedId: str(body.provided_id)
1693
+ });
1694
+ if (orgCode) d.addMembership(user.id, orgCode);
1695
+ this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
1696
+ return [
1697
+ 200,
1698
+ { id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
1699
+ ];
1700
+ });
1701
+ this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
1702
+ const user = d.user(query.get("id") ?? "");
1703
+ if (!user) return notFound("USER_INVALID", "No user has that id.");
1704
+ if (typeof body.given_name === "string") user.givenName = body.given_name;
1705
+ if (typeof body.family_name === "string") user.familyName = body.family_name;
1706
+ if (typeof body.picture === "string") user.picture = body.picture;
1707
+ const meta = d.meta(user);
1708
+ if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
1709
+ if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
1710
+ if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
1711
+ this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
1712
+ return [
1713
+ 200,
1714
+ {
1715
+ id: user.id,
1716
+ given_name: user.givenName,
1717
+ family_name: user.familyName,
1718
+ email: user.email,
1719
+ is_suspended: meta.isSuspended,
1720
+ is_password_reset_requested: meta.isPasswordResetRequested,
1721
+ picture: user.picture
1722
+ }
1723
+ ];
1724
+ });
1725
+ this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
1726
+ const id = query.get("id") ?? "";
1727
+ if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
1728
+ this.webhooks.emit("user.deleted", { user: { id } });
1729
+ return [200, OK];
1730
+ });
1731
+ this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
1732
+ const page = paginate(d.seed.organizations, query);
1733
+ return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
1734
+ });
1735
+ this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
1736
+ const org = d.organization(query.get("code") ?? "");
1737
+ if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1738
+ const meta = d.orgInfo(org);
1739
+ return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
1740
+ });
1741
+ this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
1742
+ if (typeof body.name !== "string" || body.name.trim() === "") {
1743
+ return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
1744
+ }
1745
+ const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
1746
+ if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
1747
+ this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
1748
+ return [200, { ...OK, organization: { code: org.code } }];
1749
+ });
1750
+ this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
1751
+ const org = d.organization(params.org_code);
1752
+ if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1753
+ const meta = d.orgInfo(org);
1754
+ if (typeof body.name === "string") org.name = body.name;
1755
+ if (typeof body.external_id === "string") meta.externalId = body.external_id;
1756
+ if (typeof body.handle === "string") meta.handle = body.handle;
1757
+ if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
1758
+ this.webhooks.emit("organization.updated", {
1759
+ organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
1760
+ });
1761
+ return [200, OK];
1762
+ });
1763
+ this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
1764
+ if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1765
+ this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
1766
+ return [200, OK];
1767
+ });
1768
+ this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
1769
+ if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1770
+ const members = d.seed.memberships.filter((m) => m.organizationCode === params.org_code).map((m) => ({ membership: m, user: d.user(m.userId) })).filter((m) => m.user !== void 0);
1771
+ const page = paginate(members, query);
1772
+ return [
1773
+ 200,
1774
+ {
1775
+ ...OK,
1776
+ organization_users: page.items.map(({ membership, user }) => ({
1777
+ id: user.id,
1778
+ email: user.email,
1779
+ full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
1780
+ last_name: user.familyName,
1781
+ first_name: user.givenName,
1782
+ picture: user.picture,
1783
+ joined_on: d.meta(user).createdOn,
1784
+ last_accessed_on: d.meta(user).lastSignedIn,
1785
+ is_suspended: d.meta(user).isSuspended,
1786
+ roles: [...membership.roles]
1787
+ })),
1788
+ next_token: page.nextToken
1789
+ }
1790
+ ];
1791
+ });
1792
+ this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
1793
+ if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1794
+ const users = Array.isArray(body.users) ? body.users : [];
1795
+ const added = [];
1796
+ const blocked = [];
1797
+ for (const entry of users) {
1798
+ const id = typeof entry.id === "string" ? entry.id : "";
1799
+ if (!d.user(id)) {
1800
+ blocked.push(id);
1801
+ continue;
1802
+ }
1803
+ d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
1804
+ added.push(id);
1805
+ }
1806
+ return [200, { ...OK, users_added: added, users_blocked: blocked }];
1807
+ });
1808
+ this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
1809
+ return d.removeMembership(params.user_id, params.org_code) ? [200, OK] : notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1810
+ });
1811
+ this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
1812
+ const membership = d.membership(params.user_id, params.org_code);
1813
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1814
+ const roles = membership.roles.map((key) => d.ensureRole(key));
1815
+ return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
1816
+ });
1817
+ this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
1818
+ const membership = d.membership(params.user_id, params.org_code);
1819
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1820
+ const role = d.role(str(body.role_id) ?? "");
1821
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1822
+ if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
1823
+ return [200, OK];
1824
+ });
1825
+ this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
1826
+ const membership = d.membership(params.user_id, params.org_code);
1827
+ const role = d.role(params.role_id);
1828
+ if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
1829
+ membership.roles = membership.roles.filter((key) => key !== role.key);
1830
+ return [200, OK];
1831
+ });
1832
+ this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
1833
+ const membership = d.membership(params.user_id, params.org_code);
1834
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1835
+ const permissions = effectivePermissions(d.seed, membership).map((key) => {
1836
+ const permission = d.ensurePermission(key);
1837
+ const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
1838
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
1839
+ });
1840
+ return [200, { ...OK, permissions }];
1841
+ });
1842
+ this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
1843
+ const membership = d.membership(params.user_id, params.org_code);
1844
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1845
+ const permission = d.permission(str(body.permission_id) ?? "");
1846
+ if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
1847
+ if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
1848
+ return [200, OK];
1849
+ });
1850
+ this.route(
1851
+ "DELETE",
1852
+ "/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
1853
+ "delete:organization_user_permissions",
1854
+ ({ params }) => {
1855
+ const membership = d.membership(params.user_id, params.org_code);
1856
+ const permission = d.permission(params.permission_id);
1857
+ if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
1858
+ membership.permissions = membership.permissions.filter((key) => key !== permission.key);
1859
+ return [200, OK];
1860
+ }
1861
+ );
1862
+ this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
1863
+ const page = paginate(d.seed.roles, query);
1864
+ return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
1865
+ });
1866
+ this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
1867
+ const key = str(body.key);
1868
+ if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
1869
+ if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
1870
+ const role = d.ensureRole(key, {
1871
+ name: str(body.name) ?? void 0,
1872
+ description: str(body.description) ?? void 0,
1873
+ isDefault: body.is_default_role === true
1874
+ });
1875
+ this.webhooks.emit("role.created", {
1876
+ role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
1877
+ });
1878
+ return [201, { ...OK, role: { id: role.id } }];
1879
+ });
1880
+ this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
1881
+ const role = d.role(params.role_id);
1882
+ return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
1883
+ });
1884
+ this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
1885
+ const role = d.deleteRole(params.role_id);
1886
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1887
+ this.webhooks.emit("role.deleted", { role: { id: role.id } });
1888
+ return [200, OK];
1889
+ });
1890
+ this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
1891
+ const role = d.role(params.role_id);
1892
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1893
+ return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
1894
+ });
1895
+ this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
1896
+ const page = paginate(d.seed.permissions, query);
1897
+ return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
1898
+ });
1899
+ this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
1900
+ const key = str(body.key);
1901
+ if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
1902
+ if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
1903
+ const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
1904
+ this.webhooks.emit("permission.created", {
1905
+ permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
1906
+ });
1907
+ return [201, OK];
1908
+ });
1909
+ this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
1910
+ const permission = d.deletePermission(params.permission_id);
1911
+ if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
1912
+ this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
1913
+ return [200, OK];
1914
+ });
1915
+ }
1916
+ userListItem(user) {
1917
+ const meta = this.directory.meta(user);
1918
+ return {
1919
+ id: user.id,
1920
+ provided_id: meta.providedId,
1921
+ email: user.email,
1922
+ phone: null,
1923
+ username: null,
1924
+ last_name: user.familyName,
1925
+ first_name: user.givenName,
1926
+ is_suspended: meta.isSuspended,
1927
+ picture: user.picture,
1928
+ total_sign_ins: meta.totalSignIns,
1929
+ failed_sign_ins: 0,
1930
+ last_signed_in: meta.lastSignedIn,
1931
+ created_on: meta.createdOn,
1932
+ organizations: this.organizationsOf(user),
1933
+ identities: user.email ? [{ type: "email", identity: user.email }] : []
1934
+ };
1935
+ }
1936
+ userDetail(user) {
1937
+ const { email, ...rest } = this.userListItem(user);
1938
+ return { ...rest, preferred_email: email };
1939
+ }
1940
+ organizationsOf(user) {
1941
+ return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
1942
+ }
1943
+ organizationItem(org) {
1944
+ const meta = this.directory.orgInfo(org);
1945
+ return {
1946
+ code: org.code,
1947
+ name: org.name,
1948
+ handle: meta.handle,
1949
+ is_default: false,
1950
+ external_id: meta.externalId,
1951
+ is_auto_membership_enabled: false
1952
+ };
1953
+ }
1954
+ organizationEvent(org) {
1955
+ const meta = this.directory.orgInfo(org);
1956
+ return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
1957
+ }
1958
+ roleItem(role) {
1959
+ return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
1960
+ }
1961
+ permissionItem(permission) {
1962
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
1963
+ }
1964
+ };
1965
+ function paginate(items, query) {
1966
+ const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
1967
+ const token = query.get("next_token");
1968
+ const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
1969
+ const page = items.slice(offset, offset + size);
1970
+ const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
1971
+ return { items: page, nextToken: next };
1972
+ }
1973
+ function errors2(code, message) {
1974
+ return { errors: [{ code, message }] };
1975
+ }
1976
+ function notFound(code, message) {
1977
+ return [404, errors2(code, message)];
1978
+ }
1979
+ function str(value) {
1980
+ return typeof value === "string" ? value : null;
1981
+ }
1982
+ function strings(value) {
1983
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
1984
+ }
1985
+ function sendJson3(res, status, body) {
1986
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1987
+ res.end(JSON.stringify(body));
1988
+ }
1989
+
998
1990
  // src/failures.ts
999
1991
  var MAX_DELAY_MS = 6e4;
1000
1992
  var FailureInjector = class {
@@ -1075,6 +2067,278 @@ function validate(rule) {
1075
2067
  return problems;
1076
2068
  }
1077
2069
 
2070
+ // src/webhooks.ts
2071
+ import { randomBytes as randomBytes4 } from "crypto";
2072
+ var WEBHOOK_EVENT_TYPES = [
2073
+ "user.created",
2074
+ "user.updated",
2075
+ "user.deleted",
2076
+ "user.authenticated",
2077
+ "user.authentication_failed",
2078
+ "organization.created",
2079
+ "organization.updated",
2080
+ "organization.deleted",
2081
+ "role.created",
2082
+ "role.updated",
2083
+ "role.deleted",
2084
+ "permission.created",
2085
+ "permission.updated",
2086
+ "permission.deleted",
2087
+ "subscriber.created",
2088
+ "access_request.created"
2089
+ ];
2090
+ var BILLING_EVENT_TYPES = [
2091
+ "customer.agreement_cancelled",
2092
+ "customer.agreement_created",
2093
+ "customer.invoice_overdue",
2094
+ "customer.meter_usage_updated",
2095
+ "customer.payment_failed",
2096
+ "customer.payment_succeeded",
2097
+ "customer.plan_assigned",
2098
+ "customer.plan_changed"
2099
+ ];
2100
+ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
2101
+ var DEFAULT_TIMEOUT_MS = 5e3;
2102
+ var MAX_DUPLICATES = 10;
2103
+ var WebhookDispatcher = class {
2104
+ constructor(testkit, seed, endpoints = [], options = {}) {
2105
+ this.testkit = testkit;
2106
+ this.seed = seed;
2107
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
2108
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2109
+ for (const endpoint of endpoints) this.addEndpoint(endpoint);
2110
+ this.seededEndpoints = [...this.endpoints];
2111
+ }
2112
+ testkit;
2113
+ seed;
2114
+ endpoints = [];
2115
+ seededEndpoints = [];
2116
+ log = [];
2117
+ nextEndpoint = 1;
2118
+ retryDelaysMs;
2119
+ timeoutMs;
2120
+ addEndpoint(input) {
2121
+ if (!isHttpUrl2(input.url)) {
2122
+ throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
2123
+ }
2124
+ if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
2125
+ throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
2126
+ }
2127
+ const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
2128
+ this.endpoints.push(endpoint);
2129
+ return { ...endpoint };
2130
+ }
2131
+ removeEndpoint(id) {
2132
+ const before = this.endpoints.length;
2133
+ this.endpoints = this.endpoints.filter((e) => e.id !== id);
2134
+ return this.endpoints.length < before;
2135
+ }
2136
+ listEndpoints() {
2137
+ return this.endpoints.map((e) => ({ ...e }));
2138
+ }
2139
+ deliveries() {
2140
+ return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
2141
+ }
2142
+ reset() {
2143
+ this.log = [];
2144
+ this.endpoints = [...this.seededEndpoints];
2145
+ }
2146
+ buildEvent(options) {
2147
+ if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
2148
+ throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
2149
+ }
2150
+ const now = /* @__PURE__ */ new Date();
2151
+ const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
2152
+ const event = {
2153
+ data: options.data ?? this.buildData(options),
2154
+ event_id: `event_${randomBytes4(16).toString("hex")}`,
2155
+ event_timestamp: timestamp,
2156
+ source: options.source ?? "admin",
2157
+ timestamp,
2158
+ type: options.type
2159
+ };
2160
+ if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
2161
+ event.ip_address = options.ipAddress ?? "127.0.0.1";
2162
+ }
2163
+ return event;
2164
+ }
2165
+ async send(options) {
2166
+ const event = this.buildEvent(options);
2167
+ const copies = options.duplicate ?? 1;
2168
+ if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
2169
+ throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
2170
+ }
2171
+ const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
2172
+ if (options.to && !isHttpUrl2(options.to)) {
2173
+ throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
2174
+ }
2175
+ if (targets.length === 0) {
2176
+ throw new TestkitError(
2177
+ "INVALID_REQUEST",
2178
+ `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
2179
+ );
2180
+ }
2181
+ if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
2182
+ const signed = await this.testkit.signPayload(
2183
+ event,
2184
+ options.invalid === "stale" ? void 0 : options.invalid
2185
+ );
2186
+ const jobs = targets.flatMap((target) => {
2187
+ const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
2188
+ return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
2189
+ });
2190
+ return Promise.all(jobs);
2191
+ }
2192
+ async deliver(url, webhookId, body, event, copy) {
2193
+ const delivery = {
2194
+ webhookId,
2195
+ eventId: String(event.event_id),
2196
+ type: String(event.type),
2197
+ url,
2198
+ copy,
2199
+ delivered: false,
2200
+ attempts: [],
2201
+ payload: event
2202
+ };
2203
+ this.log.push(delivery);
2204
+ for (const [index, delay] of this.retryDelaysMs.entries()) {
2205
+ if (delay > 0) await sleep(delay);
2206
+ const started = Date.now();
2207
+ try {
2208
+ const response = await fetch(url, {
2209
+ method: "POST",
2210
+ headers: { "content-type": "application/jwt", "webhook-id": webhookId },
2211
+ body,
2212
+ signal: AbortSignal.timeout(this.timeoutMs)
2213
+ });
2214
+ await response.arrayBuffer().catch(() => void 0);
2215
+ delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
2216
+ if (response.status === 200) {
2217
+ delivery.delivered = true;
2218
+ break;
2219
+ }
2220
+ } catch (error) {
2221
+ const name = error.name;
2222
+ delivery.attempts.push({
2223
+ attempt: index + 1,
2224
+ status: null,
2225
+ error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
2226
+ durationMs: Date.now() - started
2227
+ });
2228
+ }
2229
+ }
2230
+ return { ...delivery, attempts: [...delivery.attempts] };
2231
+ }
2232
+ buildData(options) {
2233
+ const [subject] = options.type.split(".");
2234
+ switch (subject) {
2235
+ case "user":
2236
+ return { user: this.userData(options) };
2237
+ case "organization":
2238
+ return { organization: this.organizationData(options) };
2239
+ case "role":
2240
+ return { role: this.namedData(options, "role") };
2241
+ case "permission":
2242
+ return { permission: this.namedData(options, "permission") };
2243
+ case "subscriber": {
2244
+ const user = this.requireUser(options);
2245
+ return {
2246
+ subscriber: {
2247
+ email: user.email,
2248
+ first_name: user.givenName,
2249
+ id: stableId("sub", user.id),
2250
+ last_name: user.familyName,
2251
+ user_id: user.id
2252
+ }
2253
+ };
2254
+ }
2255
+ case "access_request": {
2256
+ const user = this.requireUser(options);
2257
+ return {
2258
+ access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
2259
+ };
2260
+ }
2261
+ default:
2262
+ throw new TestkitError(
2263
+ "INVALID_REQUEST",
2264
+ `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
2265
+ );
2266
+ }
2267
+ }
2268
+ emit(type, data, source = "api") {
2269
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
2270
+ void this.send({ type, data, source }).catch(() => void 0);
2271
+ }
2272
+ userEventData(user) {
2273
+ return this.userPayload(user);
2274
+ }
2275
+ emitForUser(type, user) {
2276
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
2277
+ const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
2278
+ void this.send({ type, data, source: "user" }).catch(() => void 0);
2279
+ }
2280
+ userData(options) {
2281
+ const user = this.requireUser(options);
2282
+ if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
2283
+ return this.userPayload(user);
2284
+ }
2285
+ userPayload(user) {
2286
+ return {
2287
+ email: user.email,
2288
+ first_name: user.givenName,
2289
+ id: user.id,
2290
+ is_password_reset_requested: false,
2291
+ is_suspended: false,
2292
+ last_name: user.familyName,
2293
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
2294
+ code: m.organizationCode,
2295
+ permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
2296
+ roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
2297
+ })),
2298
+ phone: null,
2299
+ username: typeof user.claims.username === "string" ? user.claims.username : null
2300
+ };
2301
+ }
2302
+ organizationData(options) {
2303
+ if (!options.organization) {
2304
+ throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
2305
+ }
2306
+ const org = this.seed.organizations.find((o) => o.code === options.organization);
2307
+ if (options.type === "organization.deleted") return { code: options.organization };
2308
+ const name = org?.name ?? titleCase(options.organization);
2309
+ const data = { code: options.organization, external_id: null, handle: slug(name), name };
2310
+ if (options.type === "organization.updated") data.is_allow_registrations = false;
2311
+ return data;
2312
+ }
2313
+ namedData(options, kind) {
2314
+ const key = kind === "role" ? options.role : options.permission;
2315
+ if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
2316
+ const id = stableId(kind === "role" ? "role" : "perm", key);
2317
+ if (options.type.endsWith(".deleted")) return { id };
2318
+ const data = { description: "", id, key, name: titleCase(key) };
2319
+ if (kind === "role") data.is_default_role = false;
2320
+ return data;
2321
+ }
2322
+ requireUser(options) {
2323
+ if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
2324
+ const user = findUser(this.seed.users, options.user);
2325
+ if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
2326
+ return user;
2327
+ }
2328
+ };
2329
+ function isHttpUrl2(value) {
2330
+ if (typeof value !== "string") return false;
2331
+ try {
2332
+ const { protocol } = new URL(value);
2333
+ return protocol === "http:" || protocol === "https:";
2334
+ } catch {
2335
+ return false;
2336
+ }
2337
+ }
2338
+ function sleep(ms) {
2339
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
2340
+ }
2341
+
1078
2342
  // src/server.ts
1079
2343
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
1080
2344
  var MAX_BODY_BYTES = 64 * 1024;
@@ -1090,28 +2354,36 @@ async function startKindeTestkit(options = {}) {
1090
2354
  const seed = resolveSeed(options.seed ?? {});
1091
2355
  const failures = new FailureInjector();
1092
2356
  let ready;
1093
- const testkitReady = new Promise((resolve) => ready = resolve);
1094
- const server = createServer((req, res) => {
2357
+ const testkitReady = new Promise((resolve2) => ready = resolve2);
2358
+ const listener = (req, res) => {
1095
2359
  testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
1096
- });
1097
- await new Promise((resolve, reject) => {
2360
+ };
2361
+ const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
2362
+ const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
2363
+ await new Promise((resolve2, reject) => {
1098
2364
  server.once("error", reject);
1099
- server.listen(options.port ?? 4400, host, () => resolve());
2365
+ server.listen(options.port ?? 4400, host, () => resolve2());
1100
2366
  });
1101
2367
  const { port } = server.address();
1102
2368
  const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
1103
- const url = `http://${urlHost}:${port}`;
2369
+ const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
1104
2370
  const testkit = await KindeTestkit.create({
1105
2371
  issuer: options.issuer ?? options.seed?.issuer ?? url,
1106
2372
  audience: options.audience ?? options.seed?.audience,
1107
2373
  clientId: options.clientId ?? options.seed?.clientId
1108
2374
  });
1109
- const auth = new AuthorizationServer(testkit, seed);
2375
+ const directory = new Directory(seed);
2376
+ const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
2377
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
2378
+ const management = new ManagementApi(testkit, directory, webhooks);
2379
+ const account = new AccountApi(testkit, directory);
1110
2380
  const reset = () => {
1111
2381
  auth.reset();
1112
2382
  failures.clear();
2383
+ webhooks.reset();
2384
+ directory.restore();
1113
2385
  };
1114
- ready({ testkit, auth, seed, failures, reset });
2386
+ ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
1115
2387
  return {
1116
2388
  url,
1117
2389
  issuer: testkit.issuer,
@@ -1120,15 +2392,18 @@ async function startKindeTestkit(options = {}) {
1120
2392
  testkit,
1121
2393
  seed,
1122
2394
  failures,
2395
+ webhooks,
2396
+ directory,
2397
+ certificatePath: certificate?.certPath ?? null,
1123
2398
  reset,
1124
- close: () => new Promise((resolve, reject) => {
2399
+ close: () => new Promise((resolve2, reject) => {
1125
2400
  server.closeAllConnections();
1126
- server.close((error) => error ? reject(error) : resolve());
2401
+ server.close((error) => error ? reject(error) : resolve2());
1127
2402
  })
1128
2403
  };
1129
2404
  }
1130
2405
  async function handle(req, res, context) {
1131
- const { testkit, auth, seed, failures } = context;
2406
+ const { testkit, auth, seed, failures, webhooks } = context;
1132
2407
  const url = new URL(req.url ?? "/", "http://localhost");
1133
2408
  const { pathname } = url;
1134
2409
  const method = req.method ?? "GET";
@@ -1136,53 +2411,77 @@ async function handle(req, res, context) {
1136
2411
  const failure = failures.take(method, pathname);
1137
2412
  if (failure) {
1138
2413
  if (failure.hang) return;
1139
- if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
2414
+ if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
1140
2415
  if (failure.status !== null) {
1141
2416
  const headers = {};
1142
2417
  if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
1143
- return sendJson2(res, failure.status, failureBody(failure.status), headers);
2418
+ return sendJson4(res, failure.status, failureBody(failure.status), headers);
1144
2419
  }
1145
2420
  }
1146
2421
  }
1147
2422
  if (await auth.handle(req, res, url, () => readForm(req))) return;
2423
+ if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
2424
+ if (await context.account.handle(req, res, url)) return;
2425
+ if (method === "GET" && pathname === "/testkit/portal") {
2426
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2427
+ res.end(
2428
+ `<!doctype html><meta charset="utf-8"><title>Self-serve portal</title><body style="font:15px system-ui;padding:40px"><h1>Self-serve portal</h1><p>kinde-testkit does not emulate Kinde's self-serve portal. Your app linked here for <code>${escapeHtml(url.searchParams.get("subnav") ?? "profile")}</code>.</p>`
2429
+ );
2430
+ return;
2431
+ }
1148
2432
  if (method === "GET" && pathname === "/.well-known/openid-configuration") {
1149
- return sendJson2(res, 200, discovery(testkit));
2433
+ return sendJson4(res, 200, discovery(testkit));
1150
2434
  }
1151
2435
  if (method === "GET" && JWKS_PATHS.has(pathname)) {
1152
- return sendJson2(res, 200, testkit.jwks());
2436
+ return sendJson4(res, 200, testkit.jwks());
1153
2437
  }
1154
2438
  if (method === "GET" && pathname === "/testkit/health") {
1155
- return sendJson2(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
2439
+ return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
1156
2440
  }
1157
- if (method === "GET" && pathname === "/testkit/users") return sendJson2(res, 200, seed.users);
2441
+ if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
1158
2442
  if (method === "GET" && pathname === "/testkit/organizations") {
1159
- return sendJson2(res, 200, seed.organizations);
2443
+ return sendJson4(res, 200, seed.organizations);
1160
2444
  }
1161
2445
  if (method === "GET" && pathname === "/testkit/memberships") {
1162
- return sendJson2(res, 200, seed.memberships);
2446
+ return sendJson4(res, 200, seed.memberships);
1163
2447
  }
1164
- if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
2448
+ if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
1165
2449
  if (method === "POST" && pathname === "/testkit/failures") {
1166
- return sendJson2(res, 201, failures.add(await readJson(req)));
2450
+ return sendJson4(res, 201, failures.add(await readJson(req)));
1167
2451
  }
1168
2452
  if (method === "DELETE" && pathname === "/testkit/failures") {
1169
2453
  failures.clear();
1170
- return sendJson2(res, 200, { ok: true });
2454
+ return sendJson4(res, 200, { ok: true });
1171
2455
  }
1172
2456
  if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
1173
2457
  const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1174
- return sendJson2(res, removed ? 200 : 404, { ok: removed });
2458
+ return sendJson4(res, removed ? 200 : 404, { ok: removed });
2459
+ }
2460
+ if (method === "POST" && pathname === "/testkit/webhooks") {
2461
+ return sendJson4(res, 200, await webhooks.send(await readJson(req)));
2462
+ }
2463
+ if (method === "GET" && pathname === "/testkit/webhooks/types") {
2464
+ return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
2465
+ }
2466
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
2467
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
2468
+ if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
2469
+ return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
2470
+ }
2471
+ if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
2472
+ const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
2473
+ return sendJson4(res, removed ? 200 : 404, { ok: removed });
1175
2474
  }
1176
2475
  if (method === "POST" && pathname === "/testkit/reset") {
1177
2476
  context.reset();
1178
- return sendJson2(res, 200, { ok: true });
2477
+ return sendJson4(res, 200, { ok: true });
1179
2478
  }
1180
2479
  if (method === "POST" && pathname === "/testkit/token") {
1181
2480
  const body = await readJson(req);
1182
2481
  const accessToken = await issueToken(testkit, seed, body);
1183
- return sendJson2(res, 200, { access_token: accessToken, token_type: "Bearer" });
2482
+ return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
1184
2483
  }
1185
- return sendJson2(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
2484
+ return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
1186
2485
  }
1187
2486
  function discovery(testkit) {
1188
2487
  const base = testkit.issuer;
@@ -1241,7 +2540,11 @@ async function issueToken(testkit, seed, body) {
1241
2540
  });
1242
2541
  if (permissions) scenario.permissions = permissions;
1243
2542
  if (roles) scenario.roles = roles;
1244
- return await testkit.tokenFor(scenario, { expiresIn, invalid: invalid2 });
2543
+ return await testkit.tokenFor(scenario, {
2544
+ expiresIn,
2545
+ invalid: invalid2,
2546
+ featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
2547
+ });
1245
2548
  }
1246
2549
  const options = {
1247
2550
  subject: optionalString(input, "subject"),
@@ -1306,7 +2609,7 @@ async function readText(req) {
1306
2609
  }
1307
2610
  return Buffer.concat(chunks).toString("utf8").trim();
1308
2611
  }
1309
- function sendJson2(res, status, body, headers = {}) {
2612
+ function sendJson4(res, status, body, headers = {}) {
1310
2613
  res.writeHead(status, {
1311
2614
  "content-type": "application/json; charset=utf-8",
1312
2615
  "cache-control": "no-store",
@@ -1320,10 +2623,10 @@ function sendError(res, error) {
1320
2623
  return;
1321
2624
  }
1322
2625
  if (error instanceof TestkitError) {
1323
- sendJson2(res, 400, { error: error.code, error_description: error.message, details: error.details });
2626
+ sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
1324
2627
  return;
1325
2628
  }
1326
- sendJson2(res, 500, {
2629
+ sendJson4(res, 500, {
1327
2630
  error: "server_error",
1328
2631
  error_description: error instanceof Error ? error.message : String(error)
1329
2632
  });
@@ -1370,6 +2673,9 @@ function useKindeTestkit(options = {}) {
1370
2673
  get failures() {
1371
2674
  return current().failures;
1372
2675
  },
2676
+ get webhooks() {
2677
+ return current().webhooks;
2678
+ },
1373
2679
  auth: (scenario, token) => kindeTest({ scenario, testkit: current().testkit, token }),
1374
2680
  reset: () => current().reset()
1375
2681
  };