kinde-testkit 0.4.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.js CHANGED
@@ -440,8 +440,230 @@ async function createKindeToken(options = {}) {
440
440
 
441
441
  // src/server.ts
442
442
  import { createServer } from "http";
443
+ import { createServer as createHttpsServer } from "https";
444
+
445
+ // src/certificate.ts
446
+ import { createHash as createHash2, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
447
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
448
+ import { join, resolve } from "path";
449
+ var CERT_FILE = "localhost-cert.pem";
450
+ var KEY_FILE = "localhost-key.pem";
451
+ var VALID_DAYS = 825;
452
+ function ensureLocalCertificate(directory = ".kinde-testkit") {
453
+ const dir = resolve(directory);
454
+ const certPath = join(dir, CERT_FILE);
455
+ const keyPath = join(dir, KEY_FILE);
456
+ if (existsSync(certPath) && existsSync(keyPath)) {
457
+ const cert2 = readFileSync(certPath, "utf8");
458
+ const key2 = readFileSync(keyPath, "utf8");
459
+ try {
460
+ if (new Date(new X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
461
+ return { cert: cert2, key: key2, certPath, keyPath, created: false };
462
+ }
463
+ } catch {
464
+ }
465
+ }
466
+ const { cert, key } = createLocalCertificate();
467
+ mkdirSync(dir, { recursive: true });
468
+ writeFileSync(certPath, cert);
469
+ writeFileSync(keyPath, key, { mode: 384 });
470
+ writeFileSync(join(dir, ".gitignore"), "*\n");
471
+ return { cert, key, certPath, keyPath, created: true };
472
+ }
473
+ function createLocalCertificate() {
474
+ const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
475
+ const spki = publicKey.export({ type: "spki", format: "der" });
476
+ const keyId = createHash2("sha1").update(subjectPublicKeyBits(spki)).digest();
477
+ const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
478
+ const now = Date.now();
479
+ const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
480
+ const serial = randomBytes(16);
481
+ serial[0] &= 127;
482
+ const extensions = seq(
483
+ seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
484
+ seq(oid("2.5.29.14"), octets(octets(keyId))),
485
+ seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
486
+ seq(
487
+ oid("2.5.29.17"),
488
+ octets(
489
+ seq(
490
+ tlv(130, Buffer.from("localhost")),
491
+ tlv(135, Buffer.from([127, 0, 0, 1])),
492
+ tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
493
+ )
494
+ )
495
+ )
496
+ );
497
+ const tbs = seq(
498
+ tlv(160, integer(Buffer.from([2]))),
499
+ integer(serial),
500
+ algorithm,
501
+ name,
502
+ seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
503
+ name,
504
+ spki,
505
+ tlv(163, extensions)
506
+ );
507
+ const signature = sign("sha256", tbs, privateKey);
508
+ const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
509
+ return {
510
+ cert: pem("CERTIFICATE", der),
511
+ key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
512
+ };
513
+ }
514
+ function subjectPublicKeyBits(spki) {
515
+ const outer = readTlv(spki, 0);
516
+ const algorithm = readTlv(spki, outer.start);
517
+ const bits = readTlv(spki, algorithm.end);
518
+ return spki.subarray(bits.start + 1, bits.end);
519
+ }
520
+ function readTlv(buf, offset) {
521
+ let len = buf[offset + 1];
522
+ let header = 2;
523
+ if (len & 128) {
524
+ const n = len & 127;
525
+ len = 0;
526
+ for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
527
+ header += n;
528
+ }
529
+ return { start: offset + header, end: offset + header + len };
530
+ }
531
+ function tlv(tag, content) {
532
+ return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
533
+ }
534
+ function length(n) {
535
+ if (n < 128) return Buffer.from([n]);
536
+ const bytes = [];
537
+ while (n > 0) {
538
+ bytes.unshift(n & 255);
539
+ n >>= 8;
540
+ }
541
+ return Buffer.from([128 | bytes.length, ...bytes]);
542
+ }
543
+ function seq(...items) {
544
+ return tlv(48, Buffer.concat(items));
545
+ }
546
+ function set(...items) {
547
+ return tlv(49, Buffer.concat(items));
548
+ }
549
+ function octets(content) {
550
+ return tlv(4, content);
551
+ }
552
+ function integer(bytes) {
553
+ return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
554
+ }
555
+ function oid(dotted) {
556
+ const parts = dotted.split(".").map(Number);
557
+ const bytes = [parts[0] * 40 + parts[1]];
558
+ for (const part of parts.slice(2)) {
559
+ const chunk = [part & 127];
560
+ let value = part >> 7;
561
+ while (value > 0) {
562
+ chunk.unshift(value & 127 | 128);
563
+ value >>= 7;
564
+ }
565
+ bytes.push(...chunk);
566
+ }
567
+ return tlv(6, Buffer.from(bytes));
568
+ }
569
+ function utcTime(date) {
570
+ const iso = date.toISOString();
571
+ 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`;
572
+ return tlv(23, Buffer.from(value));
573
+ }
574
+ function pem(label, der) {
575
+ const body = der.toString("base64").match(/.{1,64}/g).join("\n");
576
+ return `-----BEGIN ${label}-----
577
+ ${body}
578
+ -----END ${label}-----
579
+ `;
580
+ }
581
+
582
+ // src/login-page.ts
583
+ var STYLE = `
584
+ :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}
585
+ @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}}
586
+ *{box-sizing:border-box}
587
+ 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}
588
+ main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
589
+ .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
590
+ h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
591
+ p{margin:0;color:var(--muted)}
592
+ .note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
593
+ form{margin:0}
594
+ label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
595
+ 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}
596
+ input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
597
+ .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}
598
+ h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
599
+ .list{display:grid;gap:8px}
600
+ .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}
601
+ .option:hover{border-color:var(--muted)}
602
+ .option strong{display:block;font-weight:500}
603
+ .option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
604
+ .tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
605
+ .error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
606
+ `;
607
+ function escapeHtml(value) {
608
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
609
+ }
610
+ function layout(title, body) {
611
+ 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>`;
612
+ }
613
+ function displayName(user) {
614
+ return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
615
+ }
616
+ function renderSignIn(options) {
617
+ const users = options.users.map(({ user, organizations }) => {
618
+ const value = escapeHtml(user.email ?? user.id);
619
+ const hasName = Boolean(user.givenName || user.familyName);
620
+ const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
621
+ const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
622
+ 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>`;
623
+ }).join("");
624
+ const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
625
+ return layout(
626
+ "Sign in",
627
+ `<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>`
628
+ );
629
+ }
630
+ function renderOrganizationPicker(options) {
631
+ const choices = options.organizations.map(
632
+ (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>`
633
+ ).join("");
634
+ return layout(
635
+ "Choose an organization",
636
+ `<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>`
637
+ );
638
+ }
639
+ function renderMessage(title, message) {
640
+ return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
641
+ }
443
642
 
444
643
  // src/seed.ts
644
+ function roleRecord(key, extra = {}) {
645
+ return {
646
+ id: stableId("role", key),
647
+ key,
648
+ name: extra.name ?? titleCase(key),
649
+ description: extra.description ?? null,
650
+ isDefault: extra.isDefault ?? false,
651
+ permissions: [...extra.permissions ?? []]
652
+ };
653
+ }
654
+ function permissionRecord(key, extra = {}) {
655
+ return {
656
+ id: stableId("perm", key),
657
+ key,
658
+ name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
659
+ description: extra.description ?? null
660
+ };
661
+ }
662
+ function effectivePermissions(seed, membership) {
663
+ if (!membership) return [];
664
+ const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
665
+ return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
666
+ }
445
667
  function resolveSeed(input) {
446
668
  const problems = [];
447
669
  if (!isRecord(input)) {
@@ -452,6 +674,10 @@ function resolveSeed(input) {
452
674
  const rawMemberships = listOf(input.memberships, "memberships", problems);
453
675
  const rawApplications = listOf(input.applications, "applications", problems);
454
676
  const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
677
+ const rawRoles = listOf(input.roles, "roles", problems);
678
+ const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
679
+ const rawPlans = listOf(input.plans, "plans", problems);
680
+ const rawPermissions = listOf(input.permissions, "permissions", problems);
455
681
  const webhooks = [];
456
682
  rawWebhooks.forEach((raw, index) => {
457
683
  if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
@@ -555,7 +781,107 @@ function resolveSeed(input) {
555
781
  if (problems.length > 0) {
556
782
  throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
557
783
  }
558
- return { users, organizations, memberships, applications, webhooks };
784
+ const permissions = [];
785
+ rawPermissions.forEach((raw, index) => {
786
+ if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
787
+ problems.push(`permissions[${index}] needs a string "key".`);
788
+ return;
789
+ }
790
+ if (permissions.some((p) => p.key === raw.key)) {
791
+ problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
792
+ return;
793
+ }
794
+ permissions.push(
795
+ permissionRecord(raw.key, {
796
+ name: typeof raw.name === "string" ? raw.name : void 0,
797
+ description: typeof raw.description === "string" ? raw.description : void 0
798
+ })
799
+ );
800
+ });
801
+ const roles = [];
802
+ rawRoles.forEach((raw, index) => {
803
+ if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
804
+ problems.push(`roles[${index}] needs a string "key".`);
805
+ return;
806
+ }
807
+ if (roles.some((r) => r.key === raw.key)) {
808
+ problems.push(`roles[${index}] repeats the key "${raw.key}".`);
809
+ return;
810
+ }
811
+ if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
812
+ problems.push(`roles[${index}].permissions must be a list of permission keys.`);
813
+ return;
814
+ }
815
+ roles.push(
816
+ roleRecord(raw.key, {
817
+ name: typeof raw.name === "string" ? raw.name : void 0,
818
+ description: typeof raw.description === "string" ? raw.description : void 0,
819
+ isDefault: raw.isDefault === true,
820
+ permissions: raw.permissions ?? []
821
+ })
822
+ );
823
+ });
824
+ if (problems.length > 0) {
825
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
826
+ }
827
+ const featureFlags = [];
828
+ rawFlags.forEach((raw, index) => {
829
+ if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
830
+ problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
831
+ return;
832
+ }
833
+ const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
834
+ featureFlags.push({
835
+ id: stableId("flag", raw.key),
836
+ key: raw.key,
837
+ name: typeof raw.name === "string" ? raw.name : raw.key,
838
+ type,
839
+ value: raw.value,
840
+ organizations: isRecord(raw.organizations) ? raw.organizations : {}
841
+ });
842
+ });
843
+ const plans = [];
844
+ rawPlans.forEach((raw, index) => {
845
+ if (!isRecord(raw) || typeof raw.key !== "string") {
846
+ problems.push(`plans[${index}] needs a string "key".`);
847
+ return;
848
+ }
849
+ const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
850
+ plans.push({
851
+ key: raw.key,
852
+ name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
853
+ subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
854
+ subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
855
+ entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
856
+ id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
857
+ featureKey: e.featureKey,
858
+ featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
859
+ priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
860
+ fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
861
+ unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
862
+ limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
863
+ limitMin: typeof e.limitMin === "number" ? e.limitMin : null
864
+ }))
865
+ });
866
+ });
867
+ const userProperties = {};
868
+ rawUsers.forEach((raw) => {
869
+ if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
870
+ userProperties[raw.id] = raw.properties;
871
+ }
872
+ });
873
+ if (problems.length > 0) {
874
+ throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
875
+ }
876
+ const usedRoles = new Set(memberships.flatMap((m) => m.roles));
877
+ for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
878
+ const usedPermissions = /* @__PURE__ */ new Set([
879
+ ...memberships.flatMap((m) => m.permissions),
880
+ ...roles.flatMap((r) => r.permissions),
881
+ ...applications.flatMap((a) => a.permissions ?? [])
882
+ ]);
883
+ for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
884
+ return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
559
885
  }
560
886
  function findUser(users, ref) {
561
887
  const needle = ref.toLowerCase();
@@ -600,7 +926,7 @@ function seedScenario(seed, ref) {
600
926
  user,
601
927
  organization,
602
928
  roles: [...membership?.roles ?? []],
603
- permissions: [...membership?.permissions ?? []],
929
+ permissions: effectivePermissions(seed, membership),
604
930
  claims: {}
605
931
  };
606
932
  }
@@ -615,72 +941,18 @@ function listOf(value, field, problems) {
615
941
  function isRecord(value) {
616
942
  return typeof value === "object" && value !== null && !Array.isArray(value);
617
943
  }
618
-
619
- // src/oauth.ts
620
- import { createHash as createHash2, randomBytes, timingSafeEqual } from "crypto";
621
-
622
- // src/login-page.ts
623
- var STYLE = `
624
- :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}
625
- @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}}
626
- *{box-sizing:border-box}
627
- 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}
628
- main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
629
- .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
630
- h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
631
- p{margin:0;color:var(--muted)}
632
- .note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
633
- form{margin:0}
634
- label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
635
- 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}
636
- input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
637
- .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}
638
- h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
639
- .list{display:grid;gap:8px}
640
- .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}
641
- .option:hover{border-color:var(--muted)}
642
- .option strong{display:block;font-weight:500}
643
- .option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
644
- .tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
645
- .error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
646
- `;
647
- function escapeHtml(value) {
648
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
649
- }
650
- function layout(title, body) {
651
- 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>`;
652
- }
653
- function displayName(user) {
654
- return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
655
- }
656
- function renderSignIn(options) {
657
- const users = options.users.map(({ user, organizations }) => {
658
- const value = escapeHtml(user.email ?? user.id);
659
- const hasName = Boolean(user.givenName || user.familyName);
660
- const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
661
- const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
662
- 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>`;
663
- }).join("");
664
- const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
665
- return layout(
666
- "Sign in",
667
- `<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>`
668
- );
669
- }
670
- function renderOrganizationPicker(options) {
671
- const choices = options.organizations.map(
672
- (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>`
673
- ).join("");
674
- return layout(
675
- "Choose an organization",
676
- `<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>`
677
- );
678
- }
679
- function renderMessage(title, message) {
680
- return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
944
+ function featureFlagsFor(seed, organizationCode) {
945
+ if (seed.featureFlags.length === 0) return void 0;
946
+ const claim = {};
947
+ for (const flag of seed.featureFlags) {
948
+ const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
949
+ claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
950
+ }
951
+ return claim;
681
952
  }
682
953
 
683
954
  // src/oauth.ts
955
+ import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
684
956
  var CODE_LIFETIME_MS = 10 * 60 * 1e3;
685
957
  var OAuthError = class extends Error {
686
958
  constructor(status, error, description) {
@@ -692,14 +964,16 @@ var OAuthError = class extends Error {
692
964
  error;
693
965
  };
694
966
  var AuthorizationServer = class {
695
- constructor(testkit, seed, emit = () => void 0) {
967
+ constructor(testkit, seed, emit = () => void 0, directory) {
696
968
  this.testkit = testkit;
697
969
  this.seed = seed;
698
970
  this.emit = emit;
971
+ this.directory = directory;
699
972
  }
700
973
  testkit;
701
974
  seed;
702
975
  emit;
976
+ directory;
703
977
  codes = /* @__PURE__ */ new Map();
704
978
  refreshTokens = /* @__PURE__ */ new Map();
705
979
  signedUpUsers = /* @__PURE__ */ new Map();
@@ -765,6 +1039,18 @@ var AuthorizationServer = class {
765
1039
  if (!user) {
766
1040
  return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
767
1041
  }
1042
+ if (this.directory?.isSuspended(user.id)) {
1043
+ return sendHtml(
1044
+ res,
1045
+ 403,
1046
+ renderSignIn({
1047
+ request: encoded,
1048
+ users: this.loginPageUsers(),
1049
+ requiredOrganization: request.orgCode ?? void 0,
1050
+ error: `${user.email ?? user.id} is suspended and cannot sign in.`
1051
+ })
1052
+ );
1053
+ }
768
1054
  const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
769
1055
  const wanted = request.orgCode ?? form.org ?? null;
770
1056
  let organizationCode = null;
@@ -801,7 +1087,7 @@ var AuthorizationServer = class {
801
1087
  user,
802
1088
  organization: organizationCode ? this.organization(organizationCode) : null,
803
1089
  roles: [...membership?.roles ?? []],
804
- permissions: [...membership?.permissions ?? []],
1090
+ permissions: effectivePermissions(this.seed, membership),
805
1091
  claims: {}
806
1092
  };
807
1093
  const code = randomToken();
@@ -817,6 +1103,7 @@ var AuthorizationServer = class {
817
1103
  codeChallengeMethod: request.codeChallengeMethod,
818
1104
  expiresAt: Date.now() + CODE_LIFETIME_MS
819
1105
  });
1106
+ this.directory?.recordSignIn(user, organizationCode);
820
1107
  this.emit("user.authenticated", user);
821
1108
  const target = new URL(request.redirectUri);
822
1109
  target.searchParams.set("code", code);
@@ -852,7 +1139,7 @@ var AuthorizationServer = class {
852
1139
  throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
853
1140
  }
854
1141
  const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
855
- const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
1142
+ const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
856
1143
  const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
857
1144
  return {
858
1145
  access_token: await this.testkit.m2mToken({
@@ -888,7 +1175,7 @@ var AuthorizationServer = class {
888
1175
  }
889
1176
  if (pending.codeChallenge) {
890
1177
  const verifier = form.code_verifier ?? "";
891
- const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash2("sha256").update(verifier).digest("base64url");
1178
+ const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
892
1179
  if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
893
1180
  throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
894
1181
  }
@@ -918,7 +1205,8 @@ var AuthorizationServer = class {
918
1205
  scopes: grant.scope,
919
1206
  clientId: grant.clientId,
920
1207
  audience: grant.audience.length > 0 ? grant.audience : void 0,
921
- authTime: grant.authTime
1208
+ authTime: grant.authTime,
1209
+ featureFlags: featureFlagsFor(this.seed, scenario2.organization?.code ?? null)
922
1210
  }),
923
1211
  expires_in: this.testkit.accessTokenLifetime,
924
1212
  scope: grant.scope.join(" "),
@@ -985,6 +1273,7 @@ var AuthorizationServer = class {
985
1273
  const user = createKindeUser({ email: ref.toLowerCase() });
986
1274
  if (!this.signedUpUsers.has(user.id)) {
987
1275
  this.signedUpUsers.set(user.id, user);
1276
+ if (this.directory) this.seed.users.push(user);
988
1277
  this.emit("user.created", user);
989
1278
  }
990
1279
  return this.signedUpUsers.get(user.id);
@@ -1072,7 +1361,7 @@ function isHttpUrl(value) {
1072
1361
  }
1073
1362
  }
1074
1363
  function randomToken() {
1075
- return randomBytes(32).toString("base64url");
1364
+ return randomBytes2(32).toString("base64url");
1076
1365
  }
1077
1366
  function safeEqual(a, b) {
1078
1367
  const left = Buffer.from(a);
@@ -1096,6 +1385,687 @@ function sendJson(res, status, body) {
1096
1385
  res.end(JSON.stringify(body));
1097
1386
  }
1098
1387
 
1388
+ // src/account.ts
1389
+ var DEFAULT_PAGE_SIZE = 10;
1390
+ var AccountApi = class {
1391
+ constructor(testkit, directory) {
1392
+ this.testkit = testkit;
1393
+ this.directory = directory;
1394
+ }
1395
+ testkit;
1396
+ directory;
1397
+ async handle(req, res, url) {
1398
+ if (!url.pathname.startsWith("/account_api/v1/")) return false;
1399
+ if ((req.method ?? "GET") !== "GET") {
1400
+ sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
1401
+ return true;
1402
+ }
1403
+ const header = req.headers.authorization ?? "";
1404
+ let token;
1405
+ try {
1406
+ if (!header.startsWith("Bearer ")) throw new Error("missing");
1407
+ token = await this.testkit.verify(header.slice(7));
1408
+ } catch {
1409
+ sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
1410
+ return true;
1411
+ }
1412
+ if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
1413
+ sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
1414
+ return true;
1415
+ }
1416
+ const userId = token.sub;
1417
+ const orgCode = typeof token.org_code === "string" ? token.org_code : null;
1418
+ const path = url.pathname.slice("/account_api/v1/".length);
1419
+ const d = this.directory;
1420
+ const membership = orgCode ? d.membership(userId, orgCode) : void 0;
1421
+ if (path === "permissions") {
1422
+ const items = effectivePermissions(d.seed, membership).map((key) => {
1423
+ const p = d.ensurePermission(key);
1424
+ return { id: p.id, name: p.name, key: p.key };
1425
+ });
1426
+ sendPage(res, url, "permissions", items, { org_code: orgCode });
1427
+ return true;
1428
+ }
1429
+ if (path.startsWith("permission/")) {
1430
+ const key = decodeURIComponent(path.slice("permission/".length));
1431
+ sendJson2(res, 200, {
1432
+ data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
1433
+ });
1434
+ return true;
1435
+ }
1436
+ if (path === "roles") {
1437
+ const items = (membership?.roles ?? []).map((key) => {
1438
+ const r = d.ensureRole(key);
1439
+ return { id: r.id, name: r.name, key: r.key };
1440
+ });
1441
+ sendPage(res, url, "roles", items, { org_code: orgCode });
1442
+ return true;
1443
+ }
1444
+ if (path === "feature_flags") {
1445
+ const items = d.seed.featureFlags.map((flag) => ({
1446
+ id: flag.id,
1447
+ name: flag.name,
1448
+ key: flag.key,
1449
+ type: flag.type,
1450
+ value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
1451
+ }));
1452
+ sendPage(res, url, "feature_flags", items, {});
1453
+ return true;
1454
+ }
1455
+ if (path === "properties") {
1456
+ const values = d.seed.userProperties[userId] ?? {};
1457
+ const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
1458
+ sendPage(res, url, "properties", items, {});
1459
+ return true;
1460
+ }
1461
+ if (path === "entitlements" || path.startsWith("entitlement")) {
1462
+ const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
1463
+ const entitlements = (plan?.entitlements ?? []).map((e) => ({
1464
+ id: e.id,
1465
+ fixed_charge: e.fixedCharge,
1466
+ price_name: e.priceName,
1467
+ unit_amount: e.unitAmount,
1468
+ feature_key: e.featureKey,
1469
+ feature_name: e.featureName,
1470
+ entitlement_limit_max: e.limitMax,
1471
+ entitlement_limit_min: e.limitMin
1472
+ }));
1473
+ if (path === "entitlements") {
1474
+ const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
1475
+ sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
1476
+ return true;
1477
+ }
1478
+ const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
1479
+ const entitlement = entitlements.find((e) => e.feature_key === key);
1480
+ if (!entitlement) {
1481
+ sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
1482
+ } else {
1483
+ sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
1484
+ }
1485
+ return true;
1486
+ }
1487
+ if (path === "portal_link") {
1488
+ sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
1489
+ return true;
1490
+ }
1491
+ sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
1492
+ return true;
1493
+ }
1494
+ };
1495
+ function sendPage(res, url, field, items, extra) {
1496
+ const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
1497
+ const after = url.searchParams.get("starting_after");
1498
+ const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
1499
+ const page = items.slice(start, start + size);
1500
+ const hasMore = start + size < items.length;
1501
+ sendJson2(res, 200, {
1502
+ data: { ...extra, [field]: page },
1503
+ metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
1504
+ });
1505
+ }
1506
+ function errors(code, message) {
1507
+ return { errors: [{ code, message }] };
1508
+ }
1509
+ function sendJson2(res, status, body) {
1510
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1511
+ res.end(JSON.stringify(body));
1512
+ }
1513
+
1514
+ // src/directory.ts
1515
+ import { randomBytes as randomBytes3 } from "crypto";
1516
+ var Directory = class {
1517
+ constructor(seed) {
1518
+ this.seed = seed;
1519
+ this.snapshot = JSON.stringify(seed);
1520
+ }
1521
+ seed;
1522
+ userMeta = /* @__PURE__ */ new Map();
1523
+ orgMeta = /* @__PURE__ */ new Map();
1524
+ snapshot;
1525
+ restore() {
1526
+ const original = JSON.parse(this.snapshot);
1527
+ for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
1528
+ this.seed[key].splice(0, this.seed[key].length, ...original[key]);
1529
+ }
1530
+ this.userMeta.clear();
1531
+ this.orgMeta.clear();
1532
+ }
1533
+ user(id) {
1534
+ return this.seed.users.find((user) => user.id === id);
1535
+ }
1536
+ meta(user) {
1537
+ let meta = this.userMeta.get(user.id);
1538
+ if (!meta) {
1539
+ meta = {
1540
+ providedId: null,
1541
+ isSuspended: false,
1542
+ isPasswordResetRequested: false,
1543
+ createdOn: (/* @__PURE__ */ new Date()).toISOString(),
1544
+ totalSignIns: 0,
1545
+ lastSignedIn: null
1546
+ };
1547
+ this.userMeta.set(user.id, meta);
1548
+ }
1549
+ return meta;
1550
+ }
1551
+ isSuspended(userId) {
1552
+ return this.userMeta.get(userId)?.isSuspended ?? false;
1553
+ }
1554
+ recordSignIn(user, organizationCode) {
1555
+ const meta = this.meta(user);
1556
+ meta.totalSignIns += 1;
1557
+ meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
1558
+ void organizationCode;
1559
+ }
1560
+ createUser(input) {
1561
+ const user = createKindeUser({
1562
+ id: `kp_${randomBytes3(16).toString("hex")}`,
1563
+ email: input.email ?? null,
1564
+ givenName: input.givenName ?? null,
1565
+ familyName: input.familyName ?? null,
1566
+ picture: input.picture ?? null
1567
+ });
1568
+ this.seed.users.push(user);
1569
+ this.meta(user).providedId = input.providedId ?? null;
1570
+ return user;
1571
+ }
1572
+ deleteUser(id) {
1573
+ const index = this.seed.users.findIndex((user) => user.id === id);
1574
+ if (index < 0) return false;
1575
+ this.seed.users.splice(index, 1);
1576
+ for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
1577
+ if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
1578
+ }
1579
+ this.userMeta.delete(id);
1580
+ return true;
1581
+ }
1582
+ organization(code) {
1583
+ return this.seed.organizations.find((org) => org.code === code);
1584
+ }
1585
+ orgInfo(org) {
1586
+ let meta = this.orgMeta.get(org.code);
1587
+ if (!meta) {
1588
+ meta = {
1589
+ externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
1590
+ handle: slug(org.name),
1591
+ createdOn: (/* @__PURE__ */ new Date()).toISOString(),
1592
+ isAllowRegistrations: false
1593
+ };
1594
+ this.orgMeta.set(org.code, meta);
1595
+ }
1596
+ return meta;
1597
+ }
1598
+ createOrganization(input) {
1599
+ const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
1600
+ this.seed.organizations.push(org);
1601
+ const meta = this.orgInfo(org);
1602
+ meta.externalId = input.externalId ?? null;
1603
+ if (input.handle) meta.handle = input.handle;
1604
+ return org;
1605
+ }
1606
+ deleteOrganization(code) {
1607
+ const index = this.seed.organizations.findIndex((org) => org.code === code);
1608
+ if (index < 0) return false;
1609
+ this.seed.organizations.splice(index, 1);
1610
+ for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
1611
+ if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
1612
+ }
1613
+ this.orgMeta.delete(code);
1614
+ return true;
1615
+ }
1616
+ membership(userId, organizationCode) {
1617
+ return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
1618
+ }
1619
+ addMembership(userId, organizationCode, roles = [], permissions = []) {
1620
+ const existing = this.membership(userId, organizationCode);
1621
+ if (existing) return existing;
1622
+ const membership = createMembership({ userId, organizationCode, roles, permissions });
1623
+ this.seed.memberships.push(membership);
1624
+ for (const key of roles) this.ensureRole(key);
1625
+ for (const key of permissions) this.ensurePermission(key);
1626
+ return membership;
1627
+ }
1628
+ removeMembership(userId, organizationCode) {
1629
+ const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
1630
+ if (index < 0) return false;
1631
+ this.seed.memberships.splice(index, 1);
1632
+ return true;
1633
+ }
1634
+ role(idOrKey) {
1635
+ return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
1636
+ }
1637
+ permission(idOrKey) {
1638
+ return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
1639
+ }
1640
+ ensureRole(key, extra = {}) {
1641
+ const existing = this.role(key);
1642
+ if (existing) return existing;
1643
+ const role = roleRecord(key, extra);
1644
+ this.seed.roles.push(role);
1645
+ return role;
1646
+ }
1647
+ ensurePermission(key, extra = {}) {
1648
+ const existing = this.permission(key);
1649
+ if (existing) return existing;
1650
+ const permission = permissionRecord(key, extra);
1651
+ this.seed.permissions.push(permission);
1652
+ return permission;
1653
+ }
1654
+ deleteRole(id) {
1655
+ const role = this.role(id);
1656
+ if (!role) return void 0;
1657
+ this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
1658
+ for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
1659
+ return role;
1660
+ }
1661
+ deletePermission(id) {
1662
+ const permission = this.permission(id);
1663
+ if (!permission) return void 0;
1664
+ this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
1665
+ for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
1666
+ for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
1667
+ return permission;
1668
+ }
1669
+ };
1670
+
1671
+ // src/management.ts
1672
+ var OK = { code: "OK", message: "Success" };
1673
+ var DEFAULT_PAGE_SIZE2 = 10;
1674
+ var MAX_PAGE_SIZE = 500;
1675
+ var ManagementApi = class {
1676
+ constructor(testkit, directory, webhooks) {
1677
+ this.testkit = testkit;
1678
+ this.directory = directory;
1679
+ this.webhooks = webhooks;
1680
+ this.register();
1681
+ }
1682
+ testkit;
1683
+ directory;
1684
+ webhooks;
1685
+ routes = [];
1686
+ async handle(req, res, url, readBody) {
1687
+ if (!url.pathname.startsWith("/api/v1/")) return false;
1688
+ const method = req.method ?? "GET";
1689
+ const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
1690
+ if (!route) {
1691
+ sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
1692
+ return true;
1693
+ }
1694
+ const token = await this.authenticate(req.headers.authorization);
1695
+ if ("error" in token) {
1696
+ sendJson3(res, 403, errors2(token.code, token.error));
1697
+ return true;
1698
+ }
1699
+ const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
1700
+ if (granted.length > 0 && !granted.includes(route.scope)) {
1701
+ sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
1702
+ return true;
1703
+ }
1704
+ const match = route.pattern.exec(url.pathname);
1705
+ const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
1706
+ const body = method === "GET" || method === "DELETE" ? {} : await readBody();
1707
+ const [status, payload] = await route.handler({ params, query: url.searchParams, body });
1708
+ sendJson3(res, status, payload);
1709
+ return true;
1710
+ }
1711
+ async authenticate(header) {
1712
+ if (!header?.startsWith("Bearer ")) {
1713
+ return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
1714
+ }
1715
+ let payload;
1716
+ try {
1717
+ payload = await this.testkit.verify(header.slice(7));
1718
+ } catch {
1719
+ return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
1720
+ }
1721
+ const audience = `${this.testkit.issuer}/api`;
1722
+ const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
1723
+ if (!aud.includes(audience)) {
1724
+ return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
1725
+ }
1726
+ if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
1727
+ return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
1728
+ }
1729
+ return { payload };
1730
+ }
1731
+ route(method, path, scope, handler) {
1732
+ const keys = [];
1733
+ const pattern = new RegExp(
1734
+ `^${path.replace(/\{(\w+)\}/g, (_, key) => {
1735
+ keys.push(key);
1736
+ return "([^/]+)";
1737
+ })}$`
1738
+ );
1739
+ this.routes.push({ method, pattern, keys, scope, handler });
1740
+ }
1741
+ register() {
1742
+ const d = this.directory;
1743
+ this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
1744
+ let users = [...d.seed.users];
1745
+ const userId = query.get("user_id");
1746
+ const email = query.get("email")?.toLowerCase();
1747
+ if (userId) users = users.filter((u) => u.id === userId);
1748
+ if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
1749
+ const page = paginate(users, query);
1750
+ return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
1751
+ });
1752
+ this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
1753
+ const user = d.user(query.get("id") ?? "");
1754
+ return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
1755
+ });
1756
+ this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
1757
+ const profile = body.profile ?? {};
1758
+ const identities = Array.isArray(body.identities) ? body.identities : [];
1759
+ const emailIdentity = identities.find((i) => i.type === "email");
1760
+ const email = (emailIdentity?.details ?? {}).email;
1761
+ if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
1762
+ return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
1763
+ }
1764
+ const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
1765
+ if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
1766
+ const user = d.createUser({
1767
+ email: typeof email === "string" ? email : null,
1768
+ givenName: str(profile.given_name),
1769
+ familyName: str(profile.family_name),
1770
+ picture: str(profile.picture),
1771
+ providedId: str(body.provided_id)
1772
+ });
1773
+ if (orgCode) d.addMembership(user.id, orgCode);
1774
+ this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
1775
+ return [
1776
+ 200,
1777
+ { id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
1778
+ ];
1779
+ });
1780
+ this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
1781
+ const user = d.user(query.get("id") ?? "");
1782
+ if (!user) return notFound("USER_INVALID", "No user has that id.");
1783
+ if (typeof body.given_name === "string") user.givenName = body.given_name;
1784
+ if (typeof body.family_name === "string") user.familyName = body.family_name;
1785
+ if (typeof body.picture === "string") user.picture = body.picture;
1786
+ const meta = d.meta(user);
1787
+ if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
1788
+ if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
1789
+ if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
1790
+ this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
1791
+ return [
1792
+ 200,
1793
+ {
1794
+ id: user.id,
1795
+ given_name: user.givenName,
1796
+ family_name: user.familyName,
1797
+ email: user.email,
1798
+ is_suspended: meta.isSuspended,
1799
+ is_password_reset_requested: meta.isPasswordResetRequested,
1800
+ picture: user.picture
1801
+ }
1802
+ ];
1803
+ });
1804
+ this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
1805
+ const id = query.get("id") ?? "";
1806
+ if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
1807
+ this.webhooks.emit("user.deleted", { user: { id } });
1808
+ return [200, OK];
1809
+ });
1810
+ this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
1811
+ const page = paginate(d.seed.organizations, query);
1812
+ return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
1813
+ });
1814
+ this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
1815
+ const org = d.organization(query.get("code") ?? "");
1816
+ if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1817
+ const meta = d.orgInfo(org);
1818
+ return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
1819
+ });
1820
+ this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
1821
+ if (typeof body.name !== "string" || body.name.trim() === "") {
1822
+ return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
1823
+ }
1824
+ const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
1825
+ if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
1826
+ this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
1827
+ return [200, { ...OK, organization: { code: org.code } }];
1828
+ });
1829
+ this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
1830
+ const org = d.organization(params.org_code);
1831
+ if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1832
+ const meta = d.orgInfo(org);
1833
+ if (typeof body.name === "string") org.name = body.name;
1834
+ if (typeof body.external_id === "string") meta.externalId = body.external_id;
1835
+ if (typeof body.handle === "string") meta.handle = body.handle;
1836
+ if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
1837
+ this.webhooks.emit("organization.updated", {
1838
+ organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
1839
+ });
1840
+ return [200, OK];
1841
+ });
1842
+ this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
1843
+ if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1844
+ this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
1845
+ return [200, OK];
1846
+ });
1847
+ this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
1848
+ if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1849
+ 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);
1850
+ const page = paginate(members, query);
1851
+ return [
1852
+ 200,
1853
+ {
1854
+ ...OK,
1855
+ organization_users: page.items.map(({ membership, user }) => ({
1856
+ id: user.id,
1857
+ email: user.email,
1858
+ full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
1859
+ last_name: user.familyName,
1860
+ first_name: user.givenName,
1861
+ picture: user.picture,
1862
+ joined_on: d.meta(user).createdOn,
1863
+ last_accessed_on: d.meta(user).lastSignedIn,
1864
+ is_suspended: d.meta(user).isSuspended,
1865
+ roles: [...membership.roles]
1866
+ })),
1867
+ next_token: page.nextToken
1868
+ }
1869
+ ];
1870
+ });
1871
+ this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
1872
+ if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1873
+ const users = Array.isArray(body.users) ? body.users : [];
1874
+ const added = [];
1875
+ const blocked = [];
1876
+ for (const entry of users) {
1877
+ const id = typeof entry.id === "string" ? entry.id : "";
1878
+ if (!d.user(id)) {
1879
+ blocked.push(id);
1880
+ continue;
1881
+ }
1882
+ d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
1883
+ added.push(id);
1884
+ }
1885
+ return [200, { ...OK, users_added: added, users_blocked: blocked }];
1886
+ });
1887
+ this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
1888
+ 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}.`);
1889
+ });
1890
+ this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
1891
+ const membership = d.membership(params.user_id, params.org_code);
1892
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1893
+ const roles = membership.roles.map((key) => d.ensureRole(key));
1894
+ return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
1895
+ });
1896
+ this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
1897
+ const membership = d.membership(params.user_id, params.org_code);
1898
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1899
+ const role = d.role(str(body.role_id) ?? "");
1900
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1901
+ if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
1902
+ return [200, OK];
1903
+ });
1904
+ this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
1905
+ const membership = d.membership(params.user_id, params.org_code);
1906
+ const role = d.role(params.role_id);
1907
+ if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
1908
+ membership.roles = membership.roles.filter((key) => key !== role.key);
1909
+ return [200, OK];
1910
+ });
1911
+ this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
1912
+ const membership = d.membership(params.user_id, params.org_code);
1913
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1914
+ const permissions = effectivePermissions(d.seed, membership).map((key) => {
1915
+ const permission = d.ensurePermission(key);
1916
+ const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
1917
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
1918
+ });
1919
+ return [200, { ...OK, permissions }];
1920
+ });
1921
+ this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
1922
+ const membership = d.membership(params.user_id, params.org_code);
1923
+ if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1924
+ const permission = d.permission(str(body.permission_id) ?? "");
1925
+ if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
1926
+ if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
1927
+ return [200, OK];
1928
+ });
1929
+ this.route(
1930
+ "DELETE",
1931
+ "/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
1932
+ "delete:organization_user_permissions",
1933
+ ({ params }) => {
1934
+ const membership = d.membership(params.user_id, params.org_code);
1935
+ const permission = d.permission(params.permission_id);
1936
+ if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
1937
+ membership.permissions = membership.permissions.filter((key) => key !== permission.key);
1938
+ return [200, OK];
1939
+ }
1940
+ );
1941
+ this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
1942
+ const page = paginate(d.seed.roles, query);
1943
+ return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
1944
+ });
1945
+ this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
1946
+ const key = str(body.key);
1947
+ if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
1948
+ if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
1949
+ const role = d.ensureRole(key, {
1950
+ name: str(body.name) ?? void 0,
1951
+ description: str(body.description) ?? void 0,
1952
+ isDefault: body.is_default_role === true
1953
+ });
1954
+ this.webhooks.emit("role.created", {
1955
+ role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
1956
+ });
1957
+ return [201, { ...OK, role: { id: role.id } }];
1958
+ });
1959
+ this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
1960
+ const role = d.role(params.role_id);
1961
+ return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
1962
+ });
1963
+ this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
1964
+ const role = d.deleteRole(params.role_id);
1965
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1966
+ this.webhooks.emit("role.deleted", { role: { id: role.id } });
1967
+ return [200, OK];
1968
+ });
1969
+ this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
1970
+ const role = d.role(params.role_id);
1971
+ if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1972
+ return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
1973
+ });
1974
+ this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
1975
+ const page = paginate(d.seed.permissions, query);
1976
+ return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
1977
+ });
1978
+ this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
1979
+ const key = str(body.key);
1980
+ if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
1981
+ if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
1982
+ const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
1983
+ this.webhooks.emit("permission.created", {
1984
+ permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
1985
+ });
1986
+ return [201, OK];
1987
+ });
1988
+ this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
1989
+ const permission = d.deletePermission(params.permission_id);
1990
+ if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
1991
+ this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
1992
+ return [200, OK];
1993
+ });
1994
+ }
1995
+ userListItem(user) {
1996
+ const meta = this.directory.meta(user);
1997
+ return {
1998
+ id: user.id,
1999
+ provided_id: meta.providedId,
2000
+ email: user.email,
2001
+ phone: null,
2002
+ username: null,
2003
+ last_name: user.familyName,
2004
+ first_name: user.givenName,
2005
+ is_suspended: meta.isSuspended,
2006
+ picture: user.picture,
2007
+ total_sign_ins: meta.totalSignIns,
2008
+ failed_sign_ins: 0,
2009
+ last_signed_in: meta.lastSignedIn,
2010
+ created_on: meta.createdOn,
2011
+ organizations: this.organizationsOf(user),
2012
+ identities: user.email ? [{ type: "email", identity: user.email }] : []
2013
+ };
2014
+ }
2015
+ userDetail(user) {
2016
+ const { email, ...rest } = this.userListItem(user);
2017
+ return { ...rest, preferred_email: email };
2018
+ }
2019
+ organizationsOf(user) {
2020
+ return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
2021
+ }
2022
+ organizationItem(org) {
2023
+ const meta = this.directory.orgInfo(org);
2024
+ return {
2025
+ code: org.code,
2026
+ name: org.name,
2027
+ handle: meta.handle,
2028
+ is_default: false,
2029
+ external_id: meta.externalId,
2030
+ is_auto_membership_enabled: false
2031
+ };
2032
+ }
2033
+ organizationEvent(org) {
2034
+ const meta = this.directory.orgInfo(org);
2035
+ return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
2036
+ }
2037
+ roleItem(role) {
2038
+ return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
2039
+ }
2040
+ permissionItem(permission) {
2041
+ return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
2042
+ }
2043
+ };
2044
+ function paginate(items, query) {
2045
+ const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
2046
+ const token = query.get("next_token");
2047
+ const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
2048
+ const page = items.slice(offset, offset + size);
2049
+ const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
2050
+ return { items: page, nextToken: next };
2051
+ }
2052
+ function errors2(code, message) {
2053
+ return { errors: [{ code, message }] };
2054
+ }
2055
+ function notFound(code, message) {
2056
+ return [404, errors2(code, message)];
2057
+ }
2058
+ function str(value) {
2059
+ return typeof value === "string" ? value : null;
2060
+ }
2061
+ function strings(value) {
2062
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
2063
+ }
2064
+ function sendJson3(res, status, body) {
2065
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2066
+ res.end(JSON.stringify(body));
2067
+ }
2068
+
1099
2069
  // src/failures.ts
1100
2070
  var MAX_DELAY_MS = 6e4;
1101
2071
  var FailureInjector = class {
@@ -1177,7 +2147,7 @@ function validate(rule) {
1177
2147
  }
1178
2148
 
1179
2149
  // src/webhooks.ts
1180
- import { randomBytes as randomBytes2 } from "crypto";
2150
+ import { randomBytes as randomBytes4 } from "crypto";
1181
2151
  var WEBHOOK_EVENT_TYPES = [
1182
2152
  "user.created",
1183
2153
  "user.updated",
@@ -1260,7 +2230,7 @@ var WebhookDispatcher = class {
1260
2230
  const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
1261
2231
  const event = {
1262
2232
  data: options.data ?? this.buildData(options),
1263
- event_id: `event_${randomBytes2(16).toString("hex")}`,
2233
+ event_id: `event_${randomBytes4(16).toString("hex")}`,
1264
2234
  event_timestamp: timestamp,
1265
2235
  source: options.source ?? "admin",
1266
2236
  timestamp,
@@ -1293,7 +2263,7 @@ var WebhookDispatcher = class {
1293
2263
  options.invalid === "stale" ? void 0 : options.invalid
1294
2264
  );
1295
2265
  const jobs = targets.flatMap((target) => {
1296
- const webhookId = `wh_${randomBytes2(12).toString("hex")}`;
2266
+ const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
1297
2267
  return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
1298
2268
  });
1299
2269
  return Promise.all(jobs);
@@ -1374,6 +2344,13 @@ var WebhookDispatcher = class {
1374
2344
  );
1375
2345
  }
1376
2346
  }
2347
+ emit(type, data, source = "api") {
2348
+ if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
2349
+ void this.send({ type, data, source }).catch(() => void 0);
2350
+ }
2351
+ userEventData(user) {
2352
+ return this.userPayload(user);
2353
+ }
1377
2354
  emitForUser(type, user) {
1378
2355
  if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
1379
2356
  const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
@@ -1438,7 +2415,7 @@ function isHttpUrl2(value) {
1438
2415
  }
1439
2416
  }
1440
2417
  function sleep(ms) {
1441
- return new Promise((resolve) => setTimeout(resolve, ms));
2418
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1442
2419
  }
1443
2420
 
1444
2421
  // src/server.ts
@@ -1456,30 +2433,36 @@ async function startKindeTestkit(options = {}) {
1456
2433
  const seed = resolveSeed(options.seed ?? {});
1457
2434
  const failures = new FailureInjector();
1458
2435
  let ready;
1459
- const testkitReady = new Promise((resolve) => ready = resolve);
1460
- const server = createServer((req, res) => {
2436
+ const testkitReady = new Promise((resolve2) => ready = resolve2);
2437
+ const listener = (req, res) => {
1461
2438
  testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
1462
- });
1463
- await new Promise((resolve, reject) => {
2439
+ };
2440
+ const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
2441
+ const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
2442
+ await new Promise((resolve2, reject) => {
1464
2443
  server.once("error", reject);
1465
- server.listen(options.port ?? 4400, host, () => resolve());
2444
+ server.listen(options.port ?? 4400, host, () => resolve2());
1466
2445
  });
1467
2446
  const { port } = server.address();
1468
2447
  const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
1469
- const url = `http://${urlHost}:${port}`;
2448
+ const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
1470
2449
  const testkit = await KindeTestkit.create({
1471
2450
  issuer: options.issuer ?? options.seed?.issuer ?? url,
1472
2451
  audience: options.audience ?? options.seed?.audience,
1473
2452
  clientId: options.clientId ?? options.seed?.clientId
1474
2453
  });
2454
+ const directory = new Directory(seed);
1475
2455
  const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
1476
- const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
2456
+ const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
2457
+ const management = new ManagementApi(testkit, directory, webhooks);
2458
+ const account = new AccountApi(testkit, directory);
1477
2459
  const reset = () => {
1478
2460
  auth.reset();
1479
2461
  failures.clear();
1480
2462
  webhooks.reset();
2463
+ directory.restore();
1481
2464
  };
1482
- ready({ testkit, auth, seed, failures, webhooks, reset });
2465
+ ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
1483
2466
  return {
1484
2467
  url,
1485
2468
  issuer: testkit.issuer,
@@ -1489,10 +2472,12 @@ async function startKindeTestkit(options = {}) {
1489
2472
  seed,
1490
2473
  failures,
1491
2474
  webhooks,
2475
+ directory,
2476
+ certificatePath: certificate?.certPath ?? null,
1492
2477
  reset,
1493
- close: () => new Promise((resolve, reject) => {
2478
+ close: () => new Promise((resolve2, reject) => {
1494
2479
  server.closeAllConnections();
1495
- server.close((error) => error ? reject(error) : resolve());
2480
+ server.close((error) => error ? reject(error) : resolve2());
1496
2481
  })
1497
2482
  };
1498
2483
  }
@@ -1505,68 +2490,77 @@ async function handle(req, res, context) {
1505
2490
  const failure = failures.take(method, pathname);
1506
2491
  if (failure) {
1507
2492
  if (failure.hang) return;
1508
- if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
2493
+ if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
1509
2494
  if (failure.status !== null) {
1510
2495
  const headers = {};
1511
2496
  if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
1512
- return sendJson2(res, failure.status, failureBody(failure.status), headers);
2497
+ return sendJson4(res, failure.status, failureBody(failure.status), headers);
1513
2498
  }
1514
2499
  }
1515
2500
  }
1516
2501
  if (await auth.handle(req, res, url, () => readForm(req))) return;
2502
+ if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
2503
+ if (await context.account.handle(req, res, url)) return;
2504
+ if (method === "GET" && pathname === "/testkit/portal") {
2505
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2506
+ res.end(
2507
+ `<!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>`
2508
+ );
2509
+ return;
2510
+ }
1517
2511
  if (method === "GET" && pathname === "/.well-known/openid-configuration") {
1518
- return sendJson2(res, 200, discovery(testkit));
2512
+ return sendJson4(res, 200, discovery(testkit));
1519
2513
  }
1520
2514
  if (method === "GET" && JWKS_PATHS.has(pathname)) {
1521
- return sendJson2(res, 200, testkit.jwks());
2515
+ return sendJson4(res, 200, testkit.jwks());
1522
2516
  }
1523
2517
  if (method === "GET" && pathname === "/testkit/health") {
1524
- return sendJson2(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
2518
+ return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
1525
2519
  }
1526
- if (method === "GET" && pathname === "/testkit/users") return sendJson2(res, 200, seed.users);
2520
+ if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
1527
2521
  if (method === "GET" && pathname === "/testkit/organizations") {
1528
- return sendJson2(res, 200, seed.organizations);
2522
+ return sendJson4(res, 200, seed.organizations);
1529
2523
  }
1530
2524
  if (method === "GET" && pathname === "/testkit/memberships") {
1531
- return sendJson2(res, 200, seed.memberships);
2525
+ return sendJson4(res, 200, seed.memberships);
1532
2526
  }
1533
- if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
2527
+ if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
1534
2528
  if (method === "POST" && pathname === "/testkit/failures") {
1535
- return sendJson2(res, 201, failures.add(await readJson(req)));
2529
+ return sendJson4(res, 201, failures.add(await readJson(req)));
1536
2530
  }
1537
2531
  if (method === "DELETE" && pathname === "/testkit/failures") {
1538
2532
  failures.clear();
1539
- return sendJson2(res, 200, { ok: true });
2533
+ return sendJson4(res, 200, { ok: true });
1540
2534
  }
1541
2535
  if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
1542
2536
  const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
1543
- return sendJson2(res, removed ? 200 : 404, { ok: removed });
2537
+ return sendJson4(res, removed ? 200 : 404, { ok: removed });
1544
2538
  }
1545
2539
  if (method === "POST" && pathname === "/testkit/webhooks") {
1546
- return sendJson2(res, 200, await webhooks.send(await readJson(req)));
2540
+ return sendJson4(res, 200, await webhooks.send(await readJson(req)));
1547
2541
  }
1548
2542
  if (method === "GET" && pathname === "/testkit/webhooks/types") {
1549
- return sendJson2(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
2543
+ return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
1550
2544
  }
1551
- if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson2(res, 200, webhooks.deliveries());
1552
- if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson2(res, 200, webhooks.listEndpoints());
2545
+ if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
2546
+ if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
1553
2547
  if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
1554
- return sendJson2(res, 201, webhooks.addEndpoint(await readJson(req)));
2548
+ return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
1555
2549
  }
1556
2550
  if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
1557
2551
  const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
1558
- return sendJson2(res, removed ? 200 : 404, { ok: removed });
2552
+ return sendJson4(res, removed ? 200 : 404, { ok: removed });
1559
2553
  }
1560
2554
  if (method === "POST" && pathname === "/testkit/reset") {
1561
2555
  context.reset();
1562
- return sendJson2(res, 200, { ok: true });
2556
+ return sendJson4(res, 200, { ok: true });
1563
2557
  }
1564
2558
  if (method === "POST" && pathname === "/testkit/token") {
1565
2559
  const body = await readJson(req);
1566
2560
  const accessToken = await issueToken(testkit, seed, body);
1567
- return sendJson2(res, 200, { access_token: accessToken, token_type: "Bearer" });
2561
+ return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
1568
2562
  }
1569
- return sendJson2(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
2563
+ return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
1570
2564
  }
1571
2565
  function discovery(testkit) {
1572
2566
  const base = testkit.issuer;
@@ -1625,7 +2619,11 @@ async function issueToken(testkit, seed, body) {
1625
2619
  });
1626
2620
  if (permissions) scenario2.permissions = permissions;
1627
2621
  if (roles) scenario2.roles = roles;
1628
- return await testkit.tokenFor(scenario2, { expiresIn, invalid: invalid2 });
2622
+ return await testkit.tokenFor(scenario2, {
2623
+ expiresIn,
2624
+ invalid: invalid2,
2625
+ featureFlags: featureFlagsFor(seed, scenario2.organization?.code ?? null)
2626
+ });
1629
2627
  }
1630
2628
  const options = {
1631
2629
  subject: optionalString(input, "subject"),
@@ -1690,7 +2688,7 @@ async function readText(req) {
1690
2688
  }
1691
2689
  return Buffer.concat(chunks).toString("utf8").trim();
1692
2690
  }
1693
- function sendJson2(res, status, body, headers = {}) {
2691
+ function sendJson4(res, status, body, headers = {}) {
1694
2692
  res.writeHead(status, {
1695
2693
  "content-type": "application/json; charset=utf-8",
1696
2694
  "cache-control": "no-store",
@@ -1704,10 +2702,10 @@ function sendError(res, error) {
1704
2702
  return;
1705
2703
  }
1706
2704
  if (error instanceof TestkitError) {
1707
- sendJson2(res, 400, { error: error.code, error_description: error.message, details: error.details });
2705
+ sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
1708
2706
  return;
1709
2707
  }
1710
- sendJson2(res, 500, {
2708
+ sendJson4(res, 500, {
1711
2709
  error: "server_error",
1712
2710
  error_description: error instanceof Error ? error.message : String(error)
1713
2711
  });
@@ -1854,6 +2852,15 @@ async function runDoctor(options) {
1854
2852
  } else {
1855
2853
  checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
1856
2854
  }
2855
+ if (issuer?.startsWith("https://")) {
2856
+ checks.push(
2857
+ env.NODE_EXTRA_CA_CERTS ? { name: "NODE_EXTRA_CA_CERTS", status: "pass", detail: `${env.NODE_EXTRA_CA_CERTS}.` } : {
2858
+ name: "NODE_EXTRA_CA_CERTS",
2859
+ status: "warn",
2860
+ 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."
2861
+ }
2862
+ );
2863
+ }
1857
2864
  const site = env.KINDE_SITE_URL;
1858
2865
  if (!site) {
1859
2866
  checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
@@ -1886,6 +2893,7 @@ export {
1886
2893
  DEFAULT_ISSUER,
1887
2894
  DEFAULT_M2M_CLIENT_ID,
1888
2895
  DEFAULT_SCOPES,
2896
+ Directory,
1889
2897
  FailureInjector,
1890
2898
  INVALID_TOKEN_KINDS,
1891
2899
  KindeTestkit,
@@ -1896,7 +2904,9 @@ export {
1896
2904
  createKindeOrganization,
1897
2905
  createKindeToken,
1898
2906
  createKindeUser,
2907
+ createLocalCertificate,
1899
2908
  createMembership,
2909
+ ensureLocalCertificate,
1900
2910
  getDefaultTestkit,
1901
2911
  inspectToken,
1902
2912
  isAuthenticated,