kinde-testkit 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +48 -2
- package/dist/cli.js +1177 -124
- package/dist/index.cjs +1124 -111
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +150 -1
- package/dist/index.d.ts +150 -1
- package/dist/index.js +1120 -110
- package/dist/index.js.map +1 -1
- package/dist/vitest.d.ts +82 -0
- package/dist/vitest.js +1108 -110
- package/dist/vitest.js.map +1 -1
- package/package.json +3 -1
package/dist/cli.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { spawnSync } from "child_process";
|
|
5
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
6
|
+
import { resolve as resolve2 } from "path";
|
|
6
7
|
import { parseArgs } from "util";
|
|
7
8
|
|
|
8
9
|
// src/errors.ts
|
|
@@ -26,6 +27,144 @@ ${this.message}`;
|
|
|
26
27
|
|
|
27
28
|
// src/server.ts
|
|
28
29
|
import { createServer } from "http";
|
|
30
|
+
import { createServer as createHttpsServer } from "https";
|
|
31
|
+
|
|
32
|
+
// src/certificate.ts
|
|
33
|
+
import { createHash, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
|
|
34
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
35
|
+
import { join, resolve } from "path";
|
|
36
|
+
var CERT_FILE = "localhost-cert.pem";
|
|
37
|
+
var KEY_FILE = "localhost-key.pem";
|
|
38
|
+
var VALID_DAYS = 825;
|
|
39
|
+
function ensureLocalCertificate(directory = ".kinde-testkit") {
|
|
40
|
+
const dir = resolve(directory);
|
|
41
|
+
const certPath = join(dir, CERT_FILE);
|
|
42
|
+
const keyPath = join(dir, KEY_FILE);
|
|
43
|
+
if (existsSync(certPath) && existsSync(keyPath)) {
|
|
44
|
+
const cert3 = readFileSync(certPath, "utf8");
|
|
45
|
+
const key2 = readFileSync(keyPath, "utf8");
|
|
46
|
+
try {
|
|
47
|
+
if (new Date(new X509Certificate(cert3).validTo).getTime() > Date.now() + 864e5) {
|
|
48
|
+
return { cert: cert3, key: key2, certPath, keyPath, created: false };
|
|
49
|
+
}
|
|
50
|
+
} catch {
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const { cert: cert2, key } = createLocalCertificate();
|
|
54
|
+
mkdirSync(dir, { recursive: true });
|
|
55
|
+
writeFileSync(certPath, cert2);
|
|
56
|
+
writeFileSync(keyPath, key, { mode: 384 });
|
|
57
|
+
writeFileSync(join(dir, ".gitignore"), "*\n");
|
|
58
|
+
return { cert: cert2, key, certPath, keyPath, created: true };
|
|
59
|
+
}
|
|
60
|
+
function createLocalCertificate() {
|
|
61
|
+
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
62
|
+
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
63
|
+
const keyId = createHash("sha1").update(subjectPublicKeyBits(spki)).digest();
|
|
64
|
+
const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
|
|
65
|
+
const now = Date.now();
|
|
66
|
+
const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
|
|
67
|
+
const serial = randomBytes(16);
|
|
68
|
+
serial[0] &= 127;
|
|
69
|
+
const extensions = seq(
|
|
70
|
+
seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
|
|
71
|
+
seq(oid("2.5.29.14"), octets(octets(keyId))),
|
|
72
|
+
seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
|
|
73
|
+
seq(
|
|
74
|
+
oid("2.5.29.17"),
|
|
75
|
+
octets(
|
|
76
|
+
seq(
|
|
77
|
+
tlv(130, Buffer.from("localhost")),
|
|
78
|
+
tlv(135, Buffer.from([127, 0, 0, 1])),
|
|
79
|
+
tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
);
|
|
84
|
+
const tbs = seq(
|
|
85
|
+
tlv(160, integer(Buffer.from([2]))),
|
|
86
|
+
integer(serial),
|
|
87
|
+
algorithm,
|
|
88
|
+
name,
|
|
89
|
+
seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
|
|
90
|
+
name,
|
|
91
|
+
spki,
|
|
92
|
+
tlv(163, extensions)
|
|
93
|
+
);
|
|
94
|
+
const signature = sign("sha256", tbs, privateKey);
|
|
95
|
+
const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
|
|
96
|
+
return {
|
|
97
|
+
cert: pem("CERTIFICATE", der),
|
|
98
|
+
key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function subjectPublicKeyBits(spki) {
|
|
102
|
+
const outer = readTlv(spki, 0);
|
|
103
|
+
const algorithm = readTlv(spki, outer.start);
|
|
104
|
+
const bits = readTlv(spki, algorithm.end);
|
|
105
|
+
return spki.subarray(bits.start + 1, bits.end);
|
|
106
|
+
}
|
|
107
|
+
function readTlv(buf, offset) {
|
|
108
|
+
let len = buf[offset + 1];
|
|
109
|
+
let header = 2;
|
|
110
|
+
if (len & 128) {
|
|
111
|
+
const n = len & 127;
|
|
112
|
+
len = 0;
|
|
113
|
+
for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
|
|
114
|
+
header += n;
|
|
115
|
+
}
|
|
116
|
+
return { start: offset + header, end: offset + header + len };
|
|
117
|
+
}
|
|
118
|
+
function tlv(tag, content) {
|
|
119
|
+
return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
|
|
120
|
+
}
|
|
121
|
+
function length(n) {
|
|
122
|
+
if (n < 128) return Buffer.from([n]);
|
|
123
|
+
const bytes = [];
|
|
124
|
+
while (n > 0) {
|
|
125
|
+
bytes.unshift(n & 255);
|
|
126
|
+
n >>= 8;
|
|
127
|
+
}
|
|
128
|
+
return Buffer.from([128 | bytes.length, ...bytes]);
|
|
129
|
+
}
|
|
130
|
+
function seq(...items) {
|
|
131
|
+
return tlv(48, Buffer.concat(items));
|
|
132
|
+
}
|
|
133
|
+
function set(...items) {
|
|
134
|
+
return tlv(49, Buffer.concat(items));
|
|
135
|
+
}
|
|
136
|
+
function octets(content) {
|
|
137
|
+
return tlv(4, content);
|
|
138
|
+
}
|
|
139
|
+
function integer(bytes) {
|
|
140
|
+
return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
|
|
141
|
+
}
|
|
142
|
+
function oid(dotted) {
|
|
143
|
+
const parts = dotted.split(".").map(Number);
|
|
144
|
+
const bytes = [parts[0] * 40 + parts[1]];
|
|
145
|
+
for (const part of parts.slice(2)) {
|
|
146
|
+
const chunk = [part & 127];
|
|
147
|
+
let value = part >> 7;
|
|
148
|
+
while (value > 0) {
|
|
149
|
+
chunk.unshift(value & 127 | 128);
|
|
150
|
+
value >>= 7;
|
|
151
|
+
}
|
|
152
|
+
bytes.push(...chunk);
|
|
153
|
+
}
|
|
154
|
+
return tlv(6, Buffer.from(bytes));
|
|
155
|
+
}
|
|
156
|
+
function utcTime(date) {
|
|
157
|
+
const iso = date.toISOString();
|
|
158
|
+
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`;
|
|
159
|
+
return tlv(23, Buffer.from(value));
|
|
160
|
+
}
|
|
161
|
+
function pem(label, der) {
|
|
162
|
+
const body = der.toString("base64").match(/.{1,64}/g).join("\n");
|
|
163
|
+
return `-----BEGIN ${label}-----
|
|
164
|
+
${body}
|
|
165
|
+
-----END ${label}-----
|
|
166
|
+
`;
|
|
167
|
+
}
|
|
29
168
|
|
|
30
169
|
// src/testkit.ts
|
|
31
170
|
import { randomUUID } from "crypto";
|
|
@@ -39,10 +178,10 @@ import {
|
|
|
39
178
|
} from "jose";
|
|
40
179
|
|
|
41
180
|
// src/ids.ts
|
|
42
|
-
import { createHash } from "crypto";
|
|
181
|
+
import { createHash as createHash2 } from "crypto";
|
|
43
182
|
var counters = /* @__PURE__ */ new Map();
|
|
44
183
|
function stableId(prefix, seed) {
|
|
45
|
-
return `${prefix}_${
|
|
184
|
+
return `${prefix}_${createHash2("sha256").update(seed).digest("hex").slice(0, 16)}`;
|
|
46
185
|
}
|
|
47
186
|
function nextSequence(prefix) {
|
|
48
187
|
const next = (counters.get(prefix) ?? 0) + 1;
|
|
@@ -358,7 +497,91 @@ function warnIfRealKindeDomain(issuer) {
|
|
|
358
497
|
}
|
|
359
498
|
}
|
|
360
499
|
|
|
500
|
+
// src/login-page.ts
|
|
501
|
+
var STYLE = `
|
|
502
|
+
: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}
|
|
503
|
+
@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}}
|
|
504
|
+
*{box-sizing:border-box}
|
|
505
|
+
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}
|
|
506
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
507
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
508
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
509
|
+
p{margin:0;color:var(--muted)}
|
|
510
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
511
|
+
form{margin:0}
|
|
512
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
513
|
+
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}
|
|
514
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
515
|
+
.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}
|
|
516
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
517
|
+
.list{display:grid;gap:8px}
|
|
518
|
+
.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}
|
|
519
|
+
.option:hover{border-color:var(--muted)}
|
|
520
|
+
.option strong{display:block;font-weight:500}
|
|
521
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
522
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
523
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
524
|
+
`;
|
|
525
|
+
function escapeHtml(value) {
|
|
526
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
527
|
+
}
|
|
528
|
+
function layout(title, body) {
|
|
529
|
+
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>`;
|
|
530
|
+
}
|
|
531
|
+
function displayName(user) {
|
|
532
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
533
|
+
}
|
|
534
|
+
function renderSignIn(options) {
|
|
535
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
536
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
537
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
538
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
539
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
540
|
+
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>`;
|
|
541
|
+
}).join("");
|
|
542
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
543
|
+
return layout(
|
|
544
|
+
"Sign in",
|
|
545
|
+
`<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>`
|
|
546
|
+
);
|
|
547
|
+
}
|
|
548
|
+
function renderOrganizationPicker(options) {
|
|
549
|
+
const choices = options.organizations.map(
|
|
550
|
+
(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>`
|
|
551
|
+
).join("");
|
|
552
|
+
return layout(
|
|
553
|
+
"Choose an organization",
|
|
554
|
+
`<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>`
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
function renderMessage(title, message) {
|
|
558
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
559
|
+
}
|
|
560
|
+
|
|
361
561
|
// src/seed.ts
|
|
562
|
+
function roleRecord(key, extra = {}) {
|
|
563
|
+
return {
|
|
564
|
+
id: stableId("role", key),
|
|
565
|
+
key,
|
|
566
|
+
name: extra.name ?? titleCase(key),
|
|
567
|
+
description: extra.description ?? null,
|
|
568
|
+
isDefault: extra.isDefault ?? false,
|
|
569
|
+
permissions: [...extra.permissions ?? []]
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
function permissionRecord(key, extra = {}) {
|
|
573
|
+
return {
|
|
574
|
+
id: stableId("perm", key),
|
|
575
|
+
key,
|
|
576
|
+
name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
|
|
577
|
+
description: extra.description ?? null
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
function effectivePermissions(seed, membership) {
|
|
581
|
+
if (!membership) return [];
|
|
582
|
+
const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
|
|
583
|
+
return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
|
|
584
|
+
}
|
|
362
585
|
function resolveSeed(input) {
|
|
363
586
|
const problems = [];
|
|
364
587
|
if (!isRecord(input)) {
|
|
@@ -369,6 +592,10 @@ function resolveSeed(input) {
|
|
|
369
592
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
370
593
|
const rawApplications = listOf(input.applications, "applications", problems);
|
|
371
594
|
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
595
|
+
const rawRoles = listOf(input.roles, "roles", problems);
|
|
596
|
+
const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
|
|
597
|
+
const rawPlans = listOf(input.plans, "plans", problems);
|
|
598
|
+
const rawPermissions = listOf(input.permissions, "permissions", problems);
|
|
372
599
|
const webhooks = [];
|
|
373
600
|
rawWebhooks.forEach((raw, index) => {
|
|
374
601
|
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
@@ -472,7 +699,107 @@ function resolveSeed(input) {
|
|
|
472
699
|
if (problems.length > 0) {
|
|
473
700
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
474
701
|
}
|
|
475
|
-
|
|
702
|
+
const permissions = [];
|
|
703
|
+
rawPermissions.forEach((raw, index) => {
|
|
704
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
705
|
+
problems.push(`permissions[${index}] needs a string "key".`);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (permissions.some((p) => p.key === raw.key)) {
|
|
709
|
+
problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
permissions.push(
|
|
713
|
+
permissionRecord(raw.key, {
|
|
714
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
715
|
+
description: typeof raw.description === "string" ? raw.description : void 0
|
|
716
|
+
})
|
|
717
|
+
);
|
|
718
|
+
});
|
|
719
|
+
const roles = [];
|
|
720
|
+
rawRoles.forEach((raw, index) => {
|
|
721
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
722
|
+
problems.push(`roles[${index}] needs a string "key".`);
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
if (roles.some((r) => r.key === raw.key)) {
|
|
726
|
+
problems.push(`roles[${index}] repeats the key "${raw.key}".`);
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
|
|
730
|
+
problems.push(`roles[${index}].permissions must be a list of permission keys.`);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
roles.push(
|
|
734
|
+
roleRecord(raw.key, {
|
|
735
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
736
|
+
description: typeof raw.description === "string" ? raw.description : void 0,
|
|
737
|
+
isDefault: raw.isDefault === true,
|
|
738
|
+
permissions: raw.permissions ?? []
|
|
739
|
+
})
|
|
740
|
+
);
|
|
741
|
+
});
|
|
742
|
+
if (problems.length > 0) {
|
|
743
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
744
|
+
}
|
|
745
|
+
const featureFlags = [];
|
|
746
|
+
rawFlags.forEach((raw, index) => {
|
|
747
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
|
|
748
|
+
problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
|
|
752
|
+
featureFlags.push({
|
|
753
|
+
id: stableId("flag", raw.key),
|
|
754
|
+
key: raw.key,
|
|
755
|
+
name: typeof raw.name === "string" ? raw.name : raw.key,
|
|
756
|
+
type,
|
|
757
|
+
value: raw.value,
|
|
758
|
+
organizations: isRecord(raw.organizations) ? raw.organizations : {}
|
|
759
|
+
});
|
|
760
|
+
});
|
|
761
|
+
const plans = [];
|
|
762
|
+
rawPlans.forEach((raw, index) => {
|
|
763
|
+
if (!isRecord(raw) || typeof raw.key !== "string") {
|
|
764
|
+
problems.push(`plans[${index}] needs a string "key".`);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
|
|
768
|
+
plans.push({
|
|
769
|
+
key: raw.key,
|
|
770
|
+
name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
|
|
771
|
+
subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
|
|
772
|
+
subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
773
|
+
entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
|
|
774
|
+
id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
|
|
775
|
+
featureKey: e.featureKey,
|
|
776
|
+
featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
|
|
777
|
+
priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
|
|
778
|
+
fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
|
|
779
|
+
unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
|
|
780
|
+
limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
|
|
781
|
+
limitMin: typeof e.limitMin === "number" ? e.limitMin : null
|
|
782
|
+
}))
|
|
783
|
+
});
|
|
784
|
+
});
|
|
785
|
+
const userProperties = {};
|
|
786
|
+
rawUsers.forEach((raw) => {
|
|
787
|
+
if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
|
|
788
|
+
userProperties[raw.id] = raw.properties;
|
|
789
|
+
}
|
|
790
|
+
});
|
|
791
|
+
if (problems.length > 0) {
|
|
792
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
793
|
+
}
|
|
794
|
+
const usedRoles = new Set(memberships.flatMap((m) => m.roles));
|
|
795
|
+
for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
|
|
796
|
+
const usedPermissions = /* @__PURE__ */ new Set([
|
|
797
|
+
...memberships.flatMap((m) => m.permissions),
|
|
798
|
+
...roles.flatMap((r) => r.permissions),
|
|
799
|
+
...applications.flatMap((a) => a.permissions ?? [])
|
|
800
|
+
]);
|
|
801
|
+
for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
|
|
802
|
+
return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
|
|
476
803
|
}
|
|
477
804
|
function findUser(users, ref) {
|
|
478
805
|
const needle = ref.toLowerCase();
|
|
@@ -517,7 +844,7 @@ function seedScenario(seed, ref) {
|
|
|
517
844
|
user,
|
|
518
845
|
organization,
|
|
519
846
|
roles: [...membership?.roles ?? []],
|
|
520
|
-
permissions:
|
|
847
|
+
permissions: effectivePermissions(seed, membership),
|
|
521
848
|
claims: {}
|
|
522
849
|
};
|
|
523
850
|
}
|
|
@@ -532,72 +859,18 @@ function listOf(value, field, problems) {
|
|
|
532
859
|
function isRecord(value) {
|
|
533
860
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
534
861
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
*{box-sizing:border-box}
|
|
544
|
-
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}
|
|
545
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
546
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
547
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
548
|
-
p{margin:0;color:var(--muted)}
|
|
549
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
550
|
-
form{margin:0}
|
|
551
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
552
|
-
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}
|
|
553
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
554
|
-
.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}
|
|
555
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
556
|
-
.list{display:grid;gap:8px}
|
|
557
|
-
.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}
|
|
558
|
-
.option:hover{border-color:var(--muted)}
|
|
559
|
-
.option strong{display:block;font-weight:500}
|
|
560
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
561
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
562
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
563
|
-
`;
|
|
564
|
-
function escapeHtml(value) {
|
|
565
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
566
|
-
}
|
|
567
|
-
function layout(title, body) {
|
|
568
|
-
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>`;
|
|
569
|
-
}
|
|
570
|
-
function displayName(user) {
|
|
571
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
572
|
-
}
|
|
573
|
-
function renderSignIn(options) {
|
|
574
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
575
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
576
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
577
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
578
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
579
|
-
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>`;
|
|
580
|
-
}).join("");
|
|
581
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
582
|
-
return layout(
|
|
583
|
-
"Sign in",
|
|
584
|
-
`<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>`
|
|
585
|
-
);
|
|
586
|
-
}
|
|
587
|
-
function renderOrganizationPicker(options) {
|
|
588
|
-
const choices = options.organizations.map(
|
|
589
|
-
(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>`
|
|
590
|
-
).join("");
|
|
591
|
-
return layout(
|
|
592
|
-
"Choose an organization",
|
|
593
|
-
`<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>`
|
|
594
|
-
);
|
|
595
|
-
}
|
|
596
|
-
function renderMessage(title, message) {
|
|
597
|
-
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
862
|
+
function featureFlagsFor(seed, organizationCode) {
|
|
863
|
+
if (seed.featureFlags.length === 0) return void 0;
|
|
864
|
+
const claim = {};
|
|
865
|
+
for (const flag of seed.featureFlags) {
|
|
866
|
+
const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
|
|
867
|
+
claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
|
|
868
|
+
}
|
|
869
|
+
return claim;
|
|
598
870
|
}
|
|
599
871
|
|
|
600
872
|
// src/oauth.ts
|
|
873
|
+
import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
601
874
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
602
875
|
var OAuthError = class extends Error {
|
|
603
876
|
constructor(status, error, description) {
|
|
@@ -609,14 +882,16 @@ var OAuthError = class extends Error {
|
|
|
609
882
|
error;
|
|
610
883
|
};
|
|
611
884
|
var AuthorizationServer = class {
|
|
612
|
-
constructor(testkit, seed, emit = () => void 0) {
|
|
885
|
+
constructor(testkit, seed, emit = () => void 0, directory) {
|
|
613
886
|
this.testkit = testkit;
|
|
614
887
|
this.seed = seed;
|
|
615
888
|
this.emit = emit;
|
|
889
|
+
this.directory = directory;
|
|
616
890
|
}
|
|
617
891
|
testkit;
|
|
618
892
|
seed;
|
|
619
893
|
emit;
|
|
894
|
+
directory;
|
|
620
895
|
codes = /* @__PURE__ */ new Map();
|
|
621
896
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
622
897
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -682,6 +957,18 @@ var AuthorizationServer = class {
|
|
|
682
957
|
if (!user) {
|
|
683
958
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
684
959
|
}
|
|
960
|
+
if (this.directory?.isSuspended(user.id)) {
|
|
961
|
+
return sendHtml(
|
|
962
|
+
res,
|
|
963
|
+
403,
|
|
964
|
+
renderSignIn({
|
|
965
|
+
request: encoded,
|
|
966
|
+
users: this.loginPageUsers(),
|
|
967
|
+
requiredOrganization: request2.orgCode ?? void 0,
|
|
968
|
+
error: `${user.email ?? user.id} is suspended and cannot sign in.`
|
|
969
|
+
})
|
|
970
|
+
);
|
|
971
|
+
}
|
|
685
972
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
686
973
|
const wanted = request2.orgCode ?? form.org ?? null;
|
|
687
974
|
let organizationCode = null;
|
|
@@ -718,7 +1005,7 @@ var AuthorizationServer = class {
|
|
|
718
1005
|
user,
|
|
719
1006
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
720
1007
|
roles: [...membership?.roles ?? []],
|
|
721
|
-
permissions:
|
|
1008
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
722
1009
|
claims: {}
|
|
723
1010
|
};
|
|
724
1011
|
const code = randomToken();
|
|
@@ -734,6 +1021,7 @@ var AuthorizationServer = class {
|
|
|
734
1021
|
codeChallengeMethod: request2.codeChallengeMethod,
|
|
735
1022
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
736
1023
|
});
|
|
1024
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
737
1025
|
this.emit("user.authenticated", user);
|
|
738
1026
|
const target = new URL(request2.redirectUri);
|
|
739
1027
|
target.searchParams.set("code", code);
|
|
@@ -769,7 +1057,7 @@ var AuthorizationServer = class {
|
|
|
769
1057
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
770
1058
|
}
|
|
771
1059
|
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
772
|
-
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1060
|
+
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
773
1061
|
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
774
1062
|
return {
|
|
775
1063
|
access_token: await this.testkit.m2mToken({
|
|
@@ -805,7 +1093,7 @@ var AuthorizationServer = class {
|
|
|
805
1093
|
}
|
|
806
1094
|
if (pending.codeChallenge) {
|
|
807
1095
|
const verifier = form.code_verifier ?? "";
|
|
808
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1096
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
809
1097
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
810
1098
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
811
1099
|
}
|
|
@@ -835,7 +1123,8 @@ var AuthorizationServer = class {
|
|
|
835
1123
|
scopes: grant.scope,
|
|
836
1124
|
clientId: grant.clientId,
|
|
837
1125
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
838
|
-
authTime: grant.authTime
|
|
1126
|
+
authTime: grant.authTime,
|
|
1127
|
+
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
839
1128
|
}),
|
|
840
1129
|
expires_in: this.testkit.accessTokenLifetime,
|
|
841
1130
|
scope: grant.scope.join(" "),
|
|
@@ -902,6 +1191,7 @@ var AuthorizationServer = class {
|
|
|
902
1191
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
903
1192
|
if (!this.signedUpUsers.has(user.id)) {
|
|
904
1193
|
this.signedUpUsers.set(user.id, user);
|
|
1194
|
+
if (this.directory) this.seed.users.push(user);
|
|
905
1195
|
this.emit("user.created", user);
|
|
906
1196
|
}
|
|
907
1197
|
return this.signedUpUsers.get(user.id);
|
|
@@ -989,7 +1279,7 @@ function isHttpUrl(value) {
|
|
|
989
1279
|
}
|
|
990
1280
|
}
|
|
991
1281
|
function randomToken() {
|
|
992
|
-
return
|
|
1282
|
+
return randomBytes2(32).toString("base64url");
|
|
993
1283
|
}
|
|
994
1284
|
function safeEqual(a, b) {
|
|
995
1285
|
const left = Buffer.from(a);
|
|
@@ -1013,6 +1303,687 @@ function sendJson(res, status, body) {
|
|
|
1013
1303
|
res.end(JSON.stringify(body));
|
|
1014
1304
|
}
|
|
1015
1305
|
|
|
1306
|
+
// src/account.ts
|
|
1307
|
+
var DEFAULT_PAGE_SIZE = 10;
|
|
1308
|
+
var AccountApi = class {
|
|
1309
|
+
constructor(testkit, directory) {
|
|
1310
|
+
this.testkit = testkit;
|
|
1311
|
+
this.directory = directory;
|
|
1312
|
+
}
|
|
1313
|
+
testkit;
|
|
1314
|
+
directory;
|
|
1315
|
+
async handle(req, res, url) {
|
|
1316
|
+
if (!url.pathname.startsWith("/account_api/v1/")) return false;
|
|
1317
|
+
if ((req.method ?? "GET") !== "GET") {
|
|
1318
|
+
sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
|
|
1319
|
+
return true;
|
|
1320
|
+
}
|
|
1321
|
+
const header = req.headers.authorization ?? "";
|
|
1322
|
+
let token2;
|
|
1323
|
+
try {
|
|
1324
|
+
if (!header.startsWith("Bearer ")) throw new Error("missing");
|
|
1325
|
+
token2 = await this.testkit.verify(header.slice(7));
|
|
1326
|
+
} catch {
|
|
1327
|
+
sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
|
|
1328
|
+
return true;
|
|
1329
|
+
}
|
|
1330
|
+
if (typeof token2.sub !== "string" || Array.isArray(token2.gty) && token2.gty.includes("client_credentials")) {
|
|
1331
|
+
sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
|
|
1332
|
+
return true;
|
|
1333
|
+
}
|
|
1334
|
+
const userId = token2.sub;
|
|
1335
|
+
const orgCode = typeof token2.org_code === "string" ? token2.org_code : null;
|
|
1336
|
+
const path = url.pathname.slice("/account_api/v1/".length);
|
|
1337
|
+
const d = this.directory;
|
|
1338
|
+
const membership = orgCode ? d.membership(userId, orgCode) : void 0;
|
|
1339
|
+
if (path === "permissions") {
|
|
1340
|
+
const items = effectivePermissions(d.seed, membership).map((key) => {
|
|
1341
|
+
const p = d.ensurePermission(key);
|
|
1342
|
+
return { id: p.id, name: p.name, key: p.key };
|
|
1343
|
+
});
|
|
1344
|
+
sendPage(res, url, "permissions", items, { org_code: orgCode });
|
|
1345
|
+
return true;
|
|
1346
|
+
}
|
|
1347
|
+
if (path.startsWith("permission/")) {
|
|
1348
|
+
const key = decodeURIComponent(path.slice("permission/".length));
|
|
1349
|
+
sendJson2(res, 200, {
|
|
1350
|
+
data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
|
|
1351
|
+
});
|
|
1352
|
+
return true;
|
|
1353
|
+
}
|
|
1354
|
+
if (path === "roles") {
|
|
1355
|
+
const items = (membership?.roles ?? []).map((key) => {
|
|
1356
|
+
const r = d.ensureRole(key);
|
|
1357
|
+
return { id: r.id, name: r.name, key: r.key };
|
|
1358
|
+
});
|
|
1359
|
+
sendPage(res, url, "roles", items, { org_code: orgCode });
|
|
1360
|
+
return true;
|
|
1361
|
+
}
|
|
1362
|
+
if (path === "feature_flags") {
|
|
1363
|
+
const items = d.seed.featureFlags.map((flag) => ({
|
|
1364
|
+
id: flag.id,
|
|
1365
|
+
name: flag.name,
|
|
1366
|
+
key: flag.key,
|
|
1367
|
+
type: flag.type,
|
|
1368
|
+
value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
|
|
1369
|
+
}));
|
|
1370
|
+
sendPage(res, url, "feature_flags", items, {});
|
|
1371
|
+
return true;
|
|
1372
|
+
}
|
|
1373
|
+
if (path === "properties") {
|
|
1374
|
+
const values = d.seed.userProperties[userId] ?? {};
|
|
1375
|
+
const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
|
|
1376
|
+
sendPage(res, url, "properties", items, {});
|
|
1377
|
+
return true;
|
|
1378
|
+
}
|
|
1379
|
+
if (path === "entitlements" || path.startsWith("entitlement")) {
|
|
1380
|
+
const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
|
|
1381
|
+
const entitlements = (plan?.entitlements ?? []).map((e) => ({
|
|
1382
|
+
id: e.id,
|
|
1383
|
+
fixed_charge: e.fixedCharge,
|
|
1384
|
+
price_name: e.priceName,
|
|
1385
|
+
unit_amount: e.unitAmount,
|
|
1386
|
+
feature_key: e.featureKey,
|
|
1387
|
+
feature_name: e.featureName,
|
|
1388
|
+
entitlement_limit_max: e.limitMax,
|
|
1389
|
+
entitlement_limit_min: e.limitMin
|
|
1390
|
+
}));
|
|
1391
|
+
if (path === "entitlements") {
|
|
1392
|
+
const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
|
|
1393
|
+
sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
|
|
1394
|
+
return true;
|
|
1395
|
+
}
|
|
1396
|
+
const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
|
|
1397
|
+
const entitlement = entitlements.find((e) => e.feature_key === key);
|
|
1398
|
+
if (!entitlement) {
|
|
1399
|
+
sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
|
|
1400
|
+
} else {
|
|
1401
|
+
sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
|
|
1402
|
+
}
|
|
1403
|
+
return true;
|
|
1404
|
+
}
|
|
1405
|
+
if (path === "portal_link") {
|
|
1406
|
+
sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
|
|
1407
|
+
return true;
|
|
1408
|
+
}
|
|
1409
|
+
sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
|
|
1410
|
+
return true;
|
|
1411
|
+
}
|
|
1412
|
+
};
|
|
1413
|
+
function sendPage(res, url, field, items, extra) {
|
|
1414
|
+
const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
|
|
1415
|
+
const after = url.searchParams.get("starting_after");
|
|
1416
|
+
const start2 = after ? items.findIndex((item) => item.id === after) + 1 : 0;
|
|
1417
|
+
const page = items.slice(start2, start2 + size);
|
|
1418
|
+
const hasMore = start2 + size < items.length;
|
|
1419
|
+
sendJson2(res, 200, {
|
|
1420
|
+
data: { ...extra, [field]: page },
|
|
1421
|
+
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
1422
|
+
});
|
|
1423
|
+
}
|
|
1424
|
+
function errors(code, message) {
|
|
1425
|
+
return { errors: [{ code, message }] };
|
|
1426
|
+
}
|
|
1427
|
+
function sendJson2(res, status, body) {
|
|
1428
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1429
|
+
res.end(JSON.stringify(body));
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
// src/directory.ts
|
|
1433
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1434
|
+
var Directory = class {
|
|
1435
|
+
constructor(seed) {
|
|
1436
|
+
this.seed = seed;
|
|
1437
|
+
this.snapshot = JSON.stringify(seed);
|
|
1438
|
+
}
|
|
1439
|
+
seed;
|
|
1440
|
+
userMeta = /* @__PURE__ */ new Map();
|
|
1441
|
+
orgMeta = /* @__PURE__ */ new Map();
|
|
1442
|
+
snapshot;
|
|
1443
|
+
restore() {
|
|
1444
|
+
const original = JSON.parse(this.snapshot);
|
|
1445
|
+
for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
|
|
1446
|
+
this.seed[key].splice(0, this.seed[key].length, ...original[key]);
|
|
1447
|
+
}
|
|
1448
|
+
this.userMeta.clear();
|
|
1449
|
+
this.orgMeta.clear();
|
|
1450
|
+
}
|
|
1451
|
+
user(id) {
|
|
1452
|
+
return this.seed.users.find((user) => user.id === id);
|
|
1453
|
+
}
|
|
1454
|
+
meta(user) {
|
|
1455
|
+
let meta = this.userMeta.get(user.id);
|
|
1456
|
+
if (!meta) {
|
|
1457
|
+
meta = {
|
|
1458
|
+
providedId: null,
|
|
1459
|
+
isSuspended: false,
|
|
1460
|
+
isPasswordResetRequested: false,
|
|
1461
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1462
|
+
totalSignIns: 0,
|
|
1463
|
+
lastSignedIn: null
|
|
1464
|
+
};
|
|
1465
|
+
this.userMeta.set(user.id, meta);
|
|
1466
|
+
}
|
|
1467
|
+
return meta;
|
|
1468
|
+
}
|
|
1469
|
+
isSuspended(userId) {
|
|
1470
|
+
return this.userMeta.get(userId)?.isSuspended ?? false;
|
|
1471
|
+
}
|
|
1472
|
+
recordSignIn(user, organizationCode) {
|
|
1473
|
+
const meta = this.meta(user);
|
|
1474
|
+
meta.totalSignIns += 1;
|
|
1475
|
+
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
1476
|
+
void organizationCode;
|
|
1477
|
+
}
|
|
1478
|
+
createUser(input) {
|
|
1479
|
+
const user = createKindeUser({
|
|
1480
|
+
id: `kp_${randomBytes3(16).toString("hex")}`,
|
|
1481
|
+
email: input.email ?? null,
|
|
1482
|
+
givenName: input.givenName ?? null,
|
|
1483
|
+
familyName: input.familyName ?? null,
|
|
1484
|
+
picture: input.picture ?? null
|
|
1485
|
+
});
|
|
1486
|
+
this.seed.users.push(user);
|
|
1487
|
+
this.meta(user).providedId = input.providedId ?? null;
|
|
1488
|
+
return user;
|
|
1489
|
+
}
|
|
1490
|
+
deleteUser(id) {
|
|
1491
|
+
const index = this.seed.users.findIndex((user) => user.id === id);
|
|
1492
|
+
if (index < 0) return false;
|
|
1493
|
+
this.seed.users.splice(index, 1);
|
|
1494
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1495
|
+
if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
|
|
1496
|
+
}
|
|
1497
|
+
this.userMeta.delete(id);
|
|
1498
|
+
return true;
|
|
1499
|
+
}
|
|
1500
|
+
organization(code) {
|
|
1501
|
+
return this.seed.organizations.find((org) => org.code === code);
|
|
1502
|
+
}
|
|
1503
|
+
orgInfo(org) {
|
|
1504
|
+
let meta = this.orgMeta.get(org.code);
|
|
1505
|
+
if (!meta) {
|
|
1506
|
+
meta = {
|
|
1507
|
+
externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
|
|
1508
|
+
handle: slug(org.name),
|
|
1509
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1510
|
+
isAllowRegistrations: false
|
|
1511
|
+
};
|
|
1512
|
+
this.orgMeta.set(org.code, meta);
|
|
1513
|
+
}
|
|
1514
|
+
return meta;
|
|
1515
|
+
}
|
|
1516
|
+
createOrganization(input) {
|
|
1517
|
+
const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
|
|
1518
|
+
this.seed.organizations.push(org);
|
|
1519
|
+
const meta = this.orgInfo(org);
|
|
1520
|
+
meta.externalId = input.externalId ?? null;
|
|
1521
|
+
if (input.handle) meta.handle = input.handle;
|
|
1522
|
+
return org;
|
|
1523
|
+
}
|
|
1524
|
+
deleteOrganization(code) {
|
|
1525
|
+
const index = this.seed.organizations.findIndex((org) => org.code === code);
|
|
1526
|
+
if (index < 0) return false;
|
|
1527
|
+
this.seed.organizations.splice(index, 1);
|
|
1528
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1529
|
+
if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
|
|
1530
|
+
}
|
|
1531
|
+
this.orgMeta.delete(code);
|
|
1532
|
+
return true;
|
|
1533
|
+
}
|
|
1534
|
+
membership(userId, organizationCode) {
|
|
1535
|
+
return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1536
|
+
}
|
|
1537
|
+
addMembership(userId, organizationCode, roles = [], permissions = []) {
|
|
1538
|
+
const existing = this.membership(userId, organizationCode);
|
|
1539
|
+
if (existing) return existing;
|
|
1540
|
+
const membership = createMembership({ userId, organizationCode, roles, permissions });
|
|
1541
|
+
this.seed.memberships.push(membership);
|
|
1542
|
+
for (const key of roles) this.ensureRole(key);
|
|
1543
|
+
for (const key of permissions) this.ensurePermission(key);
|
|
1544
|
+
return membership;
|
|
1545
|
+
}
|
|
1546
|
+
removeMembership(userId, organizationCode) {
|
|
1547
|
+
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1548
|
+
if (index < 0) return false;
|
|
1549
|
+
this.seed.memberships.splice(index, 1);
|
|
1550
|
+
return true;
|
|
1551
|
+
}
|
|
1552
|
+
role(idOrKey) {
|
|
1553
|
+
return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
|
|
1554
|
+
}
|
|
1555
|
+
permission(idOrKey) {
|
|
1556
|
+
return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
|
|
1557
|
+
}
|
|
1558
|
+
ensureRole(key, extra = {}) {
|
|
1559
|
+
const existing = this.role(key);
|
|
1560
|
+
if (existing) return existing;
|
|
1561
|
+
const role = roleRecord(key, extra);
|
|
1562
|
+
this.seed.roles.push(role);
|
|
1563
|
+
return role;
|
|
1564
|
+
}
|
|
1565
|
+
ensurePermission(key, extra = {}) {
|
|
1566
|
+
const existing = this.permission(key);
|
|
1567
|
+
if (existing) return existing;
|
|
1568
|
+
const permission = permissionRecord(key, extra);
|
|
1569
|
+
this.seed.permissions.push(permission);
|
|
1570
|
+
return permission;
|
|
1571
|
+
}
|
|
1572
|
+
deleteRole(id) {
|
|
1573
|
+
const role = this.role(id);
|
|
1574
|
+
if (!role) return void 0;
|
|
1575
|
+
this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
|
|
1576
|
+
for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
|
|
1577
|
+
return role;
|
|
1578
|
+
}
|
|
1579
|
+
deletePermission(id) {
|
|
1580
|
+
const permission = this.permission(id);
|
|
1581
|
+
if (!permission) return void 0;
|
|
1582
|
+
this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
|
|
1583
|
+
for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
|
|
1584
|
+
for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
|
|
1585
|
+
return permission;
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
|
|
1589
|
+
// src/management.ts
|
|
1590
|
+
var OK = { code: "OK", message: "Success" };
|
|
1591
|
+
var DEFAULT_PAGE_SIZE2 = 10;
|
|
1592
|
+
var MAX_PAGE_SIZE = 500;
|
|
1593
|
+
var ManagementApi = class {
|
|
1594
|
+
constructor(testkit, directory, webhooks) {
|
|
1595
|
+
this.testkit = testkit;
|
|
1596
|
+
this.directory = directory;
|
|
1597
|
+
this.webhooks = webhooks;
|
|
1598
|
+
this.register();
|
|
1599
|
+
}
|
|
1600
|
+
testkit;
|
|
1601
|
+
directory;
|
|
1602
|
+
webhooks;
|
|
1603
|
+
routes = [];
|
|
1604
|
+
async handle(req, res, url, readBody) {
|
|
1605
|
+
if (!url.pathname.startsWith("/api/v1/")) return false;
|
|
1606
|
+
const method = req.method ?? "GET";
|
|
1607
|
+
const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
1608
|
+
if (!route) {
|
|
1609
|
+
sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
|
|
1610
|
+
return true;
|
|
1611
|
+
}
|
|
1612
|
+
const token2 = await this.authenticate(req.headers.authorization);
|
|
1613
|
+
if ("error" in token2) {
|
|
1614
|
+
sendJson3(res, 403, errors2(token2.code, token2.error));
|
|
1615
|
+
return true;
|
|
1616
|
+
}
|
|
1617
|
+
const granted = typeof token2.payload.scope === "string" ? token2.payload.scope.split(" ").filter(Boolean) : [];
|
|
1618
|
+
if (granted.length > 0 && !granted.includes(route.scope)) {
|
|
1619
|
+
sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
|
|
1620
|
+
return true;
|
|
1621
|
+
}
|
|
1622
|
+
const match = route.pattern.exec(url.pathname);
|
|
1623
|
+
const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
|
|
1624
|
+
const body = method === "GET" || method === "DELETE" ? {} : await readBody();
|
|
1625
|
+
const [status, payload] = await route.handler({ params, query: url.searchParams, body });
|
|
1626
|
+
sendJson3(res, status, payload);
|
|
1627
|
+
return true;
|
|
1628
|
+
}
|
|
1629
|
+
async authenticate(header) {
|
|
1630
|
+
if (!header?.startsWith("Bearer ")) {
|
|
1631
|
+
return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
|
|
1632
|
+
}
|
|
1633
|
+
let payload;
|
|
1634
|
+
try {
|
|
1635
|
+
payload = await this.testkit.verify(header.slice(7));
|
|
1636
|
+
} catch {
|
|
1637
|
+
return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
|
|
1638
|
+
}
|
|
1639
|
+
const audience = `${this.testkit.issuer}/api`;
|
|
1640
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
1641
|
+
if (!aud.includes(audience)) {
|
|
1642
|
+
return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
|
|
1643
|
+
}
|
|
1644
|
+
if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
|
|
1645
|
+
return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
|
|
1646
|
+
}
|
|
1647
|
+
return { payload };
|
|
1648
|
+
}
|
|
1649
|
+
route(method, path, scope, handler) {
|
|
1650
|
+
const keys = [];
|
|
1651
|
+
const pattern = new RegExp(
|
|
1652
|
+
`^${path.replace(/\{(\w+)\}/g, (_, key) => {
|
|
1653
|
+
keys.push(key);
|
|
1654
|
+
return "([^/]+)";
|
|
1655
|
+
})}$`
|
|
1656
|
+
);
|
|
1657
|
+
this.routes.push({ method, pattern, keys, scope, handler });
|
|
1658
|
+
}
|
|
1659
|
+
register() {
|
|
1660
|
+
const d = this.directory;
|
|
1661
|
+
this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
|
|
1662
|
+
let users = [...d.seed.users];
|
|
1663
|
+
const userId = query.get("user_id");
|
|
1664
|
+
const email = query.get("email")?.toLowerCase();
|
|
1665
|
+
if (userId) users = users.filter((u) => u.id === userId);
|
|
1666
|
+
if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
|
|
1667
|
+
const page = paginate(users, query);
|
|
1668
|
+
return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
|
|
1669
|
+
});
|
|
1670
|
+
this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
|
|
1671
|
+
const user = d.user(query.get("id") ?? "");
|
|
1672
|
+
return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
|
|
1673
|
+
});
|
|
1674
|
+
this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
|
|
1675
|
+
const profile = body.profile ?? {};
|
|
1676
|
+
const identities = Array.isArray(body.identities) ? body.identities : [];
|
|
1677
|
+
const emailIdentity = identities.find((i) => i.type === "email");
|
|
1678
|
+
const email = (emailIdentity?.details ?? {}).email;
|
|
1679
|
+
if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
|
|
1680
|
+
return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
|
|
1681
|
+
}
|
|
1682
|
+
const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
|
|
1683
|
+
if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
|
|
1684
|
+
const user = d.createUser({
|
|
1685
|
+
email: typeof email === "string" ? email : null,
|
|
1686
|
+
givenName: str(profile.given_name),
|
|
1687
|
+
familyName: str(profile.family_name),
|
|
1688
|
+
picture: str(profile.picture),
|
|
1689
|
+
providedId: str(body.provided_id)
|
|
1690
|
+
});
|
|
1691
|
+
if (orgCode) d.addMembership(user.id, orgCode);
|
|
1692
|
+
this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
|
|
1693
|
+
return [
|
|
1694
|
+
200,
|
|
1695
|
+
{ id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
|
|
1696
|
+
];
|
|
1697
|
+
});
|
|
1698
|
+
this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
|
|
1699
|
+
const user = d.user(query.get("id") ?? "");
|
|
1700
|
+
if (!user) return notFound("USER_INVALID", "No user has that id.");
|
|
1701
|
+
if (typeof body.given_name === "string") user.givenName = body.given_name;
|
|
1702
|
+
if (typeof body.family_name === "string") user.familyName = body.family_name;
|
|
1703
|
+
if (typeof body.picture === "string") user.picture = body.picture;
|
|
1704
|
+
const meta = d.meta(user);
|
|
1705
|
+
if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
|
|
1706
|
+
if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
|
|
1707
|
+
if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
|
|
1708
|
+
this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
|
|
1709
|
+
return [
|
|
1710
|
+
200,
|
|
1711
|
+
{
|
|
1712
|
+
id: user.id,
|
|
1713
|
+
given_name: user.givenName,
|
|
1714
|
+
family_name: user.familyName,
|
|
1715
|
+
email: user.email,
|
|
1716
|
+
is_suspended: meta.isSuspended,
|
|
1717
|
+
is_password_reset_requested: meta.isPasswordResetRequested,
|
|
1718
|
+
picture: user.picture
|
|
1719
|
+
}
|
|
1720
|
+
];
|
|
1721
|
+
});
|
|
1722
|
+
this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
|
|
1723
|
+
const id = query.get("id") ?? "";
|
|
1724
|
+
if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
|
|
1725
|
+
this.webhooks.emit("user.deleted", { user: { id } });
|
|
1726
|
+
return [200, OK];
|
|
1727
|
+
});
|
|
1728
|
+
this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
|
|
1729
|
+
const page = paginate(d.seed.organizations, query);
|
|
1730
|
+
return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
|
|
1731
|
+
});
|
|
1732
|
+
this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
|
|
1733
|
+
const org = d.organization(query.get("code") ?? "");
|
|
1734
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1735
|
+
const meta = d.orgInfo(org);
|
|
1736
|
+
return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
|
|
1737
|
+
});
|
|
1738
|
+
this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
|
|
1739
|
+
if (typeof body.name !== "string" || body.name.trim() === "") {
|
|
1740
|
+
return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
|
|
1741
|
+
}
|
|
1742
|
+
const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
|
|
1743
|
+
if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
|
|
1744
|
+
this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
|
|
1745
|
+
return [200, { ...OK, organization: { code: org.code } }];
|
|
1746
|
+
});
|
|
1747
|
+
this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
|
|
1748
|
+
const org = d.organization(params.org_code);
|
|
1749
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1750
|
+
const meta = d.orgInfo(org);
|
|
1751
|
+
if (typeof body.name === "string") org.name = body.name;
|
|
1752
|
+
if (typeof body.external_id === "string") meta.externalId = body.external_id;
|
|
1753
|
+
if (typeof body.handle === "string") meta.handle = body.handle;
|
|
1754
|
+
if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
|
|
1755
|
+
this.webhooks.emit("organization.updated", {
|
|
1756
|
+
organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
|
|
1757
|
+
});
|
|
1758
|
+
return [200, OK];
|
|
1759
|
+
});
|
|
1760
|
+
this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
|
|
1761
|
+
if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1762
|
+
this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
|
|
1763
|
+
return [200, OK];
|
|
1764
|
+
});
|
|
1765
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
|
|
1766
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1767
|
+
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);
|
|
1768
|
+
const page = paginate(members, query);
|
|
1769
|
+
return [
|
|
1770
|
+
200,
|
|
1771
|
+
{
|
|
1772
|
+
...OK,
|
|
1773
|
+
organization_users: page.items.map(({ membership, user }) => ({
|
|
1774
|
+
id: user.id,
|
|
1775
|
+
email: user.email,
|
|
1776
|
+
full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
|
|
1777
|
+
last_name: user.familyName,
|
|
1778
|
+
first_name: user.givenName,
|
|
1779
|
+
picture: user.picture,
|
|
1780
|
+
joined_on: d.meta(user).createdOn,
|
|
1781
|
+
last_accessed_on: d.meta(user).lastSignedIn,
|
|
1782
|
+
is_suspended: d.meta(user).isSuspended,
|
|
1783
|
+
roles: [...membership.roles]
|
|
1784
|
+
})),
|
|
1785
|
+
next_token: page.nextToken
|
|
1786
|
+
}
|
|
1787
|
+
];
|
|
1788
|
+
});
|
|
1789
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
|
|
1790
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1791
|
+
const users = Array.isArray(body.users) ? body.users : [];
|
|
1792
|
+
const added = [];
|
|
1793
|
+
const blocked = [];
|
|
1794
|
+
for (const entry of users) {
|
|
1795
|
+
const id = typeof entry.id === "string" ? entry.id : "";
|
|
1796
|
+
if (!d.user(id)) {
|
|
1797
|
+
blocked.push(id);
|
|
1798
|
+
continue;
|
|
1799
|
+
}
|
|
1800
|
+
d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
|
|
1801
|
+
added.push(id);
|
|
1802
|
+
}
|
|
1803
|
+
return [200, { ...OK, users_added: added, users_blocked: blocked }];
|
|
1804
|
+
});
|
|
1805
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
|
|
1806
|
+
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}.`);
|
|
1807
|
+
});
|
|
1808
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
|
|
1809
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1810
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1811
|
+
const roles = membership.roles.map((key) => d.ensureRole(key));
|
|
1812
|
+
return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
|
|
1813
|
+
});
|
|
1814
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
|
|
1815
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1816
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1817
|
+
const role = d.role(str(body.role_id) ?? "");
|
|
1818
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1819
|
+
if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
|
|
1820
|
+
return [200, OK];
|
|
1821
|
+
});
|
|
1822
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
|
|
1823
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1824
|
+
const role = d.role(params.role_id);
|
|
1825
|
+
if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
|
|
1826
|
+
membership.roles = membership.roles.filter((key) => key !== role.key);
|
|
1827
|
+
return [200, OK];
|
|
1828
|
+
});
|
|
1829
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
|
|
1830
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1831
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1832
|
+
const permissions = effectivePermissions(d.seed, membership).map((key) => {
|
|
1833
|
+
const permission = d.ensurePermission(key);
|
|
1834
|
+
const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
|
|
1835
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
|
|
1836
|
+
});
|
|
1837
|
+
return [200, { ...OK, permissions }];
|
|
1838
|
+
});
|
|
1839
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
|
|
1840
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1841
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1842
|
+
const permission = d.permission(str(body.permission_id) ?? "");
|
|
1843
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1844
|
+
if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
|
|
1845
|
+
return [200, OK];
|
|
1846
|
+
});
|
|
1847
|
+
this.route(
|
|
1848
|
+
"DELETE",
|
|
1849
|
+
"/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
|
|
1850
|
+
"delete:organization_user_permissions",
|
|
1851
|
+
({ params }) => {
|
|
1852
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1853
|
+
const permission = d.permission(params.permission_id);
|
|
1854
|
+
if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
|
|
1855
|
+
membership.permissions = membership.permissions.filter((key) => key !== permission.key);
|
|
1856
|
+
return [200, OK];
|
|
1857
|
+
}
|
|
1858
|
+
);
|
|
1859
|
+
this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
|
|
1860
|
+
const page = paginate(d.seed.roles, query);
|
|
1861
|
+
return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
|
|
1862
|
+
});
|
|
1863
|
+
this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
|
|
1864
|
+
const key = str(body.key);
|
|
1865
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
|
|
1866
|
+
if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
|
|
1867
|
+
const role = d.ensureRole(key, {
|
|
1868
|
+
name: str(body.name) ?? void 0,
|
|
1869
|
+
description: str(body.description) ?? void 0,
|
|
1870
|
+
isDefault: body.is_default_role === true
|
|
1871
|
+
});
|
|
1872
|
+
this.webhooks.emit("role.created", {
|
|
1873
|
+
role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
|
|
1874
|
+
});
|
|
1875
|
+
return [201, { ...OK, role: { id: role.id } }];
|
|
1876
|
+
});
|
|
1877
|
+
this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
|
|
1878
|
+
const role = d.role(params.role_id);
|
|
1879
|
+
return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
|
|
1880
|
+
});
|
|
1881
|
+
this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
|
|
1882
|
+
const role = d.deleteRole(params.role_id);
|
|
1883
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1884
|
+
this.webhooks.emit("role.deleted", { role: { id: role.id } });
|
|
1885
|
+
return [200, OK];
|
|
1886
|
+
});
|
|
1887
|
+
this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
|
|
1888
|
+
const role = d.role(params.role_id);
|
|
1889
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1890
|
+
return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
|
|
1891
|
+
});
|
|
1892
|
+
this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
|
|
1893
|
+
const page = paginate(d.seed.permissions, query);
|
|
1894
|
+
return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
|
|
1895
|
+
});
|
|
1896
|
+
this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
|
|
1897
|
+
const key = str(body.key);
|
|
1898
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
|
|
1899
|
+
if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
|
|
1900
|
+
const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
|
|
1901
|
+
this.webhooks.emit("permission.created", {
|
|
1902
|
+
permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
|
|
1903
|
+
});
|
|
1904
|
+
return [201, OK];
|
|
1905
|
+
});
|
|
1906
|
+
this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
|
|
1907
|
+
const permission = d.deletePermission(params.permission_id);
|
|
1908
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1909
|
+
this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
|
|
1910
|
+
return [200, OK];
|
|
1911
|
+
});
|
|
1912
|
+
}
|
|
1913
|
+
userListItem(user) {
|
|
1914
|
+
const meta = this.directory.meta(user);
|
|
1915
|
+
return {
|
|
1916
|
+
id: user.id,
|
|
1917
|
+
provided_id: meta.providedId,
|
|
1918
|
+
email: user.email,
|
|
1919
|
+
phone: null,
|
|
1920
|
+
username: null,
|
|
1921
|
+
last_name: user.familyName,
|
|
1922
|
+
first_name: user.givenName,
|
|
1923
|
+
is_suspended: meta.isSuspended,
|
|
1924
|
+
picture: user.picture,
|
|
1925
|
+
total_sign_ins: meta.totalSignIns,
|
|
1926
|
+
failed_sign_ins: 0,
|
|
1927
|
+
last_signed_in: meta.lastSignedIn,
|
|
1928
|
+
created_on: meta.createdOn,
|
|
1929
|
+
organizations: this.organizationsOf(user),
|
|
1930
|
+
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
1931
|
+
};
|
|
1932
|
+
}
|
|
1933
|
+
userDetail(user) {
|
|
1934
|
+
const { email, ...rest } = this.userListItem(user);
|
|
1935
|
+
return { ...rest, preferred_email: email };
|
|
1936
|
+
}
|
|
1937
|
+
organizationsOf(user) {
|
|
1938
|
+
return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
|
|
1939
|
+
}
|
|
1940
|
+
organizationItem(org) {
|
|
1941
|
+
const meta = this.directory.orgInfo(org);
|
|
1942
|
+
return {
|
|
1943
|
+
code: org.code,
|
|
1944
|
+
name: org.name,
|
|
1945
|
+
handle: meta.handle,
|
|
1946
|
+
is_default: false,
|
|
1947
|
+
external_id: meta.externalId,
|
|
1948
|
+
is_auto_membership_enabled: false
|
|
1949
|
+
};
|
|
1950
|
+
}
|
|
1951
|
+
organizationEvent(org) {
|
|
1952
|
+
const meta = this.directory.orgInfo(org);
|
|
1953
|
+
return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
|
|
1954
|
+
}
|
|
1955
|
+
roleItem(role) {
|
|
1956
|
+
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
1957
|
+
}
|
|
1958
|
+
permissionItem(permission) {
|
|
1959
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
1960
|
+
}
|
|
1961
|
+
};
|
|
1962
|
+
function paginate(items, query) {
|
|
1963
|
+
const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
|
|
1964
|
+
const token2 = query.get("next_token");
|
|
1965
|
+
const offset = token2 ? Number(Buffer.from(token2, "base64url").toString("utf8")) || 0 : 0;
|
|
1966
|
+
const page = items.slice(offset, offset + size);
|
|
1967
|
+
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
1968
|
+
return { items: page, nextToken: next };
|
|
1969
|
+
}
|
|
1970
|
+
function errors2(code, message) {
|
|
1971
|
+
return { errors: [{ code, message }] };
|
|
1972
|
+
}
|
|
1973
|
+
function notFound(code, message) {
|
|
1974
|
+
return [404, errors2(code, message)];
|
|
1975
|
+
}
|
|
1976
|
+
function str(value) {
|
|
1977
|
+
return typeof value === "string" ? value : null;
|
|
1978
|
+
}
|
|
1979
|
+
function strings(value) {
|
|
1980
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
1981
|
+
}
|
|
1982
|
+
function sendJson3(res, status, body) {
|
|
1983
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1984
|
+
res.end(JSON.stringify(body));
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1016
1987
|
// src/failures.ts
|
|
1017
1988
|
var MAX_DELAY_MS = 6e4;
|
|
1018
1989
|
var FailureInjector = class {
|
|
@@ -1094,7 +2065,7 @@ function validate(rule) {
|
|
|
1094
2065
|
}
|
|
1095
2066
|
|
|
1096
2067
|
// src/webhooks.ts
|
|
1097
|
-
import { randomBytes as
|
|
2068
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
1098
2069
|
var WEBHOOK_EVENT_TYPES = [
|
|
1099
2070
|
"user.created",
|
|
1100
2071
|
"user.updated",
|
|
@@ -1177,7 +2148,7 @@ var WebhookDispatcher = class {
|
|
|
1177
2148
|
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1178
2149
|
const event = {
|
|
1179
2150
|
data: options.data ?? this.buildData(options),
|
|
1180
|
-
event_id: `event_${
|
|
2151
|
+
event_id: `event_${randomBytes4(16).toString("hex")}`,
|
|
1181
2152
|
event_timestamp: timestamp,
|
|
1182
2153
|
source: options.source ?? "admin",
|
|
1183
2154
|
timestamp,
|
|
@@ -1210,7 +2181,7 @@ var WebhookDispatcher = class {
|
|
|
1210
2181
|
options.invalid === "stale" ? void 0 : options.invalid
|
|
1211
2182
|
);
|
|
1212
2183
|
const jobs = targets.flatMap((target) => {
|
|
1213
|
-
const webhookId = `wh_${
|
|
2184
|
+
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
1214
2185
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1215
2186
|
});
|
|
1216
2187
|
return Promise.all(jobs);
|
|
@@ -1291,6 +2262,13 @@ var WebhookDispatcher = class {
|
|
|
1291
2262
|
);
|
|
1292
2263
|
}
|
|
1293
2264
|
}
|
|
2265
|
+
emit(type, data, source = "api") {
|
|
2266
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2267
|
+
void this.send({ type, data, source }).catch(() => void 0);
|
|
2268
|
+
}
|
|
2269
|
+
userEventData(user) {
|
|
2270
|
+
return this.userPayload(user);
|
|
2271
|
+
}
|
|
1294
2272
|
emitForUser(type, user) {
|
|
1295
2273
|
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1296
2274
|
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
@@ -1355,7 +2333,7 @@ function isHttpUrl2(value) {
|
|
|
1355
2333
|
}
|
|
1356
2334
|
}
|
|
1357
2335
|
function sleep(ms) {
|
|
1358
|
-
return new Promise((
|
|
2336
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
1359
2337
|
}
|
|
1360
2338
|
|
|
1361
2339
|
// src/server.ts
|
|
@@ -1373,30 +2351,36 @@ async function startKindeTestkit(options = {}) {
|
|
|
1373
2351
|
const seed = resolveSeed(options.seed ?? {});
|
|
1374
2352
|
const failures = new FailureInjector();
|
|
1375
2353
|
let ready;
|
|
1376
|
-
const testkitReady = new Promise((
|
|
1377
|
-
const
|
|
2354
|
+
const testkitReady = new Promise((resolve3) => ready = resolve3);
|
|
2355
|
+
const listener = (req, res) => {
|
|
1378
2356
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1379
|
-
}
|
|
1380
|
-
|
|
2357
|
+
};
|
|
2358
|
+
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
2359
|
+
const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
|
|
2360
|
+
await new Promise((resolve3, reject) => {
|
|
1381
2361
|
server.once("error", reject);
|
|
1382
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
2362
|
+
server.listen(options.port ?? 4400, host, () => resolve3());
|
|
1383
2363
|
});
|
|
1384
2364
|
const { port } = server.address();
|
|
1385
2365
|
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1386
|
-
const url =
|
|
2366
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1387
2367
|
const testkit = await KindeTestkit.create({
|
|
1388
2368
|
issuer: options.issuer ?? options.seed?.issuer ?? url,
|
|
1389
2369
|
audience: options.audience ?? options.seed?.audience,
|
|
1390
2370
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1391
2371
|
});
|
|
2372
|
+
const directory = new Directory(seed);
|
|
1392
2373
|
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
1393
|
-
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
|
|
2374
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
|
|
2375
|
+
const management = new ManagementApi(testkit, directory, webhooks);
|
|
2376
|
+
const account = new AccountApi(testkit, directory);
|
|
1394
2377
|
const reset2 = () => {
|
|
1395
2378
|
auth.reset();
|
|
1396
2379
|
failures.clear();
|
|
1397
2380
|
webhooks.reset();
|
|
2381
|
+
directory.restore();
|
|
1398
2382
|
};
|
|
1399
|
-
ready({ testkit, auth, seed, failures, webhooks, reset: reset2 });
|
|
2383
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset: reset2 });
|
|
1400
2384
|
return {
|
|
1401
2385
|
url,
|
|
1402
2386
|
issuer: testkit.issuer,
|
|
@@ -1406,10 +2390,12 @@ async function startKindeTestkit(options = {}) {
|
|
|
1406
2390
|
seed,
|
|
1407
2391
|
failures,
|
|
1408
2392
|
webhooks,
|
|
2393
|
+
directory,
|
|
2394
|
+
certificatePath: certificate?.certPath ?? null,
|
|
1409
2395
|
reset: reset2,
|
|
1410
|
-
close: () => new Promise((
|
|
2396
|
+
close: () => new Promise((resolve3, reject) => {
|
|
1411
2397
|
server.closeAllConnections();
|
|
1412
|
-
server.close((error) => error ? reject(error) :
|
|
2398
|
+
server.close((error) => error ? reject(error) : resolve3());
|
|
1413
2399
|
})
|
|
1414
2400
|
};
|
|
1415
2401
|
}
|
|
@@ -1422,68 +2408,77 @@ async function handle(req, res, context) {
|
|
|
1422
2408
|
const failure = failures.take(method, pathname);
|
|
1423
2409
|
if (failure) {
|
|
1424
2410
|
if (failure.hang) return;
|
|
1425
|
-
if (failure.delayMs > 0) await new Promise((
|
|
2411
|
+
if (failure.delayMs > 0) await new Promise((resolve3) => setTimeout(resolve3, failure.delayMs));
|
|
1426
2412
|
if (failure.status !== null) {
|
|
1427
2413
|
const headers = {};
|
|
1428
2414
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1429
|
-
return
|
|
2415
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1430
2416
|
}
|
|
1431
2417
|
}
|
|
1432
2418
|
}
|
|
1433
2419
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
2420
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
|
|
2421
|
+
if (await context.account.handle(req, res, url)) return;
|
|
2422
|
+
if (method === "GET" && pathname === "/testkit/portal") {
|
|
2423
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
2424
|
+
res.end(
|
|
2425
|
+
`<!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>`
|
|
2426
|
+
);
|
|
2427
|
+
return;
|
|
2428
|
+
}
|
|
1434
2429
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1435
|
-
return
|
|
2430
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1436
2431
|
}
|
|
1437
2432
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1438
|
-
return
|
|
2433
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1439
2434
|
}
|
|
1440
2435
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1441
|
-
return
|
|
2436
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1442
2437
|
}
|
|
1443
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
2438
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
1444
2439
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1445
|
-
return
|
|
2440
|
+
return sendJson4(res, 200, seed.organizations);
|
|
1446
2441
|
}
|
|
1447
2442
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1448
|
-
return
|
|
2443
|
+
return sendJson4(res, 200, seed.memberships);
|
|
1449
2444
|
}
|
|
1450
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
2445
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1451
2446
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1452
|
-
return
|
|
2447
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1453
2448
|
}
|
|
1454
2449
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1455
2450
|
failures.clear();
|
|
1456
|
-
return
|
|
2451
|
+
return sendJson4(res, 200, { ok: true });
|
|
1457
2452
|
}
|
|
1458
2453
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1459
2454
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1460
|
-
return
|
|
2455
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1461
2456
|
}
|
|
1462
2457
|
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1463
|
-
return
|
|
2458
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
1464
2459
|
}
|
|
1465
2460
|
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1466
|
-
return
|
|
2461
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1467
2462
|
}
|
|
1468
|
-
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return
|
|
1469
|
-
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return
|
|
2463
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
|
|
2464
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
|
|
1470
2465
|
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1471
|
-
return
|
|
2466
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1472
2467
|
}
|
|
1473
2468
|
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1474
2469
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1475
|
-
return
|
|
2470
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1476
2471
|
}
|
|
1477
2472
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1478
2473
|
context.reset();
|
|
1479
|
-
return
|
|
2474
|
+
return sendJson4(res, 200, { ok: true });
|
|
1480
2475
|
}
|
|
1481
2476
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1482
2477
|
const body = await readJson(req);
|
|
1483
2478
|
const accessToken = await issueToken(testkit, seed, body);
|
|
1484
|
-
return
|
|
2479
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
1485
2480
|
}
|
|
1486
|
-
return
|
|
2481
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
1487
2482
|
}
|
|
1488
2483
|
function discovery(testkit) {
|
|
1489
2484
|
const base = testkit.issuer;
|
|
@@ -1542,7 +2537,11 @@ async function issueToken(testkit, seed, body) {
|
|
|
1542
2537
|
});
|
|
1543
2538
|
if (permissions) scenario.permissions = permissions;
|
|
1544
2539
|
if (roles) scenario.roles = roles;
|
|
1545
|
-
return await testkit.tokenFor(scenario, {
|
|
2540
|
+
return await testkit.tokenFor(scenario, {
|
|
2541
|
+
expiresIn,
|
|
2542
|
+
invalid: invalid2,
|
|
2543
|
+
featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
|
|
2544
|
+
});
|
|
1546
2545
|
}
|
|
1547
2546
|
const options = {
|
|
1548
2547
|
subject: optionalString(input, "subject"),
|
|
@@ -1607,7 +2606,7 @@ async function readText(req) {
|
|
|
1607
2606
|
}
|
|
1608
2607
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1609
2608
|
}
|
|
1610
|
-
function
|
|
2609
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1611
2610
|
res.writeHead(status, {
|
|
1612
2611
|
"content-type": "application/json; charset=utf-8",
|
|
1613
2612
|
"cache-control": "no-store",
|
|
@@ -1621,10 +2620,10 @@ function sendError(res, error) {
|
|
|
1621
2620
|
return;
|
|
1622
2621
|
}
|
|
1623
2622
|
if (error instanceof TestkitError) {
|
|
1624
|
-
|
|
2623
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1625
2624
|
return;
|
|
1626
2625
|
}
|
|
1627
|
-
|
|
2626
|
+
sendJson4(res, 500, {
|
|
1628
2627
|
error: "server_error",
|
|
1629
2628
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1630
2629
|
});
|
|
@@ -1771,6 +2770,15 @@ async function runDoctor(options) {
|
|
|
1771
2770
|
} else {
|
|
1772
2771
|
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1773
2772
|
}
|
|
2773
|
+
if (issuer?.startsWith("https://")) {
|
|
2774
|
+
checks.push(
|
|
2775
|
+
env.NODE_EXTRA_CA_CERTS ? { name: "NODE_EXTRA_CA_CERTS", status: "pass", detail: `${env.NODE_EXTRA_CA_CERTS}.` } : {
|
|
2776
|
+
name: "NODE_EXTRA_CA_CERTS",
|
|
2777
|
+
status: "warn",
|
|
2778
|
+
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."
|
|
2779
|
+
}
|
|
2780
|
+
);
|
|
2781
|
+
}
|
|
1774
2782
|
const site = env.KINDE_SITE_URL;
|
|
1775
2783
|
if (!site) {
|
|
1776
2784
|
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
@@ -1812,6 +2820,7 @@ Usage
|
|
|
1812
2820
|
kinde-testkit fail <path> [options] Make an endpoint fail, slow down or hang
|
|
1813
2821
|
kinde-testkit reset Clear sign-in sessions and failure rules
|
|
1814
2822
|
kinde-testkit webhook <type> [options] Send a signed webhook event
|
|
2823
|
+
kinde-testkit cert [--dir <dir>] Create the local HTTPS certificate and print its path
|
|
1815
2824
|
|
|
1816
2825
|
start
|
|
1817
2826
|
--port <n> Port to listen on (default 4400)
|
|
@@ -1822,6 +2831,8 @@ start
|
|
|
1822
2831
|
--seed <file> Seed file (default ./kinde-testkit.json when it exists)
|
|
1823
2832
|
--allow-public Allow binding to a non-loopback interface
|
|
1824
2833
|
--webhook <url> Send webhooks to this URL (repeatable)
|
|
2834
|
+
--https Serve HTTPS with a local certificate (needed by @kinde/management-api-js)
|
|
2835
|
+
--cert-dir <dir> Where to keep that certificate (default ./.kinde-testkit)
|
|
1825
2836
|
|
|
1826
2837
|
token
|
|
1827
2838
|
--url <url> Running issuer (default ${DEFAULT_URL})
|
|
@@ -1893,6 +2904,8 @@ async function main(argv) {
|
|
|
1893
2904
|
case "webhook":
|
|
1894
2905
|
case "webhooks":
|
|
1895
2906
|
return webhook(rest);
|
|
2907
|
+
case "cert":
|
|
2908
|
+
return cert(rest);
|
|
1896
2909
|
case void 0:
|
|
1897
2910
|
case "help":
|
|
1898
2911
|
case "--help":
|
|
@@ -1915,10 +2928,12 @@ async function start(args) {
|
|
|
1915
2928
|
seed: { type: "string" },
|
|
1916
2929
|
"allow-public": { type: "boolean" },
|
|
1917
2930
|
webhook: { type: "string", multiple: true },
|
|
2931
|
+
https: { type: "boolean" },
|
|
2932
|
+
"cert-dir": { type: "string" },
|
|
1918
2933
|
json: { type: "boolean" }
|
|
1919
2934
|
}
|
|
1920
2935
|
});
|
|
1921
|
-
const seedPath = values.seed ?? (
|
|
2936
|
+
const seedPath = values.seed ?? (existsSync2(DEFAULT_SEED_FILE) ? DEFAULT_SEED_FILE : void 0);
|
|
1922
2937
|
const seed = seedPath ? readSeed(seedPath) : values.webhook ? {} : void 0;
|
|
1923
2938
|
if (seed && values.webhook) seed.webhooks = [...seed.webhooks ?? [], ...values.webhook.map((url) => ({ url }))];
|
|
1924
2939
|
const running = await startKindeTestkit({
|
|
@@ -1928,7 +2943,8 @@ async function start(args) {
|
|
|
1928
2943
|
audience: values.audience ? csv(values.audience) : void 0,
|
|
1929
2944
|
clientId: values["client-id"],
|
|
1930
2945
|
seed,
|
|
1931
|
-
allowPublic: values["allow-public"]
|
|
2946
|
+
allowPublic: values["allow-public"],
|
|
2947
|
+
https: values.https ? { certDirectory: values["cert-dir"] } : void 0
|
|
1932
2948
|
});
|
|
1933
2949
|
if (values.json) {
|
|
1934
2950
|
process.stdout.write(
|
|
@@ -1956,10 +2972,11 @@ async function start(args) {
|
|
|
1956
2972
|
`Sign-in page: ${running.url}/oauth2/auth`,
|
|
1957
2973
|
`Token: POST ${running.url}/testkit/token`,
|
|
1958
2974
|
"",
|
|
1959
|
-
`Seed: ${seedPath ?
|
|
2975
|
+
`Seed: ${seedPath ? resolve2(seedPath) : "none"}`,
|
|
1960
2976
|
`Users: ${running.seed.users.length}`,
|
|
1961
2977
|
`Organizations: ${running.seed.organizations.length}`,
|
|
1962
2978
|
`Webhooks: ${running.webhooks.listEndpoints().map((e) => e.url).join(", ") || "none"}`,
|
|
2979
|
+
...running.certificatePath ? ["", "HTTPS uses a local certificate. Start Node processes that call the testkit with:", ` NODE_EXTRA_CA_CERTS=${running.certificatePath}`] : [],
|
|
1963
2980
|
"",
|
|
1964
2981
|
"Test tokens only. Press Ctrl+C to stop.",
|
|
1965
2982
|
""
|
|
@@ -2065,14 +3082,14 @@ async function doctor(args) {
|
|
|
2065
3082
|
json: { type: "boolean" }
|
|
2066
3083
|
}
|
|
2067
3084
|
});
|
|
2068
|
-
const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) =>
|
|
3085
|
+
const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) => existsSync2(file));
|
|
2069
3086
|
const env = {};
|
|
2070
3087
|
for (const file of files) {
|
|
2071
|
-
if (!
|
|
2072
|
-
Object.assign(env, parseEnvFile(
|
|
3088
|
+
if (!existsSync2(file)) throw new TestkitError("INVALID_REQUEST", `No env file at ${resolve2(file)}.`);
|
|
3089
|
+
Object.assign(env, parseEnvFile(readFileSync2(file, "utf8")));
|
|
2073
3090
|
}
|
|
2074
3091
|
for (const [key, value] of Object.entries(process.env)) {
|
|
2075
|
-
if (key.startsWith("KINDE_") && value !== void 0) env[key] = value;
|
|
3092
|
+
if ((key.startsWith("KINDE_") || key === "NODE_EXTRA_CA_CERTS") && value !== void 0) env[key] = value;
|
|
2076
3093
|
}
|
|
2077
3094
|
const report = await runDoctor({ url: values.url ?? DEFAULT_URL, env });
|
|
2078
3095
|
if (values.json) {
|
|
@@ -2234,6 +3251,22 @@ ${types.billing.map((t) => ` ${t}`).join("\n")}
|
|
|
2234
3251
|
`);
|
|
2235
3252
|
if (deliveries.some((d) => !d.delivered)) process.exitCode = 1;
|
|
2236
3253
|
}
|
|
3254
|
+
async function cert(args) {
|
|
3255
|
+
const { values } = parseArgs({ args, options: { dir: { type: "string" }, json: { type: "boolean" } } });
|
|
3256
|
+
const certificate = ensureLocalCertificate(values.dir);
|
|
3257
|
+
if (values.json) {
|
|
3258
|
+
process.stdout.write(`${JSON.stringify({ certPath: certificate.certPath, created: certificate.created })}
|
|
3259
|
+
`);
|
|
3260
|
+
return;
|
|
3261
|
+
}
|
|
3262
|
+
process.stdout.write(
|
|
3263
|
+
`${certificate.created ? "Created" : "Using"} ${certificate.certPath}
|
|
3264
|
+
|
|
3265
|
+
Trust it in Node processes that call the testkit over HTTPS:
|
|
3266
|
+
NODE_EXTRA_CA_CERTS=${certificate.certPath}
|
|
3267
|
+
`
|
|
3268
|
+
);
|
|
3269
|
+
}
|
|
2237
3270
|
function describeDelivery(delivery) {
|
|
2238
3271
|
const attempts = delivery.attempts ?? [];
|
|
2239
3272
|
const outcome = attempts.map((a) => a.status === null ? "no answer" : String(a.status)).join(", ");
|
|
@@ -2301,9 +3334,9 @@ ${details.map((d) => ` - ${d}
|
|
|
2301
3334
|
}
|
|
2302
3335
|
function readSeed(path) {
|
|
2303
3336
|
try {
|
|
2304
|
-
return JSON.parse(
|
|
3337
|
+
return JSON.parse(readFileSync2(path, "utf8"));
|
|
2305
3338
|
} catch (error) {
|
|
2306
|
-
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${
|
|
3339
|
+
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${resolve2(path)}.`, [
|
|
2307
3340
|
error instanceof Error ? error.message : String(error)
|
|
2308
3341
|
]);
|
|
2309
3342
|
}
|
|
@@ -2311,7 +3344,27 @@ function readSeed(path) {
|
|
|
2311
3344
|
function csv(value) {
|
|
2312
3345
|
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
2313
3346
|
}
|
|
2314
|
-
|
|
3347
|
+
function relaunchTrustingLocalCertificate(argv) {
|
|
3348
|
+
if (process.env.KINDE_TESTKIT_TRUSTED || argv[0] === "start" || argv[0] === "cert") return false;
|
|
3349
|
+
const urlArg = argv.find((arg, i) => arg.startsWith("--url=") || argv[i - 1] === "--url");
|
|
3350
|
+
const target = urlArg?.replace(/^--url=/, "") ?? process.env.KINDE_TESTKIT_URL ?? "";
|
|
3351
|
+
const certPath = resolve2(".kinde-testkit", "localhost-cert.pem");
|
|
3352
|
+
if (!target.startsWith("https://") || !existsSync2(certPath)) return false;
|
|
3353
|
+
let trusted = certPath;
|
|
3354
|
+
const existing = process.env.NODE_EXTRA_CA_CERTS;
|
|
3355
|
+
if (existing && resolve2(existing) !== certPath) {
|
|
3356
|
+
trusted = resolve2(".kinde-testkit", "ca-bundle.pem");
|
|
3357
|
+
const current = existsSync2(existing) ? readFileSync2(existing, "utf8") : "";
|
|
3358
|
+
writeFileSync2(trusted, `${current.trimEnd()}
|
|
3359
|
+
${readFileSync2(certPath, "utf8")}`);
|
|
3360
|
+
}
|
|
3361
|
+
const result = spawnSync(process.execPath, [process.argv[1], ...argv], {
|
|
3362
|
+
stdio: "inherit",
|
|
3363
|
+
env: { ...process.env, NODE_EXTRA_CA_CERTS: trusted, KINDE_TESTKIT_TRUSTED: "1" }
|
|
3364
|
+
});
|
|
3365
|
+
process.exit(result.status ?? 1);
|
|
3366
|
+
}
|
|
3367
|
+
if (!relaunchTrustingLocalCertificate(process.argv.slice(2))) main(process.argv.slice(2)).catch((error) => {
|
|
2315
3368
|
if (error instanceof TestkitError) {
|
|
2316
3369
|
process.stderr.write(`${error.toString()}
|
|
2317
3370
|
`);
|