kinde-testkit 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +113 -8
- package/dist/cli.js +1580 -118
- package/dist/index.cjs +1428 -104
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +235 -1
- package/dist/index.d.ts +235 -1
- package/dist/index.js +1421 -103
- package/dist/index.js.map +1 -1
- package/dist/playwright.d.ts +34 -0
- package/dist/playwright.js +4 -0
- package/dist/playwright.js.map +1 -1
- package/dist/vitest.d.ts +186 -0
- package/dist/vitest.js +1409 -103
- package/dist/vitest.js.map +1 -1
- package/package.json +4 -1
package/dist/index.js
CHANGED
|
@@ -324,6 +324,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
324
324
|
if (scenario2.kind === "unauthenticated") return null;
|
|
325
325
|
return scenarioPrincipal(scenario2, this.issuer);
|
|
326
326
|
}
|
|
327
|
+
async signPayload(payload, invalid2) {
|
|
328
|
+
return this.sign(payload, invalid2);
|
|
329
|
+
}
|
|
327
330
|
async sign(payload, invalid2) {
|
|
328
331
|
if (invalid2 === "unsigned") {
|
|
329
332
|
const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
@@ -437,8 +440,230 @@ async function createKindeToken(options = {}) {
|
|
|
437
440
|
|
|
438
441
|
// src/server.ts
|
|
439
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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
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
|
+
}
|
|
440
642
|
|
|
441
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
|
+
}
|
|
442
667
|
function resolveSeed(input) {
|
|
443
668
|
const problems = [];
|
|
444
669
|
if (!isRecord(input)) {
|
|
@@ -448,6 +673,23 @@ function resolveSeed(input) {
|
|
|
448
673
|
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
449
674
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
450
675
|
const rawApplications = listOf(input.applications, "applications", problems);
|
|
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);
|
|
681
|
+
const webhooks = [];
|
|
682
|
+
rawWebhooks.forEach((raw, index) => {
|
|
683
|
+
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
684
|
+
problems.push(`webhooks[${index}] needs an http or https "url".`);
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
|
|
688
|
+
problems.push(`webhooks[${index}].events must be a list of event type names.`);
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
webhooks.push({ url: raw.url, events: raw.events });
|
|
692
|
+
});
|
|
451
693
|
const users = [];
|
|
452
694
|
rawUsers.forEach((raw, index) => {
|
|
453
695
|
if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
|
|
@@ -539,7 +781,107 @@ function resolveSeed(input) {
|
|
|
539
781
|
if (problems.length > 0) {
|
|
540
782
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
541
783
|
}
|
|
542
|
-
|
|
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 };
|
|
543
885
|
}
|
|
544
886
|
function findUser(users, ref) {
|
|
545
887
|
const needle = ref.toLowerCase();
|
|
@@ -584,7 +926,7 @@ function seedScenario(seed, ref) {
|
|
|
584
926
|
user,
|
|
585
927
|
organization,
|
|
586
928
|
roles: [...membership?.roles ?? []],
|
|
587
|
-
permissions:
|
|
929
|
+
permissions: effectivePermissions(seed, membership),
|
|
588
930
|
claims: {}
|
|
589
931
|
};
|
|
590
932
|
}
|
|
@@ -599,72 +941,18 @@ function listOf(value, field, problems) {
|
|
|
599
941
|
function isRecord(value) {
|
|
600
942
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
601
943
|
}
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
*{box-sizing:border-box}
|
|
611
|
-
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}
|
|
612
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
613
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
614
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
615
|
-
p{margin:0;color:var(--muted)}
|
|
616
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
617
|
-
form{margin:0}
|
|
618
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
619
|
-
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}
|
|
620
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
621
|
-
.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}
|
|
622
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
623
|
-
.list{display:grid;gap:8px}
|
|
624
|
-
.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}
|
|
625
|
-
.option:hover{border-color:var(--muted)}
|
|
626
|
-
.option strong{display:block;font-weight:500}
|
|
627
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
628
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
629
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
630
|
-
`;
|
|
631
|
-
function escapeHtml(value) {
|
|
632
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
633
|
-
}
|
|
634
|
-
function layout(title, body) {
|
|
635
|
-
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>`;
|
|
636
|
-
}
|
|
637
|
-
function displayName(user) {
|
|
638
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
639
|
-
}
|
|
640
|
-
function renderSignIn(options) {
|
|
641
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
642
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
643
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
644
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
645
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
646
|
-
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>`;
|
|
647
|
-
}).join("");
|
|
648
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
649
|
-
return layout(
|
|
650
|
-
"Sign in",
|
|
651
|
-
`<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>`
|
|
652
|
-
);
|
|
653
|
-
}
|
|
654
|
-
function renderOrganizationPicker(options) {
|
|
655
|
-
const choices = options.organizations.map(
|
|
656
|
-
(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>`
|
|
657
|
-
).join("");
|
|
658
|
-
return layout(
|
|
659
|
-
"Choose an organization",
|
|
660
|
-
`<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>`
|
|
661
|
-
);
|
|
662
|
-
}
|
|
663
|
-
function renderMessage(title, message) {
|
|
664
|
-
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;
|
|
665
952
|
}
|
|
666
953
|
|
|
667
954
|
// src/oauth.ts
|
|
955
|
+
import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
668
956
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
669
957
|
var OAuthError = class extends Error {
|
|
670
958
|
constructor(status, error, description) {
|
|
@@ -676,12 +964,16 @@ var OAuthError = class extends Error {
|
|
|
676
964
|
error;
|
|
677
965
|
};
|
|
678
966
|
var AuthorizationServer = class {
|
|
679
|
-
constructor(testkit, seed) {
|
|
967
|
+
constructor(testkit, seed, emit = () => void 0, directory) {
|
|
680
968
|
this.testkit = testkit;
|
|
681
969
|
this.seed = seed;
|
|
970
|
+
this.emit = emit;
|
|
971
|
+
this.directory = directory;
|
|
682
972
|
}
|
|
683
973
|
testkit;
|
|
684
974
|
seed;
|
|
975
|
+
emit;
|
|
976
|
+
directory;
|
|
685
977
|
codes = /* @__PURE__ */ new Map();
|
|
686
978
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
687
979
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -747,6 +1039,18 @@ var AuthorizationServer = class {
|
|
|
747
1039
|
if (!user) {
|
|
748
1040
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
749
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
|
+
}
|
|
750
1054
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
751
1055
|
const wanted = request.orgCode ?? form.org ?? null;
|
|
752
1056
|
let organizationCode = null;
|
|
@@ -783,7 +1087,7 @@ var AuthorizationServer = class {
|
|
|
783
1087
|
user,
|
|
784
1088
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
785
1089
|
roles: [...membership?.roles ?? []],
|
|
786
|
-
permissions:
|
|
1090
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
787
1091
|
claims: {}
|
|
788
1092
|
};
|
|
789
1093
|
const code = randomToken();
|
|
@@ -799,6 +1103,8 @@ var AuthorizationServer = class {
|
|
|
799
1103
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
800
1104
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
801
1105
|
});
|
|
1106
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
1107
|
+
this.emit("user.authenticated", user);
|
|
802
1108
|
const target = new URL(request.redirectUri);
|
|
803
1109
|
target.searchParams.set("code", code);
|
|
804
1110
|
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
@@ -833,7 +1139,7 @@ var AuthorizationServer = class {
|
|
|
833
1139
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
834
1140
|
}
|
|
835
1141
|
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
836
|
-
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;
|
|
837
1143
|
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
838
1144
|
return {
|
|
839
1145
|
access_token: await this.testkit.m2mToken({
|
|
@@ -869,7 +1175,7 @@ var AuthorizationServer = class {
|
|
|
869
1175
|
}
|
|
870
1176
|
if (pending.codeChallenge) {
|
|
871
1177
|
const verifier = form.code_verifier ?? "";
|
|
872
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1178
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
873
1179
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
874
1180
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
875
1181
|
}
|
|
@@ -899,7 +1205,8 @@ var AuthorizationServer = class {
|
|
|
899
1205
|
scopes: grant.scope,
|
|
900
1206
|
clientId: grant.clientId,
|
|
901
1207
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
902
|
-
authTime: grant.authTime
|
|
1208
|
+
authTime: grant.authTime,
|
|
1209
|
+
featureFlags: featureFlagsFor(this.seed, scenario2.organization?.code ?? null)
|
|
903
1210
|
}),
|
|
904
1211
|
expires_in: this.testkit.accessTokenLifetime,
|
|
905
1212
|
scope: grant.scope.join(" "),
|
|
@@ -964,8 +1271,12 @@ var AuthorizationServer = class {
|
|
|
964
1271
|
if (seeded) return seeded;
|
|
965
1272
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
966
1273
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
967
|
-
this.signedUpUsers.
|
|
968
|
-
|
|
1274
|
+
if (!this.signedUpUsers.has(user.id)) {
|
|
1275
|
+
this.signedUpUsers.set(user.id, user);
|
|
1276
|
+
if (this.directory) this.seed.users.push(user);
|
|
1277
|
+
this.emit("user.created", user);
|
|
1278
|
+
}
|
|
1279
|
+
return this.signedUpUsers.get(user.id);
|
|
969
1280
|
}
|
|
970
1281
|
organization(code) {
|
|
971
1282
|
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
@@ -1050,7 +1361,7 @@ function isHttpUrl(value) {
|
|
|
1050
1361
|
}
|
|
1051
1362
|
}
|
|
1052
1363
|
function randomToken() {
|
|
1053
|
-
return
|
|
1364
|
+
return randomBytes2(32).toString("base64url");
|
|
1054
1365
|
}
|
|
1055
1366
|
function safeEqual(a, b) {
|
|
1056
1367
|
const left = Buffer.from(a);
|
|
@@ -1074,6 +1385,687 @@ function sendJson(res, status, body) {
|
|
|
1074
1385
|
res.end(JSON.stringify(body));
|
|
1075
1386
|
}
|
|
1076
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
|
+
|
|
1077
2069
|
// src/failures.ts
|
|
1078
2070
|
var MAX_DELAY_MS = 6e4;
|
|
1079
2071
|
var FailureInjector = class {
|
|
@@ -1154,6 +2146,278 @@ function validate(rule) {
|
|
|
1154
2146
|
return problems;
|
|
1155
2147
|
}
|
|
1156
2148
|
|
|
2149
|
+
// src/webhooks.ts
|
|
2150
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
2151
|
+
var WEBHOOK_EVENT_TYPES = [
|
|
2152
|
+
"user.created",
|
|
2153
|
+
"user.updated",
|
|
2154
|
+
"user.deleted",
|
|
2155
|
+
"user.authenticated",
|
|
2156
|
+
"user.authentication_failed",
|
|
2157
|
+
"organization.created",
|
|
2158
|
+
"organization.updated",
|
|
2159
|
+
"organization.deleted",
|
|
2160
|
+
"role.created",
|
|
2161
|
+
"role.updated",
|
|
2162
|
+
"role.deleted",
|
|
2163
|
+
"permission.created",
|
|
2164
|
+
"permission.updated",
|
|
2165
|
+
"permission.deleted",
|
|
2166
|
+
"subscriber.created",
|
|
2167
|
+
"access_request.created"
|
|
2168
|
+
];
|
|
2169
|
+
var BILLING_EVENT_TYPES = [
|
|
2170
|
+
"customer.agreement_cancelled",
|
|
2171
|
+
"customer.agreement_created",
|
|
2172
|
+
"customer.invoice_overdue",
|
|
2173
|
+
"customer.meter_usage_updated",
|
|
2174
|
+
"customer.payment_failed",
|
|
2175
|
+
"customer.payment_succeeded",
|
|
2176
|
+
"customer.plan_assigned",
|
|
2177
|
+
"customer.plan_changed"
|
|
2178
|
+
];
|
|
2179
|
+
var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
|
|
2180
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
2181
|
+
var MAX_DUPLICATES = 10;
|
|
2182
|
+
var WebhookDispatcher = class {
|
|
2183
|
+
constructor(testkit, seed, endpoints = [], options = {}) {
|
|
2184
|
+
this.testkit = testkit;
|
|
2185
|
+
this.seed = seed;
|
|
2186
|
+
this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
2187
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
2188
|
+
for (const endpoint of endpoints) this.addEndpoint(endpoint);
|
|
2189
|
+
this.seededEndpoints = [...this.endpoints];
|
|
2190
|
+
}
|
|
2191
|
+
testkit;
|
|
2192
|
+
seed;
|
|
2193
|
+
endpoints = [];
|
|
2194
|
+
seededEndpoints = [];
|
|
2195
|
+
log = [];
|
|
2196
|
+
nextEndpoint = 1;
|
|
2197
|
+
retryDelaysMs;
|
|
2198
|
+
timeoutMs;
|
|
2199
|
+
addEndpoint(input) {
|
|
2200
|
+
if (!isHttpUrl2(input.url)) {
|
|
2201
|
+
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
2202
|
+
}
|
|
2203
|
+
if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
|
|
2204
|
+
throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
|
|
2205
|
+
}
|
|
2206
|
+
const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
|
|
2207
|
+
this.endpoints.push(endpoint);
|
|
2208
|
+
return { ...endpoint };
|
|
2209
|
+
}
|
|
2210
|
+
removeEndpoint(id) {
|
|
2211
|
+
const before = this.endpoints.length;
|
|
2212
|
+
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
2213
|
+
return this.endpoints.length < before;
|
|
2214
|
+
}
|
|
2215
|
+
listEndpoints() {
|
|
2216
|
+
return this.endpoints.map((e) => ({ ...e }));
|
|
2217
|
+
}
|
|
2218
|
+
deliveries() {
|
|
2219
|
+
return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
|
|
2220
|
+
}
|
|
2221
|
+
reset() {
|
|
2222
|
+
this.log = [];
|
|
2223
|
+
this.endpoints = [...this.seededEndpoints];
|
|
2224
|
+
}
|
|
2225
|
+
buildEvent(options) {
|
|
2226
|
+
if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
|
|
2227
|
+
throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
|
|
2228
|
+
}
|
|
2229
|
+
const now = /* @__PURE__ */ new Date();
|
|
2230
|
+
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
2231
|
+
const event = {
|
|
2232
|
+
data: options.data ?? this.buildData(options),
|
|
2233
|
+
event_id: `event_${randomBytes4(16).toString("hex")}`,
|
|
2234
|
+
event_timestamp: timestamp,
|
|
2235
|
+
source: options.source ?? "admin",
|
|
2236
|
+
timestamp,
|
|
2237
|
+
type: options.type
|
|
2238
|
+
};
|
|
2239
|
+
if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
|
|
2240
|
+
event.ip_address = options.ipAddress ?? "127.0.0.1";
|
|
2241
|
+
}
|
|
2242
|
+
return event;
|
|
2243
|
+
}
|
|
2244
|
+
async send(options) {
|
|
2245
|
+
const event = this.buildEvent(options);
|
|
2246
|
+
const copies = options.duplicate ?? 1;
|
|
2247
|
+
if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
|
|
2248
|
+
throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
|
|
2249
|
+
}
|
|
2250
|
+
const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
|
|
2251
|
+
if (options.to && !isHttpUrl2(options.to)) {
|
|
2252
|
+
throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
|
|
2253
|
+
}
|
|
2254
|
+
if (targets.length === 0) {
|
|
2255
|
+
throw new TestkitError(
|
|
2256
|
+
"INVALID_REQUEST",
|
|
2257
|
+
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
2258
|
+
);
|
|
2259
|
+
}
|
|
2260
|
+
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
2261
|
+
const signed = await this.testkit.signPayload(
|
|
2262
|
+
event,
|
|
2263
|
+
options.invalid === "stale" ? void 0 : options.invalid
|
|
2264
|
+
);
|
|
2265
|
+
const jobs = targets.flatMap((target) => {
|
|
2266
|
+
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
2267
|
+
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
2268
|
+
});
|
|
2269
|
+
return Promise.all(jobs);
|
|
2270
|
+
}
|
|
2271
|
+
async deliver(url, webhookId, body, event, copy) {
|
|
2272
|
+
const delivery = {
|
|
2273
|
+
webhookId,
|
|
2274
|
+
eventId: String(event.event_id),
|
|
2275
|
+
type: String(event.type),
|
|
2276
|
+
url,
|
|
2277
|
+
copy,
|
|
2278
|
+
delivered: false,
|
|
2279
|
+
attempts: [],
|
|
2280
|
+
payload: event
|
|
2281
|
+
};
|
|
2282
|
+
this.log.push(delivery);
|
|
2283
|
+
for (const [index, delay] of this.retryDelaysMs.entries()) {
|
|
2284
|
+
if (delay > 0) await sleep(delay);
|
|
2285
|
+
const started = Date.now();
|
|
2286
|
+
try {
|
|
2287
|
+
const response = await fetch(url, {
|
|
2288
|
+
method: "POST",
|
|
2289
|
+
headers: { "content-type": "application/jwt", "webhook-id": webhookId },
|
|
2290
|
+
body,
|
|
2291
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
2292
|
+
});
|
|
2293
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
2294
|
+
delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
|
|
2295
|
+
if (response.status === 200) {
|
|
2296
|
+
delivery.delivered = true;
|
|
2297
|
+
break;
|
|
2298
|
+
}
|
|
2299
|
+
} catch (error) {
|
|
2300
|
+
const name = error.name;
|
|
2301
|
+
delivery.attempts.push({
|
|
2302
|
+
attempt: index + 1,
|
|
2303
|
+
status: null,
|
|
2304
|
+
error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
|
|
2305
|
+
durationMs: Date.now() - started
|
|
2306
|
+
});
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
return { ...delivery, attempts: [...delivery.attempts] };
|
|
2310
|
+
}
|
|
2311
|
+
buildData(options) {
|
|
2312
|
+
const [subject] = options.type.split(".");
|
|
2313
|
+
switch (subject) {
|
|
2314
|
+
case "user":
|
|
2315
|
+
return { user: this.userData(options) };
|
|
2316
|
+
case "organization":
|
|
2317
|
+
return { organization: this.organizationData(options) };
|
|
2318
|
+
case "role":
|
|
2319
|
+
return { role: this.namedData(options, "role") };
|
|
2320
|
+
case "permission":
|
|
2321
|
+
return { permission: this.namedData(options, "permission") };
|
|
2322
|
+
case "subscriber": {
|
|
2323
|
+
const user = this.requireUser(options);
|
|
2324
|
+
return {
|
|
2325
|
+
subscriber: {
|
|
2326
|
+
email: user.email,
|
|
2327
|
+
first_name: user.givenName,
|
|
2328
|
+
id: stableId("sub", user.id),
|
|
2329
|
+
last_name: user.familyName,
|
|
2330
|
+
user_id: user.id
|
|
2331
|
+
}
|
|
2332
|
+
};
|
|
2333
|
+
}
|
|
2334
|
+
case "access_request": {
|
|
2335
|
+
const user = this.requireUser(options);
|
|
2336
|
+
return {
|
|
2337
|
+
access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
|
|
2338
|
+
};
|
|
2339
|
+
}
|
|
2340
|
+
default:
|
|
2341
|
+
throw new TestkitError(
|
|
2342
|
+
"INVALID_REQUEST",
|
|
2343
|
+
`kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
|
|
2344
|
+
);
|
|
2345
|
+
}
|
|
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
|
+
}
|
|
2354
|
+
emitForUser(type, user) {
|
|
2355
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2356
|
+
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
2357
|
+
void this.send({ type, data, source: "user" }).catch(() => void 0);
|
|
2358
|
+
}
|
|
2359
|
+
userData(options) {
|
|
2360
|
+
const user = this.requireUser(options);
|
|
2361
|
+
if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
|
|
2362
|
+
return this.userPayload(user);
|
|
2363
|
+
}
|
|
2364
|
+
userPayload(user) {
|
|
2365
|
+
return {
|
|
2366
|
+
email: user.email,
|
|
2367
|
+
first_name: user.givenName,
|
|
2368
|
+
id: user.id,
|
|
2369
|
+
is_password_reset_requested: false,
|
|
2370
|
+
is_suspended: false,
|
|
2371
|
+
last_name: user.familyName,
|
|
2372
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
|
|
2373
|
+
code: m.organizationCode,
|
|
2374
|
+
permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
|
|
2375
|
+
roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
|
|
2376
|
+
})),
|
|
2377
|
+
phone: null,
|
|
2378
|
+
username: typeof user.claims.username === "string" ? user.claims.username : null
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
organizationData(options) {
|
|
2382
|
+
if (!options.organization) {
|
|
2383
|
+
throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
|
|
2384
|
+
}
|
|
2385
|
+
const org = this.seed.organizations.find((o) => o.code === options.organization);
|
|
2386
|
+
if (options.type === "organization.deleted") return { code: options.organization };
|
|
2387
|
+
const name = org?.name ?? titleCase(options.organization);
|
|
2388
|
+
const data = { code: options.organization, external_id: null, handle: slug(name), name };
|
|
2389
|
+
if (options.type === "organization.updated") data.is_allow_registrations = false;
|
|
2390
|
+
return data;
|
|
2391
|
+
}
|
|
2392
|
+
namedData(options, kind) {
|
|
2393
|
+
const key = kind === "role" ? options.role : options.permission;
|
|
2394
|
+
if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
|
|
2395
|
+
const id = stableId(kind === "role" ? "role" : "perm", key);
|
|
2396
|
+
if (options.type.endsWith(".deleted")) return { id };
|
|
2397
|
+
const data = { description: "", id, key, name: titleCase(key) };
|
|
2398
|
+
if (kind === "role") data.is_default_role = false;
|
|
2399
|
+
return data;
|
|
2400
|
+
}
|
|
2401
|
+
requireUser(options) {
|
|
2402
|
+
if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
|
|
2403
|
+
const user = findUser(this.seed.users, options.user);
|
|
2404
|
+
if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
|
|
2405
|
+
return user;
|
|
2406
|
+
}
|
|
2407
|
+
};
|
|
2408
|
+
function isHttpUrl2(value) {
|
|
2409
|
+
if (typeof value !== "string") return false;
|
|
2410
|
+
try {
|
|
2411
|
+
const { protocol } = new URL(value);
|
|
2412
|
+
return protocol === "http:" || protocol === "https:";
|
|
2413
|
+
} catch {
|
|
2414
|
+
return false;
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
function sleep(ms) {
|
|
2418
|
+
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
2419
|
+
}
|
|
2420
|
+
|
|
1157
2421
|
// src/server.ts
|
|
1158
2422
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
1159
2423
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
@@ -1169,28 +2433,36 @@ async function startKindeTestkit(options = {}) {
|
|
|
1169
2433
|
const seed = resolveSeed(options.seed ?? {});
|
|
1170
2434
|
const failures = new FailureInjector();
|
|
1171
2435
|
let ready;
|
|
1172
|
-
const testkitReady = new Promise((
|
|
1173
|
-
const
|
|
2436
|
+
const testkitReady = new Promise((resolve2) => ready = resolve2);
|
|
2437
|
+
const listener = (req, res) => {
|
|
1174
2438
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1175
|
-
}
|
|
1176
|
-
|
|
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) => {
|
|
1177
2443
|
server.once("error", reject);
|
|
1178
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
2444
|
+
server.listen(options.port ?? 4400, host, () => resolve2());
|
|
1179
2445
|
});
|
|
1180
2446
|
const { port } = server.address();
|
|
1181
2447
|
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1182
|
-
const url =
|
|
2448
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1183
2449
|
const testkit = await KindeTestkit.create({
|
|
1184
2450
|
issuer: options.issuer ?? options.seed?.issuer ?? url,
|
|
1185
2451
|
audience: options.audience ?? options.seed?.audience,
|
|
1186
2452
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1187
2453
|
});
|
|
1188
|
-
const
|
|
2454
|
+
const directory = new Directory(seed);
|
|
2455
|
+
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
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);
|
|
1189
2459
|
const reset = () => {
|
|
1190
2460
|
auth.reset();
|
|
1191
2461
|
failures.clear();
|
|
2462
|
+
webhooks.reset();
|
|
2463
|
+
directory.restore();
|
|
1192
2464
|
};
|
|
1193
|
-
ready({ testkit, auth, seed, failures, reset });
|
|
2465
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
|
|
1194
2466
|
return {
|
|
1195
2467
|
url,
|
|
1196
2468
|
issuer: testkit.issuer,
|
|
@@ -1199,15 +2471,18 @@ async function startKindeTestkit(options = {}) {
|
|
|
1199
2471
|
testkit,
|
|
1200
2472
|
seed,
|
|
1201
2473
|
failures,
|
|
2474
|
+
webhooks,
|
|
2475
|
+
directory,
|
|
2476
|
+
certificatePath: certificate?.certPath ?? null,
|
|
1202
2477
|
reset,
|
|
1203
|
-
close: () => new Promise((
|
|
2478
|
+
close: () => new Promise((resolve2, reject) => {
|
|
1204
2479
|
server.closeAllConnections();
|
|
1205
|
-
server.close((error) => error ? reject(error) :
|
|
2480
|
+
server.close((error) => error ? reject(error) : resolve2());
|
|
1206
2481
|
})
|
|
1207
2482
|
};
|
|
1208
2483
|
}
|
|
1209
2484
|
async function handle(req, res, context) {
|
|
1210
|
-
const { testkit, auth, seed, failures } = context;
|
|
2485
|
+
const { testkit, auth, seed, failures, webhooks } = context;
|
|
1211
2486
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1212
2487
|
const { pathname } = url;
|
|
1213
2488
|
const method = req.method ?? "GET";
|
|
@@ -1215,53 +2490,77 @@ async function handle(req, res, context) {
|
|
|
1215
2490
|
const failure = failures.take(method, pathname);
|
|
1216
2491
|
if (failure) {
|
|
1217
2492
|
if (failure.hang) return;
|
|
1218
|
-
if (failure.delayMs > 0) await new Promise((
|
|
2493
|
+
if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
|
|
1219
2494
|
if (failure.status !== null) {
|
|
1220
2495
|
const headers = {};
|
|
1221
2496
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1222
|
-
return
|
|
2497
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1223
2498
|
}
|
|
1224
2499
|
}
|
|
1225
2500
|
}
|
|
1226
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
|
+
}
|
|
1227
2511
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1228
|
-
return
|
|
2512
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1229
2513
|
}
|
|
1230
2514
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1231
|
-
return
|
|
2515
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1232
2516
|
}
|
|
1233
2517
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1234
|
-
return
|
|
2518
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1235
2519
|
}
|
|
1236
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
2520
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
1237
2521
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1238
|
-
return
|
|
2522
|
+
return sendJson4(res, 200, seed.organizations);
|
|
1239
2523
|
}
|
|
1240
2524
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1241
|
-
return
|
|
2525
|
+
return sendJson4(res, 200, seed.memberships);
|
|
1242
2526
|
}
|
|
1243
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
2527
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1244
2528
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1245
|
-
return
|
|
2529
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1246
2530
|
}
|
|
1247
2531
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1248
2532
|
failures.clear();
|
|
1249
|
-
return
|
|
2533
|
+
return sendJson4(res, 200, { ok: true });
|
|
1250
2534
|
}
|
|
1251
2535
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1252
2536
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1253
|
-
return
|
|
2537
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
2538
|
+
}
|
|
2539
|
+
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
2540
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
2541
|
+
}
|
|
2542
|
+
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
2543
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
2544
|
+
}
|
|
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());
|
|
2547
|
+
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
2548
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
2549
|
+
}
|
|
2550
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
2551
|
+
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
2552
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1254
2553
|
}
|
|
1255
2554
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1256
2555
|
context.reset();
|
|
1257
|
-
return
|
|
2556
|
+
return sendJson4(res, 200, { ok: true });
|
|
1258
2557
|
}
|
|
1259
2558
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1260
2559
|
const body = await readJson(req);
|
|
1261
2560
|
const accessToken = await issueToken(testkit, seed, body);
|
|
1262
|
-
return
|
|
2561
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
1263
2562
|
}
|
|
1264
|
-
return
|
|
2563
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
1265
2564
|
}
|
|
1266
2565
|
function discovery(testkit) {
|
|
1267
2566
|
const base = testkit.issuer;
|
|
@@ -1320,7 +2619,11 @@ async function issueToken(testkit, seed, body) {
|
|
|
1320
2619
|
});
|
|
1321
2620
|
if (permissions) scenario2.permissions = permissions;
|
|
1322
2621
|
if (roles) scenario2.roles = roles;
|
|
1323
|
-
return await testkit.tokenFor(scenario2, {
|
|
2622
|
+
return await testkit.tokenFor(scenario2, {
|
|
2623
|
+
expiresIn,
|
|
2624
|
+
invalid: invalid2,
|
|
2625
|
+
featureFlags: featureFlagsFor(seed, scenario2.organization?.code ?? null)
|
|
2626
|
+
});
|
|
1324
2627
|
}
|
|
1325
2628
|
const options = {
|
|
1326
2629
|
subject: optionalString(input, "subject"),
|
|
@@ -1385,7 +2688,7 @@ async function readText(req) {
|
|
|
1385
2688
|
}
|
|
1386
2689
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1387
2690
|
}
|
|
1388
|
-
function
|
|
2691
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1389
2692
|
res.writeHead(status, {
|
|
1390
2693
|
"content-type": "application/json; charset=utf-8",
|
|
1391
2694
|
"cache-control": "no-store",
|
|
@@ -1399,10 +2702,10 @@ function sendError(res, error) {
|
|
|
1399
2702
|
return;
|
|
1400
2703
|
}
|
|
1401
2704
|
if (error instanceof TestkitError) {
|
|
1402
|
-
|
|
2705
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1403
2706
|
return;
|
|
1404
2707
|
}
|
|
1405
|
-
|
|
2708
|
+
sendJson4(res, 500, {
|
|
1406
2709
|
error: "server_error",
|
|
1407
2710
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1408
2711
|
});
|
|
@@ -1549,6 +2852,15 @@ async function runDoctor(options) {
|
|
|
1549
2852
|
} else {
|
|
1550
2853
|
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1551
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
|
+
}
|
|
1552
2864
|
const site = env.KINDE_SITE_URL;
|
|
1553
2865
|
if (!site) {
|
|
1554
2866
|
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
@@ -1575,20 +2887,26 @@ function parseEnvFile(text) {
|
|
|
1575
2887
|
return values;
|
|
1576
2888
|
}
|
|
1577
2889
|
export {
|
|
2890
|
+
BILLING_EVENT_TYPES,
|
|
1578
2891
|
DEFAULT_AUTH_METHODS,
|
|
1579
2892
|
DEFAULT_CLIENT_ID,
|
|
1580
2893
|
DEFAULT_ISSUER,
|
|
1581
2894
|
DEFAULT_M2M_CLIENT_ID,
|
|
1582
2895
|
DEFAULT_SCOPES,
|
|
2896
|
+
Directory,
|
|
1583
2897
|
FailureInjector,
|
|
1584
2898
|
INVALID_TOKEN_KINDS,
|
|
1585
2899
|
KindeTestkit,
|
|
1586
2900
|
ScenarioBuilder,
|
|
1587
2901
|
TestkitError,
|
|
2902
|
+
WEBHOOK_EVENT_TYPES,
|
|
2903
|
+
WebhookDispatcher,
|
|
1588
2904
|
createKindeOrganization,
|
|
1589
2905
|
createKindeToken,
|
|
1590
2906
|
createKindeUser,
|
|
2907
|
+
createLocalCertificate,
|
|
1591
2908
|
createMembership,
|
|
2909
|
+
ensureLocalCertificate,
|
|
1592
2910
|
getDefaultTestkit,
|
|
1593
2911
|
inspectToken,
|
|
1594
2912
|
isAuthenticated,
|