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/index.cjs CHANGED
@@ -20,20 +20,26 @@ 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,
26
27
  DEFAULT_M2M_CLIENT_ID: () => DEFAULT_M2M_CLIENT_ID,
27
28
  DEFAULT_SCOPES: () => DEFAULT_SCOPES,
29
+ Directory: () => Directory,
28
30
  FailureInjector: () => FailureInjector,
29
31
  INVALID_TOKEN_KINDS: () => INVALID_TOKEN_KINDS,
30
32
  KindeTestkit: () => KindeTestkit,
31
33
  ScenarioBuilder: () => ScenarioBuilder,
32
34
  TestkitError: () => TestkitError,
35
+ WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
36
+ WebhookDispatcher: () => WebhookDispatcher,
33
37
  createKindeOrganization: () => createKindeOrganization,
34
38
  createKindeToken: () => createKindeToken,
35
39
  createKindeUser: () => createKindeUser,
40
+ createLocalCertificate: () => createLocalCertificate,
36
41
  createMembership: () => createMembership,
42
+ ensureLocalCertificate: () => ensureLocalCertificate,
37
43
  getDefaultTestkit: () => getDefaultTestkit,
38
44
  inspectToken: () => inspectToken,
39
45
  isAuthenticated: () => isAuthenticated,
@@ -368,6 +374,9 @@ var KindeTestkit = class _KindeTestkit {
368
374
  if (scenario2.kind === "unauthenticated") return null;
369
375
  return scenarioPrincipal(scenario2, this.issuer);
370
376
  }
377
+ async signPayload(payload, invalid2) {
378
+ return this.sign(payload, invalid2);
379
+ }
371
380
  async sign(payload, invalid2) {
372
381
  if (invalid2 === "unsigned") {
373
382
  const header = import_jose.base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
@@ -481,8 +490,230 @@ async function createKindeToken(options = {}) {
481
490
 
482
491
  // src/server.ts
483
492
  var import_node_http = require("http");
493
+ var import_node_https = require("https");
494
+
495
+ // src/certificate.ts
496
+ var import_node_crypto3 = require("crypto");
497
+ var import_node_fs = require("fs");
498
+ var import_node_path = require("path");
499
+ var CERT_FILE = "localhost-cert.pem";
500
+ var KEY_FILE = "localhost-key.pem";
501
+ var VALID_DAYS = 825;
502
+ function ensureLocalCertificate(directory = ".kinde-testkit") {
503
+ const dir = (0, import_node_path.resolve)(directory);
504
+ const certPath = (0, import_node_path.join)(dir, CERT_FILE);
505
+ const keyPath = (0, import_node_path.join)(dir, KEY_FILE);
506
+ if ((0, import_node_fs.existsSync)(certPath) && (0, import_node_fs.existsSync)(keyPath)) {
507
+ const cert2 = (0, import_node_fs.readFileSync)(certPath, "utf8");
508
+ const key2 = (0, import_node_fs.readFileSync)(keyPath, "utf8");
509
+ try {
510
+ if (new Date(new import_node_crypto3.X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
511
+ return { cert: cert2, key: key2, certPath, keyPath, created: false };
512
+ }
513
+ } catch {
514
+ }
515
+ }
516
+ const { cert, key } = createLocalCertificate();
517
+ (0, import_node_fs.mkdirSync)(dir, { recursive: true });
518
+ (0, import_node_fs.writeFileSync)(certPath, cert);
519
+ (0, import_node_fs.writeFileSync)(keyPath, key, { mode: 384 });
520
+ (0, import_node_fs.writeFileSync)((0, import_node_path.join)(dir, ".gitignore"), "*\n");
521
+ return { cert, key, certPath, keyPath, created: true };
522
+ }
523
+ function createLocalCertificate() {
524
+ const { publicKey, privateKey } = (0, import_node_crypto3.generateKeyPairSync)("rsa", { modulusLength: 2048 });
525
+ const spki = publicKey.export({ type: "spki", format: "der" });
526
+ const keyId = (0, import_node_crypto3.createHash)("sha1").update(subjectPublicKeyBits(spki)).digest();
527
+ const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
528
+ const now = Date.now();
529
+ const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
530
+ const serial = (0, import_node_crypto3.randomBytes)(16);
531
+ serial[0] &= 127;
532
+ const extensions = seq(
533
+ seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
534
+ seq(oid("2.5.29.14"), octets(octets(keyId))),
535
+ seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
536
+ seq(
537
+ oid("2.5.29.17"),
538
+ octets(
539
+ seq(
540
+ tlv(130, Buffer.from("localhost")),
541
+ tlv(135, Buffer.from([127, 0, 0, 1])),
542
+ tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
543
+ )
544
+ )
545
+ )
546
+ );
547
+ const tbs = seq(
548
+ tlv(160, integer(Buffer.from([2]))),
549
+ integer(serial),
550
+ algorithm,
551
+ name,
552
+ seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
553
+ name,
554
+ spki,
555
+ tlv(163, extensions)
556
+ );
557
+ const signature = (0, import_node_crypto3.sign)("sha256", tbs, privateKey);
558
+ const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
559
+ return {
560
+ cert: pem("CERTIFICATE", der),
561
+ key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
562
+ };
563
+ }
564
+ function subjectPublicKeyBits(spki) {
565
+ const outer = readTlv(spki, 0);
566
+ const algorithm = readTlv(spki, outer.start);
567
+ const bits = readTlv(spki, algorithm.end);
568
+ return spki.subarray(bits.start + 1, bits.end);
569
+ }
570
+ function readTlv(buf, offset) {
571
+ let len = buf[offset + 1];
572
+ let header = 2;
573
+ if (len & 128) {
574
+ const n = len & 127;
575
+ len = 0;
576
+ for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
577
+ header += n;
578
+ }
579
+ return { start: offset + header, end: offset + header + len };
580
+ }
581
+ function tlv(tag, content) {
582
+ return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
583
+ }
584
+ function length(n) {
585
+ if (n < 128) return Buffer.from([n]);
586
+ const bytes = [];
587
+ while (n > 0) {
588
+ bytes.unshift(n & 255);
589
+ n >>= 8;
590
+ }
591
+ return Buffer.from([128 | bytes.length, ...bytes]);
592
+ }
593
+ function seq(...items) {
594
+ return tlv(48, Buffer.concat(items));
595
+ }
596
+ function set(...items) {
597
+ return tlv(49, Buffer.concat(items));
598
+ }
599
+ function octets(content) {
600
+ return tlv(4, content);
601
+ }
602
+ function integer(bytes) {
603
+ return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
604
+ }
605
+ function oid(dotted) {
606
+ const parts = dotted.split(".").map(Number);
607
+ const bytes = [parts[0] * 40 + parts[1]];
608
+ for (const part of parts.slice(2)) {
609
+ const chunk = [part & 127];
610
+ let value = part >> 7;
611
+ while (value > 0) {
612
+ chunk.unshift(value & 127 | 128);
613
+ value >>= 7;
614
+ }
615
+ bytes.push(...chunk);
616
+ }
617
+ return tlv(6, Buffer.from(bytes));
618
+ }
619
+ function utcTime(date) {
620
+ const iso = date.toISOString();
621
+ 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`;
622
+ return tlv(23, Buffer.from(value));
623
+ }
624
+ function pem(label, der) {
625
+ const body = der.toString("base64").match(/.{1,64}/g).join("\n");
626
+ return `-----BEGIN ${label}-----
627
+ ${body}
628
+ -----END ${label}-----
629
+ `;
630
+ }
631
+
632
+ // src/login-page.ts
633
+ var STYLE = `
634
+ :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}
635
+ @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}}
636
+ *{box-sizing:border-box}
637
+ 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}
638
+ main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
639
+ .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
640
+ h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
641
+ p{margin:0;color:var(--muted)}
642
+ .note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
643
+ form{margin:0}
644
+ label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
645
+ 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}
646
+ input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
647
+ .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}
648
+ h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
649
+ .list{display:grid;gap:8px}
650
+ .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}
651
+ .option:hover{border-color:var(--muted)}
652
+ .option strong{display:block;font-weight:500}
653
+ .option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
654
+ .tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
655
+ .error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
656
+ `;
657
+ function escapeHtml(value) {
658
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
659
+ }
660
+ function layout(title, body) {
661
+ 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>`;
662
+ }
663
+ function displayName(user) {
664
+ return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
665
+ }
666
+ function renderSignIn(options) {
667
+ const users = options.users.map(({ user, organizations }) => {
668
+ const value = escapeHtml(user.email ?? user.id);
669
+ const hasName = Boolean(user.givenName || user.familyName);
670
+ const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
671
+ const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
672
+ 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>`;
673
+ }).join("");
674
+ const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
675
+ return layout(
676
+ "Sign in",
677
+ `<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>`
678
+ );
679
+ }
680
+ function renderOrganizationPicker(options) {
681
+ const choices = options.organizations.map(
682
+ (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>`
683
+ ).join("");
684
+ return layout(
685
+ "Choose an organization",
686
+ `<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>`
687
+ );
688
+ }
689
+ function renderMessage(title, message) {
690
+ return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
691
+ }
484
692
 
485
693
  // src/seed.ts
694
+ function roleRecord(key, extra = {}) {
695
+ return {
696
+ id: stableId("role", key),
697
+ key,
698
+ name: extra.name ?? titleCase(key),
699
+ description: extra.description ?? null,
700
+ isDefault: extra.isDefault ?? false,
701
+ permissions: [...extra.permissions ?? []]
702
+ };
703
+ }
704
+ function permissionRecord(key, extra = {}) {
705
+ return {
706
+ id: stableId("perm", key),
707
+ key,
708
+ name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
709
+ description: extra.description ?? null
710
+ };
711
+ }
712
+ function effectivePermissions(seed, membership) {
713
+ if (!membership) return [];
714
+ const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
715
+ return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
716
+ }
486
717
  function resolveSeed(input) {
487
718
  const problems = [];
488
719
  if (!isRecord(input)) {
@@ -492,6 +723,23 @@ function resolveSeed(input) {
492
723
  const rawOrganizations = listOf(input.organizations, "organizations", problems);
493
724
  const rawMemberships = listOf(input.memberships, "memberships", problems);
494
725
  const rawApplications = listOf(input.applications, "applications", problems);
726
+ const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
727
+ const rawRoles = listOf(input.roles, "roles", problems);
728
+ const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
729
+ const rawPlans = listOf(input.plans, "plans", problems);
730
+ const rawPermissions = listOf(input.permissions, "permissions", problems);
731
+ const webhooks = [];
732
+ rawWebhooks.forEach((raw, index) => {
733
+ if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
734
+ problems.push(`webhooks[${index}] needs an http or https "url".`);
735
+ return;
736
+ }
737
+ if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
738
+ problems.push(`webhooks[${index}].events must be a list of event type names.`);
739
+ return;
740
+ }
741
+ webhooks.push({ url: raw.url, events: raw.events });
742
+ });
495
743
  const users = [];
496
744
  rawUsers.forEach((raw, index) => {
497
745
  if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
@@ -583,7 +831,107 @@ function resolveSeed(input) {
583
831
  if (problems.length > 0) {
584
832
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
585
833
  }
586
- return { users, organizations, memberships, applications };
834
+ const permissions = [];
835
+ rawPermissions.forEach((raw, index) => {
836
+ if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
837
+ problems.push(`permissions[${index}] needs a string "key".`);
838
+ return;
839
+ }
840
+ if (permissions.some((p) => p.key === raw.key)) {
841
+ problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
842
+ return;
843
+ }
844
+ permissions.push(
845
+ permissionRecord(raw.key, {
846
+ name: typeof raw.name === "string" ? raw.name : void 0,
847
+ description: typeof raw.description === "string" ? raw.description : void 0
848
+ })
849
+ );
850
+ });
851
+ const roles = [];
852
+ rawRoles.forEach((raw, index) => {
853
+ if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
854
+ problems.push(`roles[${index}] needs a string "key".`);
855
+ return;
856
+ }
857
+ if (roles.some((r) => r.key === raw.key)) {
858
+ problems.push(`roles[${index}] repeats the key "${raw.key}".`);
859
+ return;
860
+ }
861
+ if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
862
+ problems.push(`roles[${index}].permissions must be a list of permission keys.`);
863
+ return;
864
+ }
865
+ roles.push(
866
+ roleRecord(raw.key, {
867
+ name: typeof raw.name === "string" ? raw.name : void 0,
868
+ description: typeof raw.description === "string" ? raw.description : void 0,
869
+ isDefault: raw.isDefault === true,
870
+ permissions: raw.permissions ?? []
871
+ })
872
+ );
873
+ });
874
+ if (problems.length > 0) {
875
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
876
+ }
877
+ const featureFlags = [];
878
+ rawFlags.forEach((raw, index) => {
879
+ if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
880
+ problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
881
+ return;
882
+ }
883
+ const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
884
+ featureFlags.push({
885
+ id: stableId("flag", raw.key),
886
+ key: raw.key,
887
+ name: typeof raw.name === "string" ? raw.name : raw.key,
888
+ type,
889
+ value: raw.value,
890
+ organizations: isRecord(raw.organizations) ? raw.organizations : {}
891
+ });
892
+ });
893
+ const plans = [];
894
+ rawPlans.forEach((raw, index) => {
895
+ if (!isRecord(raw) || typeof raw.key !== "string") {
896
+ problems.push(`plans[${index}] needs a string "key".`);
897
+ return;
898
+ }
899
+ const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
900
+ plans.push({
901
+ key: raw.key,
902
+ name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
903
+ subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
904
+ subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
905
+ entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
906
+ id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
907
+ featureKey: e.featureKey,
908
+ featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
909
+ priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
910
+ fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
911
+ unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
912
+ limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
913
+ limitMin: typeof e.limitMin === "number" ? e.limitMin : null
914
+ }))
915
+ });
916
+ });
917
+ const userProperties = {};
918
+ rawUsers.forEach((raw) => {
919
+ if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
920
+ userProperties[raw.id] = raw.properties;
921
+ }
922
+ });
923
+ if (problems.length > 0) {
924
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
925
+ }
926
+ const usedRoles = new Set(memberships.flatMap((m) => m.roles));
927
+ for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
928
+ const usedPermissions = /* @__PURE__ */ new Set([
929
+ ...memberships.flatMap((m) => m.permissions),
930
+ ...roles.flatMap((r) => r.permissions),
931
+ ...applications.flatMap((a) => a.permissions ?? [])
932
+ ]);
933
+ for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
934
+ return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
587
935
  }
588
936
  function findUser(users, ref) {
589
937
  const needle = ref.toLowerCase();
@@ -628,7 +976,7 @@ function seedScenario(seed, ref) {
628
976
  user,
629
977
  organization,
630
978
  roles: [...membership?.roles ?? []],
631
- permissions: [...membership?.permissions ?? []],
979
+ permissions: effectivePermissions(seed, membership),
632
980
  claims: {}
633
981
  };
634
982
  }
@@ -643,72 +991,18 @@ function listOf(value, field, problems) {
643
991
  function isRecord(value) {
644
992
  return typeof value === "object" && value !== null && !Array.isArray(value);
645
993
  }
646
-
647
- // src/oauth.ts
648
- var import_node_crypto3 = require("crypto");
649
-
650
- // src/login-page.ts
651
- var STYLE = `
652
- :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}
653
- @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}}
654
- *{box-sizing:border-box}
655
- 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}
656
- main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
657
- .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
658
- h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
659
- p{margin:0;color:var(--muted)}
660
- .note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
661
- form{margin:0}
662
- label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
663
- 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}
664
- input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
665
- .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}
666
- h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
667
- .list{display:grid;gap:8px}
668
- .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}
669
- .option:hover{border-color:var(--muted)}
670
- .option strong{display:block;font-weight:500}
671
- .option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
672
- .tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
673
- .error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
674
- `;
675
- function escapeHtml(value) {
676
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
677
- }
678
- function layout(title, body) {
679
- 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>`;
680
- }
681
- function displayName(user) {
682
- return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
683
- }
684
- function renderSignIn(options) {
685
- const users = options.users.map(({ user, organizations }) => {
686
- const value = escapeHtml(user.email ?? user.id);
687
- const hasName = Boolean(user.givenName || user.familyName);
688
- const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
689
- const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
690
- 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>`;
691
- }).join("");
692
- const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
693
- return layout(
694
- "Sign in",
695
- `<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>`
696
- );
697
- }
698
- function renderOrganizationPicker(options) {
699
- const choices = options.organizations.map(
700
- (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>`
701
- ).join("");
702
- return layout(
703
- "Choose an organization",
704
- `<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>`
705
- );
706
- }
707
- function renderMessage(title, message) {
708
- return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
994
+ function featureFlagsFor(seed, organizationCode) {
995
+ if (seed.featureFlags.length === 0) return void 0;
996
+ const claim = {};
997
+ for (const flag of seed.featureFlags) {
998
+ const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
999
+ claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
1000
+ }
1001
+ return claim;
709
1002
  }
710
1003
 
711
1004
  // src/oauth.ts
1005
+ var import_node_crypto4 = require("crypto");
712
1006
  var CODE_LIFETIME_MS = 10 * 60 * 1e3;
713
1007
  var OAuthError = class extends Error {
714
1008
  constructor(status, error, description) {
@@ -720,12 +1014,16 @@ var OAuthError = class extends Error {
720
1014
  error;
721
1015
  };
722
1016
  var AuthorizationServer = class {
723
- constructor(testkit, seed) {
1017
+ constructor(testkit, seed, emit = () => void 0, directory) {
724
1018
  this.testkit = testkit;
725
1019
  this.seed = seed;
1020
+ this.emit = emit;
1021
+ this.directory = directory;
726
1022
  }
727
1023
  testkit;
728
1024
  seed;
1025
+ emit;
1026
+ directory;
729
1027
  codes = /* @__PURE__ */ new Map();
730
1028
  refreshTokens = /* @__PURE__ */ new Map();
731
1029
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -791,6 +1089,18 @@ var AuthorizationServer = class {
791
1089
  if (!user) {
792
1090
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
793
1091
  }
1092
+ if (this.directory?.isSuspended(user.id)) {
1093
+ return sendHtml(
1094
+ res,
1095
+ 403,
1096
+ renderSignIn({
1097
+ request: encoded,
1098
+ users: this.loginPageUsers(),
1099
+ requiredOrganization: request.orgCode ?? void 0,
1100
+ error: `${user.email ?? user.id} is suspended and cannot sign in.`
1101
+ })
1102
+ );
1103
+ }
794
1104
  const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
795
1105
  const wanted = request.orgCode ?? form.org ?? null;
796
1106
  let organizationCode = null;
@@ -827,7 +1137,7 @@ var AuthorizationServer = class {
827
1137
  user,
828
1138
  organization: organizationCode ? this.organization(organizationCode) : null,
829
1139
  roles: [...membership?.roles ?? []],
830
- permissions: [...membership?.permissions ?? []],
1140
+ permissions: effectivePermissions(this.seed, membership),
831
1141
  claims: {}
832
1142
  };
833
1143
  const code = randomToken();
@@ -843,6 +1153,8 @@ var AuthorizationServer = class {
843
1153
  codeChallengeMethod: request.codeChallengeMethod,
844
1154
  expiresAt: Date.now() + CODE_LIFETIME_MS
845
1155
  });
1156
+ this.directory?.recordSignIn(user, organizationCode);
1157
+ this.emit("user.authenticated", user);
846
1158
  const target = new URL(request.redirectUri);
847
1159
  target.searchParams.set("code", code);
848
1160
  if (request.state !== null) target.searchParams.set("state", request.state);
@@ -877,7 +1189,7 @@ var AuthorizationServer = class {
877
1189
  throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
878
1190
  }
879
1191
  const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
880
- const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
1192
+ const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
881
1193
  const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
882
1194
  return {
883
1195
  access_token: await this.testkit.m2mToken({
@@ -913,7 +1225,7 @@ var AuthorizationServer = class {
913
1225
  }
914
1226
  if (pending.codeChallenge) {
915
1227
  const verifier = form.code_verifier ?? "";
916
- const expected = pending.codeChallengeMethod === "plain" ? verifier : (0, import_node_crypto3.createHash)("sha256").update(verifier).digest("base64url");
1228
+ const expected = pending.codeChallengeMethod === "plain" ? verifier : (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
917
1229
  if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
918
1230
  throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
919
1231
  }
@@ -943,7 +1255,8 @@ var AuthorizationServer = class {
943
1255
  scopes: grant.scope,
944
1256
  clientId: grant.clientId,
945
1257
  audience: grant.audience.length > 0 ? grant.audience : void 0,
946
- authTime: grant.authTime
1258
+ authTime: grant.authTime,
1259
+ featureFlags: featureFlagsFor(this.seed, scenario2.organization?.code ?? null)
947
1260
  }),
948
1261
  expires_in: this.testkit.accessTokenLifetime,
949
1262
  scope: grant.scope.join(" "),
@@ -1008,8 +1321,12 @@ var AuthorizationServer = class {
1008
1321
  if (seeded) return seeded;
1009
1322
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
1010
1323
  const user = createKindeUser({ email: ref.toLowerCase() });
1011
- this.signedUpUsers.set(user.id, user);
1012
- return user;
1324
+ if (!this.signedUpUsers.has(user.id)) {
1325
+ this.signedUpUsers.set(user.id, user);
1326
+ if (this.directory) this.seed.users.push(user);
1327
+ this.emit("user.created", user);
1328
+ }
1329
+ return this.signedUpUsers.get(user.id);
1013
1330
  }
1014
1331
  organization(code) {
1015
1332
  return this.seed.organizations.find((org) => org.code === code) ?? null;
@@ -1094,12 +1411,12 @@ function isHttpUrl(value) {
1094
1411
  }
1095
1412
  }
1096
1413
  function randomToken() {
1097
- return (0, import_node_crypto3.randomBytes)(32).toString("base64url");
1414
+ return (0, import_node_crypto4.randomBytes)(32).toString("base64url");
1098
1415
  }
1099
1416
  function safeEqual(a, b) {
1100
1417
  const left = Buffer.from(a);
1101
1418
  const right = Buffer.from(b);
1102
- return left.length === right.length && (0, import_node_crypto3.timingSafeEqual)(left, right);
1419
+ return left.length === right.length && (0, import_node_crypto4.timingSafeEqual)(left, right);
1103
1420
  }
1104
1421
  function redirect(res, location) {
1105
1422
  res.writeHead(303, { location, "cache-control": "no-store" });
@@ -1118,6 +1435,687 @@ function sendJson(res, status, body) {
1118
1435
  res.end(JSON.stringify(body));
1119
1436
  }
1120
1437
 
1438
+ // src/account.ts
1439
+ var DEFAULT_PAGE_SIZE = 10;
1440
+ var AccountApi = class {
1441
+ constructor(testkit, directory) {
1442
+ this.testkit = testkit;
1443
+ this.directory = directory;
1444
+ }
1445
+ testkit;
1446
+ directory;
1447
+ async handle(req, res, url) {
1448
+ if (!url.pathname.startsWith("/account_api/v1/")) return false;
1449
+ if ((req.method ?? "GET") !== "GET") {
1450
+ sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
1451
+ return true;
1452
+ }
1453
+ const header = req.headers.authorization ?? "";
1454
+ let token;
1455
+ try {
1456
+ if (!header.startsWith("Bearer ")) throw new Error("missing");
1457
+ token = await this.testkit.verify(header.slice(7));
1458
+ } catch {
1459
+ sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
1460
+ return true;
1461
+ }
1462
+ if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
1463
+ sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
1464
+ return true;
1465
+ }
1466
+ const userId = token.sub;
1467
+ const orgCode = typeof token.org_code === "string" ? token.org_code : null;
1468
+ const path = url.pathname.slice("/account_api/v1/".length);
1469
+ const d = this.directory;
1470
+ const membership = orgCode ? d.membership(userId, orgCode) : void 0;
1471
+ if (path === "permissions") {
1472
+ const items = effectivePermissions(d.seed, membership).map((key) => {
1473
+ const p = d.ensurePermission(key);
1474
+ return { id: p.id, name: p.name, key: p.key };
1475
+ });
1476
+ sendPage(res, url, "permissions", items, { org_code: orgCode });
1477
+ return true;
1478
+ }
1479
+ if (path.startsWith("permission/")) {
1480
+ const key = decodeURIComponent(path.slice("permission/".length));
1481
+ sendJson2(res, 200, {
1482
+ data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
1483
+ });
1484
+ return true;
1485
+ }
1486
+ if (path === "roles") {
1487
+ const items = (membership?.roles ?? []).map((key) => {
1488
+ const r = d.ensureRole(key);
1489
+ return { id: r.id, name: r.name, key: r.key };
1490
+ });
1491
+ sendPage(res, url, "roles", items, { org_code: orgCode });
1492
+ return true;
1493
+ }
1494
+ if (path === "feature_flags") {
1495
+ const items = d.seed.featureFlags.map((flag) => ({
1496
+ id: flag.id,
1497
+ name: flag.name,
1498
+ key: flag.key,
1499
+ type: flag.type,
1500
+ value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
1501
+ }));
1502
+ sendPage(res, url, "feature_flags", items, {});
1503
+ return true;
1504
+ }
1505
+ if (path === "properties") {
1506
+ const values = d.seed.userProperties[userId] ?? {};
1507
+ const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
1508
+ sendPage(res, url, "properties", items, {});
1509
+ return true;
1510
+ }
1511
+ if (path === "entitlements" || path.startsWith("entitlement")) {
1512
+ const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
1513
+ const entitlements = (plan?.entitlements ?? []).map((e) => ({
1514
+ id: e.id,
1515
+ fixed_charge: e.fixedCharge,
1516
+ price_name: e.priceName,
1517
+ unit_amount: e.unitAmount,
1518
+ feature_key: e.featureKey,
1519
+ feature_name: e.featureName,
1520
+ entitlement_limit_max: e.limitMax,
1521
+ entitlement_limit_min: e.limitMin
1522
+ }));
1523
+ if (path === "entitlements") {
1524
+ const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
1525
+ sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
1526
+ return true;
1527
+ }
1528
+ const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
1529
+ const entitlement = entitlements.find((e) => e.feature_key === key);
1530
+ if (!entitlement) {
1531
+ sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
1532
+ } else {
1533
+ sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
1534
+ }
1535
+ return true;
1536
+ }
1537
+ if (path === "portal_link") {
1538
+ sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
1539
+ return true;
1540
+ }
1541
+ sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
1542
+ return true;
1543
+ }
1544
+ };
1545
+ function sendPage(res, url, field, items, extra) {
1546
+ const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
1547
+ const after = url.searchParams.get("starting_after");
1548
+ const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
1549
+ const page = items.slice(start, start + size);
1550
+ const hasMore = start + size < items.length;
1551
+ sendJson2(res, 200, {
1552
+ data: { ...extra, [field]: page },
1553
+ metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
1554
+ });
1555
+ }
1556
+ function errors(code, message) {
1557
+ return { errors: [{ code, message }] };
1558
+ }
1559
+ function sendJson2(res, status, body) {
1560
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1561
+ res.end(JSON.stringify(body));
1562
+ }
1563
+
1564
+ // src/directory.ts
1565
+ var import_node_crypto5 = require("crypto");
1566
+ var Directory = class {
1567
+ constructor(seed) {
1568
+ this.seed = seed;
1569
+ this.snapshot = JSON.stringify(seed);
1570
+ }
1571
+ seed;
1572
+ userMeta = /* @__PURE__ */ new Map();
1573
+ orgMeta = /* @__PURE__ */ new Map();
1574
+ snapshot;
1575
+ restore() {
1576
+ const original = JSON.parse(this.snapshot);
1577
+ for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
1578
+ this.seed[key].splice(0, this.seed[key].length, ...original[key]);
1579
+ }
1580
+ this.userMeta.clear();
1581
+ this.orgMeta.clear();
1582
+ }
1583
+ user(id) {
1584
+ return this.seed.users.find((user) => user.id === id);
1585
+ }
1586
+ meta(user) {
1587
+ let meta = this.userMeta.get(user.id);
1588
+ if (!meta) {
1589
+ meta = {
1590
+ providedId: null,
1591
+ isSuspended: false,
1592
+ isPasswordResetRequested: false,
1593
+ createdOn: (/* @__PURE__ */ new Date()).toISOString(),
1594
+ totalSignIns: 0,
1595
+ lastSignedIn: null
1596
+ };
1597
+ this.userMeta.set(user.id, meta);
1598
+ }
1599
+ return meta;
1600
+ }
1601
+ isSuspended(userId) {
1602
+ return this.userMeta.get(userId)?.isSuspended ?? false;
1603
+ }
1604
+ recordSignIn(user, organizationCode) {
1605
+ const meta = this.meta(user);
1606
+ meta.totalSignIns += 1;
1607
+ meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
1608
+ void organizationCode;
1609
+ }
1610
+ createUser(input) {
1611
+ const user = createKindeUser({
1612
+ id: `kp_${(0, import_node_crypto5.randomBytes)(16).toString("hex")}`,
1613
+ email: input.email ?? null,
1614
+ givenName: input.givenName ?? null,
1615
+ familyName: input.familyName ?? null,
1616
+ picture: input.picture ?? null
1617
+ });
1618
+ this.seed.users.push(user);
1619
+ this.meta(user).providedId = input.providedId ?? null;
1620
+ return user;
1621
+ }
1622
+ deleteUser(id) {
1623
+ const index = this.seed.users.findIndex((user) => user.id === id);
1624
+ if (index < 0) return false;
1625
+ this.seed.users.splice(index, 1);
1626
+ for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
1627
+ if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
1628
+ }
1629
+ this.userMeta.delete(id);
1630
+ return true;
1631
+ }
1632
+ organization(code) {
1633
+ return this.seed.organizations.find((org) => org.code === code);
1634
+ }
1635
+ orgInfo(org) {
1636
+ let meta = this.orgMeta.get(org.code);
1637
+ if (!meta) {
1638
+ meta = {
1639
+ externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
1640
+ handle: slug(org.name),
1641
+ createdOn: (/* @__PURE__ */ new Date()).toISOString(),
1642
+ isAllowRegistrations: false
1643
+ };
1644
+ this.orgMeta.set(org.code, meta);
1645
+ }
1646
+ return meta;
1647
+ }
1648
+ createOrganization(input) {
1649
+ const org = createKindeOrganization({ code: `org_${(0, import_node_crypto5.randomBytes)(6).toString("hex").slice(0, 11)}`, name: input.name });
1650
+ this.seed.organizations.push(org);
1651
+ const meta = this.orgInfo(org);
1652
+ meta.externalId = input.externalId ?? null;
1653
+ if (input.handle) meta.handle = input.handle;
1654
+ return org;
1655
+ }
1656
+ deleteOrganization(code) {
1657
+ const index = this.seed.organizations.findIndex((org) => org.code === code);
1658
+ if (index < 0) return false;
1659
+ this.seed.organizations.splice(index, 1);
1660
+ for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
1661
+ if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
1662
+ }
1663
+ this.orgMeta.delete(code);
1664
+ return true;
1665
+ }
1666
+ membership(userId, organizationCode) {
1667
+ return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
1668
+ }
1669
+ addMembership(userId, organizationCode, roles = [], permissions = []) {
1670
+ const existing = this.membership(userId, organizationCode);
1671
+ if (existing) return existing;
1672
+ const membership = createMembership({ userId, organizationCode, roles, permissions });
1673
+ this.seed.memberships.push(membership);
1674
+ for (const key of roles) this.ensureRole(key);
1675
+ for (const key of permissions) this.ensurePermission(key);
1676
+ return membership;
1677
+ }
1678
+ removeMembership(userId, organizationCode) {
1679
+ const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
1680
+ if (index < 0) return false;
1681
+ this.seed.memberships.splice(index, 1);
1682
+ return true;
1683
+ }
1684
+ role(idOrKey) {
1685
+ return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
1686
+ }
1687
+ permission(idOrKey) {
1688
+ return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
1689
+ }
1690
+ ensureRole(key, extra = {}) {
1691
+ const existing = this.role(key);
1692
+ if (existing) return existing;
1693
+ const role = roleRecord(key, extra);
1694
+ this.seed.roles.push(role);
1695
+ return role;
1696
+ }
1697
+ ensurePermission(key, extra = {}) {
1698
+ const existing = this.permission(key);
1699
+ if (existing) return existing;
1700
+ const permission = permissionRecord(key, extra);
1701
+ this.seed.permissions.push(permission);
1702
+ return permission;
1703
+ }
1704
+ deleteRole(id) {
1705
+ const role = this.role(id);
1706
+ if (!role) return void 0;
1707
+ this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
1708
+ for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
1709
+ return role;
1710
+ }
1711
+ deletePermission(id) {
1712
+ const permission = this.permission(id);
1713
+ if (!permission) return void 0;
1714
+ this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
1715
+ for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
1716
+ for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
1717
+ return permission;
1718
+ }
1719
+ };
1720
+
1721
+ // src/management.ts
1722
+ var OK = { code: "OK", message: "Success" };
1723
+ var DEFAULT_PAGE_SIZE2 = 10;
1724
+ var MAX_PAGE_SIZE = 500;
1725
+ var ManagementApi = class {
1726
+ constructor(testkit, directory, webhooks) {
1727
+ this.testkit = testkit;
1728
+ this.directory = directory;
1729
+ this.webhooks = webhooks;
1730
+ this.register();
1731
+ }
1732
+ testkit;
1733
+ directory;
1734
+ webhooks;
1735
+ routes = [];
1736
+ async handle(req, res, url, readBody) {
1737
+ if (!url.pathname.startsWith("/api/v1/")) return false;
1738
+ const method = req.method ?? "GET";
1739
+ const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
1740
+ if (!route) {
1741
+ sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
1742
+ return true;
1743
+ }
1744
+ const token = await this.authenticate(req.headers.authorization);
1745
+ if ("error" in token) {
1746
+ sendJson3(res, 403, errors2(token.code, token.error));
1747
+ return true;
1748
+ }
1749
+ const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
1750
+ if (granted.length > 0 && !granted.includes(route.scope)) {
1751
+ sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
1752
+ return true;
1753
+ }
1754
+ const match = route.pattern.exec(url.pathname);
1755
+ const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
1756
+ const body = method === "GET" || method === "DELETE" ? {} : await readBody();
1757
+ const [status, payload] = await route.handler({ params, query: url.searchParams, body });
1758
+ sendJson3(res, status, payload);
1759
+ return true;
1760
+ }
1761
+ async authenticate(header) {
1762
+ if (!header?.startsWith("Bearer ")) {
1763
+ return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
1764
+ }
1765
+ let payload;
1766
+ try {
1767
+ payload = await this.testkit.verify(header.slice(7));
1768
+ } catch {
1769
+ return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
1770
+ }
1771
+ const audience = `${this.testkit.issuer}/api`;
1772
+ const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
1773
+ if (!aud.includes(audience)) {
1774
+ return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
1775
+ }
1776
+ if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
1777
+ return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
1778
+ }
1779
+ return { payload };
1780
+ }
1781
+ route(method, path, scope, handler) {
1782
+ const keys = [];
1783
+ const pattern = new RegExp(
1784
+ `^${path.replace(/\{(\w+)\}/g, (_, key) => {
1785
+ keys.push(key);
1786
+ return "([^/]+)";
1787
+ })}$`
1788
+ );
1789
+ this.routes.push({ method, pattern, keys, scope, handler });
1790
+ }
1791
+ register() {
1792
+ const d = this.directory;
1793
+ this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
1794
+ let users = [...d.seed.users];
1795
+ const userId = query.get("user_id");
1796
+ const email = query.get("email")?.toLowerCase();
1797
+ if (userId) users = users.filter((u) => u.id === userId);
1798
+ if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
1799
+ const page = paginate(users, query);
1800
+ return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
1801
+ });
1802
+ this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
1803
+ const user = d.user(query.get("id") ?? "");
1804
+ return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
1805
+ });
1806
+ this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
1807
+ const profile = body.profile ?? {};
1808
+ const identities = Array.isArray(body.identities) ? body.identities : [];
1809
+ const emailIdentity = identities.find((i) => i.type === "email");
1810
+ const email = (emailIdentity?.details ?? {}).email;
1811
+ if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
1812
+ return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
1813
+ }
1814
+ const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
1815
+ if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
1816
+ const user = d.createUser({
1817
+ email: typeof email === "string" ? email : null,
1818
+ givenName: str(profile.given_name),
1819
+ familyName: str(profile.family_name),
1820
+ picture: str(profile.picture),
1821
+ providedId: str(body.provided_id)
1822
+ });
1823
+ if (orgCode) d.addMembership(user.id, orgCode);
1824
+ this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
1825
+ return [
1826
+ 200,
1827
+ { id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
1828
+ ];
1829
+ });
1830
+ this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
1831
+ const user = d.user(query.get("id") ?? "");
1832
+ if (!user) return notFound("USER_INVALID", "No user has that id.");
1833
+ if (typeof body.given_name === "string") user.givenName = body.given_name;
1834
+ if (typeof body.family_name === "string") user.familyName = body.family_name;
1835
+ if (typeof body.picture === "string") user.picture = body.picture;
1836
+ const meta = d.meta(user);
1837
+ if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
1838
+ if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
1839
+ if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
1840
+ this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
1841
+ return [
1842
+ 200,
1843
+ {
1844
+ id: user.id,
1845
+ given_name: user.givenName,
1846
+ family_name: user.familyName,
1847
+ email: user.email,
1848
+ is_suspended: meta.isSuspended,
1849
+ is_password_reset_requested: meta.isPasswordResetRequested,
1850
+ picture: user.picture
1851
+ }
1852
+ ];
1853
+ });
1854
+ this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
1855
+ const id = query.get("id") ?? "";
1856
+ if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
1857
+ this.webhooks.emit("user.deleted", { user: { id } });
1858
+ return [200, OK];
1859
+ });
1860
+ this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
1861
+ const page = paginate(d.seed.organizations, query);
1862
+ return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
1863
+ });
1864
+ this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
1865
+ const org = d.organization(query.get("code") ?? "");
1866
+ if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1867
+ const meta = d.orgInfo(org);
1868
+ return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
1869
+ });
1870
+ this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
1871
+ if (typeof body.name !== "string" || body.name.trim() === "") {
1872
+ return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
1873
+ }
1874
+ const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
1875
+ if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
1876
+ this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
1877
+ return [200, { ...OK, organization: { code: org.code } }];
1878
+ });
1879
+ this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
1880
+ const org = d.organization(params.org_code);
1881
+ if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1882
+ const meta = d.orgInfo(org);
1883
+ if (typeof body.name === "string") org.name = body.name;
1884
+ if (typeof body.external_id === "string") meta.externalId = body.external_id;
1885
+ if (typeof body.handle === "string") meta.handle = body.handle;
1886
+ if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
1887
+ this.webhooks.emit("organization.updated", {
1888
+ organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
1889
+ });
1890
+ return [200, OK];
1891
+ });
1892
+ this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
1893
+ if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1894
+ this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
1895
+ return [200, OK];
1896
+ });
1897
+ this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
1898
+ if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1899
+ 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);
1900
+ const page = paginate(members, query);
1901
+ return [
1902
+ 200,
1903
+ {
1904
+ ...OK,
1905
+ organization_users: page.items.map(({ membership, user }) => ({
1906
+ id: user.id,
1907
+ email: user.email,
1908
+ full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
1909
+ last_name: user.familyName,
1910
+ first_name: user.givenName,
1911
+ picture: user.picture,
1912
+ joined_on: d.meta(user).createdOn,
1913
+ last_accessed_on: d.meta(user).lastSignedIn,
1914
+ is_suspended: d.meta(user).isSuspended,
1915
+ roles: [...membership.roles]
1916
+ })),
1917
+ next_token: page.nextToken
1918
+ }
1919
+ ];
1920
+ });
1921
+ this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
1922
+ if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1923
+ const users = Array.isArray(body.users) ? body.users : [];
1924
+ const added = [];
1925
+ const blocked = [];
1926
+ for (const entry of users) {
1927
+ const id = typeof entry.id === "string" ? entry.id : "";
1928
+ if (!d.user(id)) {
1929
+ blocked.push(id);
1930
+ continue;
1931
+ }
1932
+ d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
1933
+ added.push(id);
1934
+ }
1935
+ return [200, { ...OK, users_added: added, users_blocked: blocked }];
1936
+ });
1937
+ this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
1938
+ 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}.`);
1939
+ });
1940
+ this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
1941
+ const membership = d.membership(params.user_id, params.org_code);
1942
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1943
+ const roles = membership.roles.map((key) => d.ensureRole(key));
1944
+ return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
1945
+ });
1946
+ this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
1947
+ const membership = d.membership(params.user_id, params.org_code);
1948
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1949
+ const role = d.role(str(body.role_id) ?? "");
1950
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1951
+ if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
1952
+ return [200, OK];
1953
+ });
1954
+ this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
1955
+ const membership = d.membership(params.user_id, params.org_code);
1956
+ const role = d.role(params.role_id);
1957
+ if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
1958
+ membership.roles = membership.roles.filter((key) => key !== role.key);
1959
+ return [200, OK];
1960
+ });
1961
+ this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
1962
+ const membership = d.membership(params.user_id, params.org_code);
1963
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1964
+ const permissions = effectivePermissions(d.seed, membership).map((key) => {
1965
+ const permission = d.ensurePermission(key);
1966
+ const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
1967
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
1968
+ });
1969
+ return [200, { ...OK, permissions }];
1970
+ });
1971
+ this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
1972
+ const membership = d.membership(params.user_id, params.org_code);
1973
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1974
+ const permission = d.permission(str(body.permission_id) ?? "");
1975
+ if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
1976
+ if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
1977
+ return [200, OK];
1978
+ });
1979
+ this.route(
1980
+ "DELETE",
1981
+ "/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
1982
+ "delete:organization_user_permissions",
1983
+ ({ params }) => {
1984
+ const membership = d.membership(params.user_id, params.org_code);
1985
+ const permission = d.permission(params.permission_id);
1986
+ if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
1987
+ membership.permissions = membership.permissions.filter((key) => key !== permission.key);
1988
+ return [200, OK];
1989
+ }
1990
+ );
1991
+ this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
1992
+ const page = paginate(d.seed.roles, query);
1993
+ return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
1994
+ });
1995
+ this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
1996
+ const key = str(body.key);
1997
+ if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
1998
+ if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
1999
+ const role = d.ensureRole(key, {
2000
+ name: str(body.name) ?? void 0,
2001
+ description: str(body.description) ?? void 0,
2002
+ isDefault: body.is_default_role === true
2003
+ });
2004
+ this.webhooks.emit("role.created", {
2005
+ role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
2006
+ });
2007
+ return [201, { ...OK, role: { id: role.id } }];
2008
+ });
2009
+ this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
2010
+ const role = d.role(params.role_id);
2011
+ return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
2012
+ });
2013
+ this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
2014
+ const role = d.deleteRole(params.role_id);
2015
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
2016
+ this.webhooks.emit("role.deleted", { role: { id: role.id } });
2017
+ return [200, OK];
2018
+ });
2019
+ this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
2020
+ const role = d.role(params.role_id);
2021
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
2022
+ return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
2023
+ });
2024
+ this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
2025
+ const page = paginate(d.seed.permissions, query);
2026
+ return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
2027
+ });
2028
+ this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
2029
+ const key = str(body.key);
2030
+ if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
2031
+ if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
2032
+ const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
2033
+ this.webhooks.emit("permission.created", {
2034
+ permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
2035
+ });
2036
+ return [201, OK];
2037
+ });
2038
+ this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
2039
+ const permission = d.deletePermission(params.permission_id);
2040
+ if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
2041
+ this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
2042
+ return [200, OK];
2043
+ });
2044
+ }
2045
+ userListItem(user) {
2046
+ const meta = this.directory.meta(user);
2047
+ return {
2048
+ id: user.id,
2049
+ provided_id: meta.providedId,
2050
+ email: user.email,
2051
+ phone: null,
2052
+ username: null,
2053
+ last_name: user.familyName,
2054
+ first_name: user.givenName,
2055
+ is_suspended: meta.isSuspended,
2056
+ picture: user.picture,
2057
+ total_sign_ins: meta.totalSignIns,
2058
+ failed_sign_ins: 0,
2059
+ last_signed_in: meta.lastSignedIn,
2060
+ created_on: meta.createdOn,
2061
+ organizations: this.organizationsOf(user),
2062
+ identities: user.email ? [{ type: "email", identity: user.email }] : []
2063
+ };
2064
+ }
2065
+ userDetail(user) {
2066
+ const { email, ...rest } = this.userListItem(user);
2067
+ return { ...rest, preferred_email: email };
2068
+ }
2069
+ organizationsOf(user) {
2070
+ return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
2071
+ }
2072
+ organizationItem(org) {
2073
+ const meta = this.directory.orgInfo(org);
2074
+ return {
2075
+ code: org.code,
2076
+ name: org.name,
2077
+ handle: meta.handle,
2078
+ is_default: false,
2079
+ external_id: meta.externalId,
2080
+ is_auto_membership_enabled: false
2081
+ };
2082
+ }
2083
+ organizationEvent(org) {
2084
+ const meta = this.directory.orgInfo(org);
2085
+ return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
2086
+ }
2087
+ roleItem(role) {
2088
+ return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
2089
+ }
2090
+ permissionItem(permission) {
2091
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
2092
+ }
2093
+ };
2094
+ function paginate(items, query) {
2095
+ const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
2096
+ const token = query.get("next_token");
2097
+ const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
2098
+ const page = items.slice(offset, offset + size);
2099
+ const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
2100
+ return { items: page, nextToken: next };
2101
+ }
2102
+ function errors2(code, message) {
2103
+ return { errors: [{ code, message }] };
2104
+ }
2105
+ function notFound(code, message) {
2106
+ return [404, errors2(code, message)];
2107
+ }
2108
+ function str(value) {
2109
+ return typeof value === "string" ? value : null;
2110
+ }
2111
+ function strings(value) {
2112
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
2113
+ }
2114
+ function sendJson3(res, status, body) {
2115
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2116
+ res.end(JSON.stringify(body));
2117
+ }
2118
+
1121
2119
  // src/failures.ts
1122
2120
  var MAX_DELAY_MS = 6e4;
1123
2121
  var FailureInjector = class {
@@ -1198,6 +2196,278 @@ function validate(rule) {
1198
2196
  return problems;
1199
2197
  }
1200
2198
 
2199
+ // src/webhooks.ts
2200
+ var import_node_crypto6 = require("crypto");
2201
+ var WEBHOOK_EVENT_TYPES = [
2202
+ "user.created",
2203
+ "user.updated",
2204
+ "user.deleted",
2205
+ "user.authenticated",
2206
+ "user.authentication_failed",
2207
+ "organization.created",
2208
+ "organization.updated",
2209
+ "organization.deleted",
2210
+ "role.created",
2211
+ "role.updated",
2212
+ "role.deleted",
2213
+ "permission.created",
2214
+ "permission.updated",
2215
+ "permission.deleted",
2216
+ "subscriber.created",
2217
+ "access_request.created"
2218
+ ];
2219
+ var BILLING_EVENT_TYPES = [
2220
+ "customer.agreement_cancelled",
2221
+ "customer.agreement_created",
2222
+ "customer.invoice_overdue",
2223
+ "customer.meter_usage_updated",
2224
+ "customer.payment_failed",
2225
+ "customer.payment_succeeded",
2226
+ "customer.plan_assigned",
2227
+ "customer.plan_changed"
2228
+ ];
2229
+ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
2230
+ var DEFAULT_TIMEOUT_MS = 5e3;
2231
+ var MAX_DUPLICATES = 10;
2232
+ var WebhookDispatcher = class {
2233
+ constructor(testkit, seed, endpoints = [], options = {}) {
2234
+ this.testkit = testkit;
2235
+ this.seed = seed;
2236
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
2237
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2238
+ for (const endpoint of endpoints) this.addEndpoint(endpoint);
2239
+ this.seededEndpoints = [...this.endpoints];
2240
+ }
2241
+ testkit;
2242
+ seed;
2243
+ endpoints = [];
2244
+ seededEndpoints = [];
2245
+ log = [];
2246
+ nextEndpoint = 1;
2247
+ retryDelaysMs;
2248
+ timeoutMs;
2249
+ addEndpoint(input) {
2250
+ if (!isHttpUrl2(input.url)) {
2251
+ throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
2252
+ }
2253
+ if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
2254
+ throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
2255
+ }
2256
+ const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
2257
+ this.endpoints.push(endpoint);
2258
+ return { ...endpoint };
2259
+ }
2260
+ removeEndpoint(id) {
2261
+ const before = this.endpoints.length;
2262
+ this.endpoints = this.endpoints.filter((e) => e.id !== id);
2263
+ return this.endpoints.length < before;
2264
+ }
2265
+ listEndpoints() {
2266
+ return this.endpoints.map((e) => ({ ...e }));
2267
+ }
2268
+ deliveries() {
2269
+ return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
2270
+ }
2271
+ reset() {
2272
+ this.log = [];
2273
+ this.endpoints = [...this.seededEndpoints];
2274
+ }
2275
+ buildEvent(options) {
2276
+ if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
2277
+ throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
2278
+ }
2279
+ const now = /* @__PURE__ */ new Date();
2280
+ const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
2281
+ const event = {
2282
+ data: options.data ?? this.buildData(options),
2283
+ event_id: `event_${(0, import_node_crypto6.randomBytes)(16).toString("hex")}`,
2284
+ event_timestamp: timestamp,
2285
+ source: options.source ?? "admin",
2286
+ timestamp,
2287
+ type: options.type
2288
+ };
2289
+ if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
2290
+ event.ip_address = options.ipAddress ?? "127.0.0.1";
2291
+ }
2292
+ return event;
2293
+ }
2294
+ async send(options) {
2295
+ const event = this.buildEvent(options);
2296
+ const copies = options.duplicate ?? 1;
2297
+ if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
2298
+ throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
2299
+ }
2300
+ const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
2301
+ if (options.to && !isHttpUrl2(options.to)) {
2302
+ throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
2303
+ }
2304
+ if (targets.length === 0) {
2305
+ throw new TestkitError(
2306
+ "INVALID_REQUEST",
2307
+ `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
2308
+ );
2309
+ }
2310
+ if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
2311
+ const signed = await this.testkit.signPayload(
2312
+ event,
2313
+ options.invalid === "stale" ? void 0 : options.invalid
2314
+ );
2315
+ const jobs = targets.flatMap((target) => {
2316
+ const webhookId = `wh_${(0, import_node_crypto6.randomBytes)(12).toString("hex")}`;
2317
+ return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
2318
+ });
2319
+ return Promise.all(jobs);
2320
+ }
2321
+ async deliver(url, webhookId, body, event, copy) {
2322
+ const delivery = {
2323
+ webhookId,
2324
+ eventId: String(event.event_id),
2325
+ type: String(event.type),
2326
+ url,
2327
+ copy,
2328
+ delivered: false,
2329
+ attempts: [],
2330
+ payload: event
2331
+ };
2332
+ this.log.push(delivery);
2333
+ for (const [index, delay] of this.retryDelaysMs.entries()) {
2334
+ if (delay > 0) await sleep(delay);
2335
+ const started = Date.now();
2336
+ try {
2337
+ const response = await fetch(url, {
2338
+ method: "POST",
2339
+ headers: { "content-type": "application/jwt", "webhook-id": webhookId },
2340
+ body,
2341
+ signal: AbortSignal.timeout(this.timeoutMs)
2342
+ });
2343
+ await response.arrayBuffer().catch(() => void 0);
2344
+ delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
2345
+ if (response.status === 200) {
2346
+ delivery.delivered = true;
2347
+ break;
2348
+ }
2349
+ } catch (error) {
2350
+ const name = error.name;
2351
+ delivery.attempts.push({
2352
+ attempt: index + 1,
2353
+ status: null,
2354
+ error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
2355
+ durationMs: Date.now() - started
2356
+ });
2357
+ }
2358
+ }
2359
+ return { ...delivery, attempts: [...delivery.attempts] };
2360
+ }
2361
+ buildData(options) {
2362
+ const [subject] = options.type.split(".");
2363
+ switch (subject) {
2364
+ case "user":
2365
+ return { user: this.userData(options) };
2366
+ case "organization":
2367
+ return { organization: this.organizationData(options) };
2368
+ case "role":
2369
+ return { role: this.namedData(options, "role") };
2370
+ case "permission":
2371
+ return { permission: this.namedData(options, "permission") };
2372
+ case "subscriber": {
2373
+ const user = this.requireUser(options);
2374
+ return {
2375
+ subscriber: {
2376
+ email: user.email,
2377
+ first_name: user.givenName,
2378
+ id: stableId("sub", user.id),
2379
+ last_name: user.familyName,
2380
+ user_id: user.id
2381
+ }
2382
+ };
2383
+ }
2384
+ case "access_request": {
2385
+ const user = this.requireUser(options);
2386
+ return {
2387
+ access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
2388
+ };
2389
+ }
2390
+ default:
2391
+ throw new TestkitError(
2392
+ "INVALID_REQUEST",
2393
+ `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
2394
+ );
2395
+ }
2396
+ }
2397
+ emit(type, data, source = "api") {
2398
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
2399
+ void this.send({ type, data, source }).catch(() => void 0);
2400
+ }
2401
+ userEventData(user) {
2402
+ return this.userPayload(user);
2403
+ }
2404
+ emitForUser(type, user) {
2405
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
2406
+ const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
2407
+ void this.send({ type, data, source: "user" }).catch(() => void 0);
2408
+ }
2409
+ userData(options) {
2410
+ const user = this.requireUser(options);
2411
+ if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
2412
+ return this.userPayload(user);
2413
+ }
2414
+ userPayload(user) {
2415
+ return {
2416
+ email: user.email,
2417
+ first_name: user.givenName,
2418
+ id: user.id,
2419
+ is_password_reset_requested: false,
2420
+ is_suspended: false,
2421
+ last_name: user.familyName,
2422
+ organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
2423
+ code: m.organizationCode,
2424
+ permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
2425
+ roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
2426
+ })),
2427
+ phone: null,
2428
+ username: typeof user.claims.username === "string" ? user.claims.username : null
2429
+ };
2430
+ }
2431
+ organizationData(options) {
2432
+ if (!options.organization) {
2433
+ throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
2434
+ }
2435
+ const org = this.seed.organizations.find((o) => o.code === options.organization);
2436
+ if (options.type === "organization.deleted") return { code: options.organization };
2437
+ const name = org?.name ?? titleCase(options.organization);
2438
+ const data = { code: options.organization, external_id: null, handle: slug(name), name };
2439
+ if (options.type === "organization.updated") data.is_allow_registrations = false;
2440
+ return data;
2441
+ }
2442
+ namedData(options, kind) {
2443
+ const key = kind === "role" ? options.role : options.permission;
2444
+ if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
2445
+ const id = stableId(kind === "role" ? "role" : "perm", key);
2446
+ if (options.type.endsWith(".deleted")) return { id };
2447
+ const data = { description: "", id, key, name: titleCase(key) };
2448
+ if (kind === "role") data.is_default_role = false;
2449
+ return data;
2450
+ }
2451
+ requireUser(options) {
2452
+ if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
2453
+ const user = findUser(this.seed.users, options.user);
2454
+ if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
2455
+ return user;
2456
+ }
2457
+ };
2458
+ function isHttpUrl2(value) {
2459
+ if (typeof value !== "string") return false;
2460
+ try {
2461
+ const { protocol } = new URL(value);
2462
+ return protocol === "http:" || protocol === "https:";
2463
+ } catch {
2464
+ return false;
2465
+ }
2466
+ }
2467
+ function sleep(ms) {
2468
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
2469
+ }
2470
+
1201
2471
  // src/server.ts
1202
2472
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
1203
2473
  var MAX_BODY_BYTES = 64 * 1024;
@@ -1213,28 +2483,36 @@ async function startKindeTestkit(options = {}) {
1213
2483
  const seed = resolveSeed(options.seed ?? {});
1214
2484
  const failures = new FailureInjector();
1215
2485
  let ready;
1216
- const testkitReady = new Promise((resolve) => ready = resolve);
1217
- const server = (0, import_node_http.createServer)((req, res) => {
2486
+ const testkitReady = new Promise((resolve2) => ready = resolve2);
2487
+ const listener = (req, res) => {
1218
2488
  testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
1219
- });
1220
- await new Promise((resolve, reject) => {
2489
+ };
2490
+ const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
2491
+ const server = certificate ? (0, import_node_https.createServer)({ cert: certificate.cert, key: certificate.key }, listener) : (0, import_node_http.createServer)(listener);
2492
+ await new Promise((resolve2, reject) => {
1221
2493
  server.once("error", reject);
1222
- server.listen(options.port ?? 4400, host, () => resolve());
2494
+ server.listen(options.port ?? 4400, host, () => resolve2());
1223
2495
  });
1224
2496
  const { port } = server.address();
1225
2497
  const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
1226
- const url = `http://${urlHost}:${port}`;
2498
+ const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
1227
2499
  const testkit = await KindeTestkit.create({
1228
2500
  issuer: options.issuer ?? options.seed?.issuer ?? url,
1229
2501
  audience: options.audience ?? options.seed?.audience,
1230
2502
  clientId: options.clientId ?? options.seed?.clientId
1231
2503
  });
1232
- const auth = new AuthorizationServer(testkit, seed);
2504
+ const directory = new Directory(seed);
2505
+ const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
2506
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
2507
+ const management = new ManagementApi(testkit, directory, webhooks);
2508
+ const account = new AccountApi(testkit, directory);
1233
2509
  const reset = () => {
1234
2510
  auth.reset();
1235
2511
  failures.clear();
2512
+ webhooks.reset();
2513
+ directory.restore();
1236
2514
  };
1237
- ready({ testkit, auth, seed, failures, reset });
2515
+ ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
1238
2516
  return {
1239
2517
  url,
1240
2518
  issuer: testkit.issuer,
@@ -1243,15 +2521,18 @@ async function startKindeTestkit(options = {}) {
1243
2521
  testkit,
1244
2522
  seed,
1245
2523
  failures,
2524
+ webhooks,
2525
+ directory,
2526
+ certificatePath: certificate?.certPath ?? null,
1246
2527
  reset,
1247
- close: () => new Promise((resolve, reject) => {
2528
+ close: () => new Promise((resolve2, reject) => {
1248
2529
  server.closeAllConnections();
1249
- server.close((error) => error ? reject(error) : resolve());
2530
+ server.close((error) => error ? reject(error) : resolve2());
1250
2531
  })
1251
2532
  };
1252
2533
  }
1253
2534
  async function handle(req, res, context) {
1254
- const { testkit, auth, seed, failures } = context;
2535
+ const { testkit, auth, seed, failures, webhooks } = context;
1255
2536
  const url = new URL(req.url ?? "/", "http://localhost");
1256
2537
  const { pathname } = url;
1257
2538
  const method = req.method ?? "GET";
@@ -1259,53 +2540,77 @@ async function handle(req, res, context) {
1259
2540
  const failure = failures.take(method, pathname);
1260
2541
  if (failure) {
1261
2542
  if (failure.hang) return;
1262
- if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
2543
+ if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
1263
2544
  if (failure.status !== null) {
1264
2545
  const headers = {};
1265
2546
  if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
1266
- return sendJson2(res, failure.status, failureBody(failure.status), headers);
2547
+ return sendJson4(res, failure.status, failureBody(failure.status), headers);
1267
2548
  }
1268
2549
  }
1269
2550
  }
1270
2551
  if (await auth.handle(req, res, url, () => readForm(req))) return;
2552
+ if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
2553
+ if (await context.account.handle(req, res, url)) return;
2554
+ if (method === "GET" && pathname === "/testkit/portal") {
2555
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2556
+ res.end(
2557
+ `<!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>`
2558
+ );
2559
+ return;
2560
+ }
1271
2561
  if (method === "GET" && pathname === "/.well-known/openid-configuration") {
1272
- return sendJson2(res, 200, discovery(testkit));
2562
+ return sendJson4(res, 200, discovery(testkit));
1273
2563
  }
1274
2564
  if (method === "GET" && JWKS_PATHS.has(pathname)) {
1275
- return sendJson2(res, 200, testkit.jwks());
2565
+ return sendJson4(res, 200, testkit.jwks());
1276
2566
  }
1277
2567
  if (method === "GET" && pathname === "/testkit/health") {
1278
- return sendJson2(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
2568
+ return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
1279
2569
  }
1280
- if (method === "GET" && pathname === "/testkit/users") return sendJson2(res, 200, seed.users);
2570
+ if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
1281
2571
  if (method === "GET" && pathname === "/testkit/organizations") {
1282
- return sendJson2(res, 200, seed.organizations);
2572
+ return sendJson4(res, 200, seed.organizations);
1283
2573
  }
1284
2574
  if (method === "GET" && pathname === "/testkit/memberships") {
1285
- return sendJson2(res, 200, seed.memberships);
2575
+ return sendJson4(res, 200, seed.memberships);
1286
2576
  }
1287
- if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
2577
+ if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
1288
2578
  if (method === "POST" && pathname === "/testkit/failures") {
1289
- return sendJson2(res, 201, failures.add(await readJson(req)));
2579
+ return sendJson4(res, 201, failures.add(await readJson(req)));
1290
2580
  }
1291
2581
  if (method === "DELETE" && pathname === "/testkit/failures") {
1292
2582
  failures.clear();
1293
- return sendJson2(res, 200, { ok: true });
2583
+ return sendJson4(res, 200, { ok: true });
1294
2584
  }
1295
2585
  if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
1296
2586
  const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1297
- return sendJson2(res, removed ? 200 : 404, { ok: removed });
2587
+ return sendJson4(res, removed ? 200 : 404, { ok: removed });
2588
+ }
2589
+ if (method === "POST" && pathname === "/testkit/webhooks") {
2590
+ return sendJson4(res, 200, await webhooks.send(await readJson(req)));
2591
+ }
2592
+ if (method === "GET" && pathname === "/testkit/webhooks/types") {
2593
+ return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
2594
+ }
2595
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
2596
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
2597
+ if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
2598
+ return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
2599
+ }
2600
+ if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
2601
+ const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
2602
+ return sendJson4(res, removed ? 200 : 404, { ok: removed });
1298
2603
  }
1299
2604
  if (method === "POST" && pathname === "/testkit/reset") {
1300
2605
  context.reset();
1301
- return sendJson2(res, 200, { ok: true });
2606
+ return sendJson4(res, 200, { ok: true });
1302
2607
  }
1303
2608
  if (method === "POST" && pathname === "/testkit/token") {
1304
2609
  const body = await readJson(req);
1305
2610
  const accessToken = await issueToken(testkit, seed, body);
1306
- return sendJson2(res, 200, { access_token: accessToken, token_type: "Bearer" });
2611
+ return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
1307
2612
  }
1308
- return sendJson2(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
2613
+ return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
1309
2614
  }
1310
2615
  function discovery(testkit) {
1311
2616
  const base = testkit.issuer;
@@ -1364,7 +2669,11 @@ async function issueToken(testkit, seed, body) {
1364
2669
  });
1365
2670
  if (permissions) scenario2.permissions = permissions;
1366
2671
  if (roles) scenario2.roles = roles;
1367
- return await testkit.tokenFor(scenario2, { expiresIn, invalid: invalid2 });
2672
+ return await testkit.tokenFor(scenario2, {
2673
+ expiresIn,
2674
+ invalid: invalid2,
2675
+ featureFlags: featureFlagsFor(seed, scenario2.organization?.code ?? null)
2676
+ });
1368
2677
  }
1369
2678
  const options = {
1370
2679
  subject: optionalString(input, "subject"),
@@ -1429,7 +2738,7 @@ async function readText(req) {
1429
2738
  }
1430
2739
  return Buffer.concat(chunks).toString("utf8").trim();
1431
2740
  }
1432
- function sendJson2(res, status, body, headers = {}) {
2741
+ function sendJson4(res, status, body, headers = {}) {
1433
2742
  res.writeHead(status, {
1434
2743
  "content-type": "application/json; charset=utf-8",
1435
2744
  "cache-control": "no-store",
@@ -1443,10 +2752,10 @@ function sendError(res, error) {
1443
2752
  return;
1444
2753
  }
1445
2754
  if (error instanceof TestkitError) {
1446
- sendJson2(res, 400, { error: error.code, error_description: error.message, details: error.details });
2755
+ sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
1447
2756
  return;
1448
2757
  }
1449
- sendJson2(res, 500, {
2758
+ sendJson4(res, 500, {
1450
2759
  error: "server_error",
1451
2760
  error_description: error instanceof Error ? error.message : String(error)
1452
2761
  });
@@ -1593,6 +2902,15 @@ async function runDoctor(options) {
1593
2902
  } else {
1594
2903
  checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
1595
2904
  }
2905
+ if (issuer?.startsWith("https://")) {
2906
+ checks.push(
2907
+ env.NODE_EXTRA_CA_CERTS ? { name: "NODE_EXTRA_CA_CERTS", status: "pass", detail: `${env.NODE_EXTRA_CA_CERTS}.` } : {
2908
+ name: "NODE_EXTRA_CA_CERTS",
2909
+ status: "warn",
2910
+ detail: "The testkit serves HTTPS with a local certificate. Start your app with NODE_EXTRA_CA_CERTS set to it, or Node will refuse the connection."
2911
+ }
2912
+ );
2913
+ }
1596
2914
  const site = env.KINDE_SITE_URL;
1597
2915
  if (!site) {
1598
2916
  checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
@@ -1620,20 +2938,26 @@ function parseEnvFile(text) {
1620
2938
  }
1621
2939
  // Annotate the CommonJS export names for ESM import in node:
1622
2940
  0 && (module.exports = {
2941
+ BILLING_EVENT_TYPES,
1623
2942
  DEFAULT_AUTH_METHODS,
1624
2943
  DEFAULT_CLIENT_ID,
1625
2944
  DEFAULT_ISSUER,
1626
2945
  DEFAULT_M2M_CLIENT_ID,
1627
2946
  DEFAULT_SCOPES,
2947
+ Directory,
1628
2948
  FailureInjector,
1629
2949
  INVALID_TOKEN_KINDS,
1630
2950
  KindeTestkit,
1631
2951
  ScenarioBuilder,
1632
2952
  TestkitError,
2953
+ WEBHOOK_EVENT_TYPES,
2954
+ WebhookDispatcher,
1633
2955
  createKindeOrganization,
1634
2956
  createKindeToken,
1635
2957
  createKindeUser,
2958
+ createLocalCertificate,
1636
2959
  createMembership,
2960
+ ensureLocalCertificate,
1637
2961
  getDefaultTestkit,
1638
2962
  inspectToken,
1639
2963
  isAuthenticated,