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/CHANGELOG.md +8 -0
- package/README.md +48 -2
- package/dist/cli.js +1177 -124
- package/dist/index.cjs +1124 -111
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +150 -1
- package/dist/index.d.ts +150 -1
- package/dist/index.js +1120 -110
- package/dist/index.js.map +1 -1
- package/dist/vitest.d.ts +82 -0
- package/dist/vitest.js +1108 -110
- package/dist/vitest.js.map +1 -1
- package/package.json +3 -1
package/dist/index.cjs
CHANGED
|
@@ -26,6 +26,7 @@ __export(src_exports, {
|
|
|
26
26
|
DEFAULT_ISSUER: () => DEFAULT_ISSUER,
|
|
27
27
|
DEFAULT_M2M_CLIENT_ID: () => DEFAULT_M2M_CLIENT_ID,
|
|
28
28
|
DEFAULT_SCOPES: () => DEFAULT_SCOPES,
|
|
29
|
+
Directory: () => Directory,
|
|
29
30
|
FailureInjector: () => FailureInjector,
|
|
30
31
|
INVALID_TOKEN_KINDS: () => INVALID_TOKEN_KINDS,
|
|
31
32
|
KindeTestkit: () => KindeTestkit,
|
|
@@ -36,7 +37,9 @@ __export(src_exports, {
|
|
|
36
37
|
createKindeOrganization: () => createKindeOrganization,
|
|
37
38
|
createKindeToken: () => createKindeToken,
|
|
38
39
|
createKindeUser: () => createKindeUser,
|
|
40
|
+
createLocalCertificate: () => createLocalCertificate,
|
|
39
41
|
createMembership: () => createMembership,
|
|
42
|
+
ensureLocalCertificate: () => ensureLocalCertificate,
|
|
40
43
|
getDefaultTestkit: () => getDefaultTestkit,
|
|
41
44
|
inspectToken: () => inspectToken,
|
|
42
45
|
isAuthenticated: () => isAuthenticated,
|
|
@@ -487,8 +490,230 @@ async function createKindeToken(options = {}) {
|
|
|
487
490
|
|
|
488
491
|
// src/server.ts
|
|
489
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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
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
|
+
}
|
|
490
692
|
|
|
491
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
|
+
}
|
|
492
717
|
function resolveSeed(input) {
|
|
493
718
|
const problems = [];
|
|
494
719
|
if (!isRecord(input)) {
|
|
@@ -499,6 +724,10 @@ function resolveSeed(input) {
|
|
|
499
724
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
500
725
|
const rawApplications = listOf(input.applications, "applications", problems);
|
|
501
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);
|
|
502
731
|
const webhooks = [];
|
|
503
732
|
rawWebhooks.forEach((raw, index) => {
|
|
504
733
|
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
@@ -602,7 +831,107 @@ function resolveSeed(input) {
|
|
|
602
831
|
if (problems.length > 0) {
|
|
603
832
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
604
833
|
}
|
|
605
|
-
|
|
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 };
|
|
606
935
|
}
|
|
607
936
|
function findUser(users, ref) {
|
|
608
937
|
const needle = ref.toLowerCase();
|
|
@@ -647,7 +976,7 @@ function seedScenario(seed, ref) {
|
|
|
647
976
|
user,
|
|
648
977
|
organization,
|
|
649
978
|
roles: [...membership?.roles ?? []],
|
|
650
|
-
permissions:
|
|
979
|
+
permissions: effectivePermissions(seed, membership),
|
|
651
980
|
claims: {}
|
|
652
981
|
};
|
|
653
982
|
}
|
|
@@ -662,72 +991,18 @@ function listOf(value, field, problems) {
|
|
|
662
991
|
function isRecord(value) {
|
|
663
992
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
664
993
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
*{box-sizing:border-box}
|
|
674
|
-
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}
|
|
675
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
676
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
677
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
678
|
-
p{margin:0;color:var(--muted)}
|
|
679
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
680
|
-
form{margin:0}
|
|
681
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
682
|
-
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}
|
|
683
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
684
|
-
.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}
|
|
685
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
686
|
-
.list{display:grid;gap:8px}
|
|
687
|
-
.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}
|
|
688
|
-
.option:hover{border-color:var(--muted)}
|
|
689
|
-
.option strong{display:block;font-weight:500}
|
|
690
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
691
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
692
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
693
|
-
`;
|
|
694
|
-
function escapeHtml(value) {
|
|
695
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
696
|
-
}
|
|
697
|
-
function layout(title, body) {
|
|
698
|
-
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>`;
|
|
699
|
-
}
|
|
700
|
-
function displayName(user) {
|
|
701
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
702
|
-
}
|
|
703
|
-
function renderSignIn(options) {
|
|
704
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
705
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
706
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
707
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
708
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
709
|
-
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>`;
|
|
710
|
-
}).join("");
|
|
711
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
712
|
-
return layout(
|
|
713
|
-
"Sign in",
|
|
714
|
-
`<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>`
|
|
715
|
-
);
|
|
716
|
-
}
|
|
717
|
-
function renderOrganizationPicker(options) {
|
|
718
|
-
const choices = options.organizations.map(
|
|
719
|
-
(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>`
|
|
720
|
-
).join("");
|
|
721
|
-
return layout(
|
|
722
|
-
"Choose an organization",
|
|
723
|
-
`<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>`
|
|
724
|
-
);
|
|
725
|
-
}
|
|
726
|
-
function renderMessage(title, message) {
|
|
727
|
-
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;
|
|
728
1002
|
}
|
|
729
1003
|
|
|
730
1004
|
// src/oauth.ts
|
|
1005
|
+
var import_node_crypto4 = require("crypto");
|
|
731
1006
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
732
1007
|
var OAuthError = class extends Error {
|
|
733
1008
|
constructor(status, error, description) {
|
|
@@ -739,14 +1014,16 @@ var OAuthError = class extends Error {
|
|
|
739
1014
|
error;
|
|
740
1015
|
};
|
|
741
1016
|
var AuthorizationServer = class {
|
|
742
|
-
constructor(testkit, seed, emit = () => void 0) {
|
|
1017
|
+
constructor(testkit, seed, emit = () => void 0, directory) {
|
|
743
1018
|
this.testkit = testkit;
|
|
744
1019
|
this.seed = seed;
|
|
745
1020
|
this.emit = emit;
|
|
1021
|
+
this.directory = directory;
|
|
746
1022
|
}
|
|
747
1023
|
testkit;
|
|
748
1024
|
seed;
|
|
749
1025
|
emit;
|
|
1026
|
+
directory;
|
|
750
1027
|
codes = /* @__PURE__ */ new Map();
|
|
751
1028
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
752
1029
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -812,6 +1089,18 @@ var AuthorizationServer = class {
|
|
|
812
1089
|
if (!user) {
|
|
813
1090
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
814
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
|
+
}
|
|
815
1104
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
816
1105
|
const wanted = request.orgCode ?? form.org ?? null;
|
|
817
1106
|
let organizationCode = null;
|
|
@@ -848,7 +1137,7 @@ var AuthorizationServer = class {
|
|
|
848
1137
|
user,
|
|
849
1138
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
850
1139
|
roles: [...membership?.roles ?? []],
|
|
851
|
-
permissions:
|
|
1140
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
852
1141
|
claims: {}
|
|
853
1142
|
};
|
|
854
1143
|
const code = randomToken();
|
|
@@ -864,6 +1153,7 @@ var AuthorizationServer = class {
|
|
|
864
1153
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
865
1154
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
866
1155
|
});
|
|
1156
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
867
1157
|
this.emit("user.authenticated", user);
|
|
868
1158
|
const target = new URL(request.redirectUri);
|
|
869
1159
|
target.searchParams.set("code", code);
|
|
@@ -899,7 +1189,7 @@ var AuthorizationServer = class {
|
|
|
899
1189
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
900
1190
|
}
|
|
901
1191
|
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
902
|
-
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;
|
|
903
1193
|
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
904
1194
|
return {
|
|
905
1195
|
access_token: await this.testkit.m2mToken({
|
|
@@ -935,7 +1225,7 @@ var AuthorizationServer = class {
|
|
|
935
1225
|
}
|
|
936
1226
|
if (pending.codeChallenge) {
|
|
937
1227
|
const verifier = form.code_verifier ?? "";
|
|
938
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier : (0,
|
|
1228
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
|
|
939
1229
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
940
1230
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
941
1231
|
}
|
|
@@ -965,7 +1255,8 @@ var AuthorizationServer = class {
|
|
|
965
1255
|
scopes: grant.scope,
|
|
966
1256
|
clientId: grant.clientId,
|
|
967
1257
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
968
|
-
authTime: grant.authTime
|
|
1258
|
+
authTime: grant.authTime,
|
|
1259
|
+
featureFlags: featureFlagsFor(this.seed, scenario2.organization?.code ?? null)
|
|
969
1260
|
}),
|
|
970
1261
|
expires_in: this.testkit.accessTokenLifetime,
|
|
971
1262
|
scope: grant.scope.join(" "),
|
|
@@ -1032,6 +1323,7 @@ var AuthorizationServer = class {
|
|
|
1032
1323
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
1033
1324
|
if (!this.signedUpUsers.has(user.id)) {
|
|
1034
1325
|
this.signedUpUsers.set(user.id, user);
|
|
1326
|
+
if (this.directory) this.seed.users.push(user);
|
|
1035
1327
|
this.emit("user.created", user);
|
|
1036
1328
|
}
|
|
1037
1329
|
return this.signedUpUsers.get(user.id);
|
|
@@ -1119,12 +1411,12 @@ function isHttpUrl(value) {
|
|
|
1119
1411
|
}
|
|
1120
1412
|
}
|
|
1121
1413
|
function randomToken() {
|
|
1122
|
-
return (0,
|
|
1414
|
+
return (0, import_node_crypto4.randomBytes)(32).toString("base64url");
|
|
1123
1415
|
}
|
|
1124
1416
|
function safeEqual(a, b) {
|
|
1125
1417
|
const left = Buffer.from(a);
|
|
1126
1418
|
const right = Buffer.from(b);
|
|
1127
|
-
return left.length === right.length && (0,
|
|
1419
|
+
return left.length === right.length && (0, import_node_crypto4.timingSafeEqual)(left, right);
|
|
1128
1420
|
}
|
|
1129
1421
|
function redirect(res, location) {
|
|
1130
1422
|
res.writeHead(303, { location, "cache-control": "no-store" });
|
|
@@ -1143,6 +1435,687 @@ function sendJson(res, status, body) {
|
|
|
1143
1435
|
res.end(JSON.stringify(body));
|
|
1144
1436
|
}
|
|
1145
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
|
+
|
|
1146
2119
|
// src/failures.ts
|
|
1147
2120
|
var MAX_DELAY_MS = 6e4;
|
|
1148
2121
|
var FailureInjector = class {
|
|
@@ -1224,7 +2197,7 @@ function validate(rule) {
|
|
|
1224
2197
|
}
|
|
1225
2198
|
|
|
1226
2199
|
// src/webhooks.ts
|
|
1227
|
-
var
|
|
2200
|
+
var import_node_crypto6 = require("crypto");
|
|
1228
2201
|
var WEBHOOK_EVENT_TYPES = [
|
|
1229
2202
|
"user.created",
|
|
1230
2203
|
"user.updated",
|
|
@@ -1307,7 +2280,7 @@ var WebhookDispatcher = class {
|
|
|
1307
2280
|
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1308
2281
|
const event = {
|
|
1309
2282
|
data: options.data ?? this.buildData(options),
|
|
1310
|
-
event_id: `event_${(0,
|
|
2283
|
+
event_id: `event_${(0, import_node_crypto6.randomBytes)(16).toString("hex")}`,
|
|
1311
2284
|
event_timestamp: timestamp,
|
|
1312
2285
|
source: options.source ?? "admin",
|
|
1313
2286
|
timestamp,
|
|
@@ -1340,7 +2313,7 @@ var WebhookDispatcher = class {
|
|
|
1340
2313
|
options.invalid === "stale" ? void 0 : options.invalid
|
|
1341
2314
|
);
|
|
1342
2315
|
const jobs = targets.flatMap((target) => {
|
|
1343
|
-
const webhookId = `wh_${(0,
|
|
2316
|
+
const webhookId = `wh_${(0, import_node_crypto6.randomBytes)(12).toString("hex")}`;
|
|
1344
2317
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1345
2318
|
});
|
|
1346
2319
|
return Promise.all(jobs);
|
|
@@ -1421,6 +2394,13 @@ var WebhookDispatcher = class {
|
|
|
1421
2394
|
);
|
|
1422
2395
|
}
|
|
1423
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
|
+
}
|
|
1424
2404
|
emitForUser(type, user) {
|
|
1425
2405
|
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1426
2406
|
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
@@ -1485,7 +2465,7 @@ function isHttpUrl2(value) {
|
|
|
1485
2465
|
}
|
|
1486
2466
|
}
|
|
1487
2467
|
function sleep(ms) {
|
|
1488
|
-
return new Promise((
|
|
2468
|
+
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1489
2469
|
}
|
|
1490
2470
|
|
|
1491
2471
|
// src/server.ts
|
|
@@ -1503,30 +2483,36 @@ async function startKindeTestkit(options = {}) {
|
|
|
1503
2483
|
const seed = resolveSeed(options.seed ?? {});
|
|
1504
2484
|
const failures = new FailureInjector();
|
|
1505
2485
|
let ready;
|
|
1506
|
-
const testkitReady = new Promise((
|
|
1507
|
-
const
|
|
2486
|
+
const testkitReady = new Promise((resolve2) => ready = resolve2);
|
|
2487
|
+
const listener = (req, res) => {
|
|
1508
2488
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1509
|
-
}
|
|
1510
|
-
|
|
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) => {
|
|
1511
2493
|
server.once("error", reject);
|
|
1512
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
2494
|
+
server.listen(options.port ?? 4400, host, () => resolve2());
|
|
1513
2495
|
});
|
|
1514
2496
|
const { port } = server.address();
|
|
1515
2497
|
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1516
|
-
const url =
|
|
2498
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1517
2499
|
const testkit = await KindeTestkit.create({
|
|
1518
2500
|
issuer: options.issuer ?? options.seed?.issuer ?? url,
|
|
1519
2501
|
audience: options.audience ?? options.seed?.audience,
|
|
1520
2502
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1521
2503
|
});
|
|
2504
|
+
const directory = new Directory(seed);
|
|
1522
2505
|
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
1523
|
-
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
|
|
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);
|
|
1524
2509
|
const reset = () => {
|
|
1525
2510
|
auth.reset();
|
|
1526
2511
|
failures.clear();
|
|
1527
2512
|
webhooks.reset();
|
|
2513
|
+
directory.restore();
|
|
1528
2514
|
};
|
|
1529
|
-
ready({ testkit, auth, seed, failures, webhooks, reset });
|
|
2515
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
|
|
1530
2516
|
return {
|
|
1531
2517
|
url,
|
|
1532
2518
|
issuer: testkit.issuer,
|
|
@@ -1536,10 +2522,12 @@ async function startKindeTestkit(options = {}) {
|
|
|
1536
2522
|
seed,
|
|
1537
2523
|
failures,
|
|
1538
2524
|
webhooks,
|
|
2525
|
+
directory,
|
|
2526
|
+
certificatePath: certificate?.certPath ?? null,
|
|
1539
2527
|
reset,
|
|
1540
|
-
close: () => new Promise((
|
|
2528
|
+
close: () => new Promise((resolve2, reject) => {
|
|
1541
2529
|
server.closeAllConnections();
|
|
1542
|
-
server.close((error) => error ? reject(error) :
|
|
2530
|
+
server.close((error) => error ? reject(error) : resolve2());
|
|
1543
2531
|
})
|
|
1544
2532
|
};
|
|
1545
2533
|
}
|
|
@@ -1552,68 +2540,77 @@ async function handle(req, res, context) {
|
|
|
1552
2540
|
const failure = failures.take(method, pathname);
|
|
1553
2541
|
if (failure) {
|
|
1554
2542
|
if (failure.hang) return;
|
|
1555
|
-
if (failure.delayMs > 0) await new Promise((
|
|
2543
|
+
if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
|
|
1556
2544
|
if (failure.status !== null) {
|
|
1557
2545
|
const headers = {};
|
|
1558
2546
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1559
|
-
return
|
|
2547
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1560
2548
|
}
|
|
1561
2549
|
}
|
|
1562
2550
|
}
|
|
1563
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
|
+
}
|
|
1564
2561
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1565
|
-
return
|
|
2562
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1566
2563
|
}
|
|
1567
2564
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1568
|
-
return
|
|
2565
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1569
2566
|
}
|
|
1570
2567
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1571
|
-
return
|
|
2568
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1572
2569
|
}
|
|
1573
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
2570
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
1574
2571
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1575
|
-
return
|
|
2572
|
+
return sendJson4(res, 200, seed.organizations);
|
|
1576
2573
|
}
|
|
1577
2574
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1578
|
-
return
|
|
2575
|
+
return sendJson4(res, 200, seed.memberships);
|
|
1579
2576
|
}
|
|
1580
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
2577
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1581
2578
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1582
|
-
return
|
|
2579
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1583
2580
|
}
|
|
1584
2581
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1585
2582
|
failures.clear();
|
|
1586
|
-
return
|
|
2583
|
+
return sendJson4(res, 200, { ok: true });
|
|
1587
2584
|
}
|
|
1588
2585
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1589
2586
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1590
|
-
return
|
|
2587
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1591
2588
|
}
|
|
1592
2589
|
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1593
|
-
return
|
|
2590
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
1594
2591
|
}
|
|
1595
2592
|
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1596
|
-
return
|
|
2593
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1597
2594
|
}
|
|
1598
|
-
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return
|
|
1599
|
-
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return
|
|
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());
|
|
1600
2597
|
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1601
|
-
return
|
|
2598
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1602
2599
|
}
|
|
1603
2600
|
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1604
2601
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1605
|
-
return
|
|
2602
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1606
2603
|
}
|
|
1607
2604
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1608
2605
|
context.reset();
|
|
1609
|
-
return
|
|
2606
|
+
return sendJson4(res, 200, { ok: true });
|
|
1610
2607
|
}
|
|
1611
2608
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1612
2609
|
const body = await readJson(req);
|
|
1613
2610
|
const accessToken = await issueToken(testkit, seed, body);
|
|
1614
|
-
return
|
|
2611
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
1615
2612
|
}
|
|
1616
|
-
return
|
|
2613
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
1617
2614
|
}
|
|
1618
2615
|
function discovery(testkit) {
|
|
1619
2616
|
const base = testkit.issuer;
|
|
@@ -1672,7 +2669,11 @@ async function issueToken(testkit, seed, body) {
|
|
|
1672
2669
|
});
|
|
1673
2670
|
if (permissions) scenario2.permissions = permissions;
|
|
1674
2671
|
if (roles) scenario2.roles = roles;
|
|
1675
|
-
return await testkit.tokenFor(scenario2, {
|
|
2672
|
+
return await testkit.tokenFor(scenario2, {
|
|
2673
|
+
expiresIn,
|
|
2674
|
+
invalid: invalid2,
|
|
2675
|
+
featureFlags: featureFlagsFor(seed, scenario2.organization?.code ?? null)
|
|
2676
|
+
});
|
|
1676
2677
|
}
|
|
1677
2678
|
const options = {
|
|
1678
2679
|
subject: optionalString(input, "subject"),
|
|
@@ -1737,7 +2738,7 @@ async function readText(req) {
|
|
|
1737
2738
|
}
|
|
1738
2739
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1739
2740
|
}
|
|
1740
|
-
function
|
|
2741
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1741
2742
|
res.writeHead(status, {
|
|
1742
2743
|
"content-type": "application/json; charset=utf-8",
|
|
1743
2744
|
"cache-control": "no-store",
|
|
@@ -1751,10 +2752,10 @@ function sendError(res, error) {
|
|
|
1751
2752
|
return;
|
|
1752
2753
|
}
|
|
1753
2754
|
if (error instanceof TestkitError) {
|
|
1754
|
-
|
|
2755
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1755
2756
|
return;
|
|
1756
2757
|
}
|
|
1757
|
-
|
|
2758
|
+
sendJson4(res, 500, {
|
|
1758
2759
|
error: "server_error",
|
|
1759
2760
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1760
2761
|
});
|
|
@@ -1901,6 +2902,15 @@ async function runDoctor(options) {
|
|
|
1901
2902
|
} else {
|
|
1902
2903
|
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1903
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
|
+
}
|
|
1904
2914
|
const site = env.KINDE_SITE_URL;
|
|
1905
2915
|
if (!site) {
|
|
1906
2916
|
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
@@ -1934,6 +2944,7 @@ function parseEnvFile(text) {
|
|
|
1934
2944
|
DEFAULT_ISSUER,
|
|
1935
2945
|
DEFAULT_M2M_CLIENT_ID,
|
|
1936
2946
|
DEFAULT_SCOPES,
|
|
2947
|
+
Directory,
|
|
1937
2948
|
FailureInjector,
|
|
1938
2949
|
INVALID_TOKEN_KINDS,
|
|
1939
2950
|
KindeTestkit,
|
|
@@ -1944,7 +2955,9 @@ function parseEnvFile(text) {
|
|
|
1944
2955
|
createKindeOrganization,
|
|
1945
2956
|
createKindeToken,
|
|
1946
2957
|
createKindeUser,
|
|
2958
|
+
createLocalCertificate,
|
|
1947
2959
|
createMembership,
|
|
2960
|
+
ensureLocalCertificate,
|
|
1948
2961
|
getDefaultTestkit,
|
|
1949
2962
|
inspectToken,
|
|
1950
2963
|
isAuthenticated,
|