kinde-testkit 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +113 -8
- package/dist/cli.js +1580 -118
- package/dist/index.cjs +1428 -104
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +235 -1
- package/dist/index.d.ts +235 -1
- package/dist/index.js +1421 -103
- package/dist/index.js.map +1 -1
- package/dist/playwright.d.ts +34 -0
- package/dist/playwright.js +4 -0
- package/dist/playwright.js.map +1 -1
- package/dist/vitest.d.ts +186 -0
- package/dist/vitest.js +1409 -103
- package/dist/vitest.js.map +1 -1
- package/package.json +4 -1
package/dist/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;
|
|
@@ -271,6 +410,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
271
410
|
if (scenario.kind === "unauthenticated") return null;
|
|
272
411
|
return scenarioPrincipal(scenario, this.issuer);
|
|
273
412
|
}
|
|
413
|
+
async signPayload(payload, invalid2) {
|
|
414
|
+
return this.sign(payload, invalid2);
|
|
415
|
+
}
|
|
274
416
|
async sign(payload, invalid2) {
|
|
275
417
|
if (invalid2 === "unsigned") {
|
|
276
418
|
const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
@@ -355,7 +497,91 @@ function warnIfRealKindeDomain(issuer) {
|
|
|
355
497
|
}
|
|
356
498
|
}
|
|
357
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
|
+
|
|
358
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
|
+
}
|
|
359
585
|
function resolveSeed(input) {
|
|
360
586
|
const problems = [];
|
|
361
587
|
if (!isRecord(input)) {
|
|
@@ -365,6 +591,23 @@ function resolveSeed(input) {
|
|
|
365
591
|
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
366
592
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
367
593
|
const rawApplications = listOf(input.applications, "applications", problems);
|
|
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);
|
|
599
|
+
const webhooks = [];
|
|
600
|
+
rawWebhooks.forEach((raw, index) => {
|
|
601
|
+
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
602
|
+
problems.push(`webhooks[${index}] needs an http or https "url".`);
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
|
|
606
|
+
problems.push(`webhooks[${index}].events must be a list of event type names.`);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
webhooks.push({ url: raw.url, events: raw.events });
|
|
610
|
+
});
|
|
368
611
|
const users = [];
|
|
369
612
|
rawUsers.forEach((raw, index) => {
|
|
370
613
|
if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
|
|
@@ -456,7 +699,107 @@ function resolveSeed(input) {
|
|
|
456
699
|
if (problems.length > 0) {
|
|
457
700
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
458
701
|
}
|
|
459
|
-
|
|
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 };
|
|
460
803
|
}
|
|
461
804
|
function findUser(users, ref) {
|
|
462
805
|
const needle = ref.toLowerCase();
|
|
@@ -501,7 +844,7 @@ function seedScenario(seed, ref) {
|
|
|
501
844
|
user,
|
|
502
845
|
organization,
|
|
503
846
|
roles: [...membership?.roles ?? []],
|
|
504
|
-
permissions:
|
|
847
|
+
permissions: effectivePermissions(seed, membership),
|
|
505
848
|
claims: {}
|
|
506
849
|
};
|
|
507
850
|
}
|
|
@@ -516,72 +859,18 @@ function listOf(value, field, problems) {
|
|
|
516
859
|
function isRecord(value) {
|
|
517
860
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
518
861
|
}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
*{box-sizing:border-box}
|
|
528
|
-
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}
|
|
529
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
530
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
531
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
532
|
-
p{margin:0;color:var(--muted)}
|
|
533
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
534
|
-
form{margin:0}
|
|
535
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
536
|
-
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}
|
|
537
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
538
|
-
.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}
|
|
539
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
540
|
-
.list{display:grid;gap:8px}
|
|
541
|
-
.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}
|
|
542
|
-
.option:hover{border-color:var(--muted)}
|
|
543
|
-
.option strong{display:block;font-weight:500}
|
|
544
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
545
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
546
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
547
|
-
`;
|
|
548
|
-
function escapeHtml(value) {
|
|
549
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
550
|
-
}
|
|
551
|
-
function layout(title, body) {
|
|
552
|
-
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>`;
|
|
553
|
-
}
|
|
554
|
-
function displayName(user) {
|
|
555
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
556
|
-
}
|
|
557
|
-
function renderSignIn(options) {
|
|
558
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
559
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
560
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
561
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
562
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
563
|
-
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>`;
|
|
564
|
-
}).join("");
|
|
565
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
566
|
-
return layout(
|
|
567
|
-
"Sign in",
|
|
568
|
-
`<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>`
|
|
569
|
-
);
|
|
570
|
-
}
|
|
571
|
-
function renderOrganizationPicker(options) {
|
|
572
|
-
const choices = options.organizations.map(
|
|
573
|
-
(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>`
|
|
574
|
-
).join("");
|
|
575
|
-
return layout(
|
|
576
|
-
"Choose an organization",
|
|
577
|
-
`<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>`
|
|
578
|
-
);
|
|
579
|
-
}
|
|
580
|
-
function renderMessage(title, message) {
|
|
581
|
-
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;
|
|
582
870
|
}
|
|
583
871
|
|
|
584
872
|
// src/oauth.ts
|
|
873
|
+
import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
585
874
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
586
875
|
var OAuthError = class extends Error {
|
|
587
876
|
constructor(status, error, description) {
|
|
@@ -593,12 +882,16 @@ var OAuthError = class extends Error {
|
|
|
593
882
|
error;
|
|
594
883
|
};
|
|
595
884
|
var AuthorizationServer = class {
|
|
596
|
-
constructor(testkit, seed) {
|
|
885
|
+
constructor(testkit, seed, emit = () => void 0, directory) {
|
|
597
886
|
this.testkit = testkit;
|
|
598
887
|
this.seed = seed;
|
|
888
|
+
this.emit = emit;
|
|
889
|
+
this.directory = directory;
|
|
599
890
|
}
|
|
600
891
|
testkit;
|
|
601
892
|
seed;
|
|
893
|
+
emit;
|
|
894
|
+
directory;
|
|
602
895
|
codes = /* @__PURE__ */ new Map();
|
|
603
896
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
604
897
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -664,6 +957,18 @@ var AuthorizationServer = class {
|
|
|
664
957
|
if (!user) {
|
|
665
958
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
666
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
|
+
}
|
|
667
972
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
668
973
|
const wanted = request2.orgCode ?? form.org ?? null;
|
|
669
974
|
let organizationCode = null;
|
|
@@ -700,7 +1005,7 @@ var AuthorizationServer = class {
|
|
|
700
1005
|
user,
|
|
701
1006
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
702
1007
|
roles: [...membership?.roles ?? []],
|
|
703
|
-
permissions:
|
|
1008
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
704
1009
|
claims: {}
|
|
705
1010
|
};
|
|
706
1011
|
const code = randomToken();
|
|
@@ -716,6 +1021,8 @@ var AuthorizationServer = class {
|
|
|
716
1021
|
codeChallengeMethod: request2.codeChallengeMethod,
|
|
717
1022
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
718
1023
|
});
|
|
1024
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
1025
|
+
this.emit("user.authenticated", user);
|
|
719
1026
|
const target = new URL(request2.redirectUri);
|
|
720
1027
|
target.searchParams.set("code", code);
|
|
721
1028
|
if (request2.state !== null) target.searchParams.set("state", request2.state);
|
|
@@ -750,7 +1057,7 @@ var AuthorizationServer = class {
|
|
|
750
1057
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
751
1058
|
}
|
|
752
1059
|
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
753
|
-
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;
|
|
754
1061
|
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
755
1062
|
return {
|
|
756
1063
|
access_token: await this.testkit.m2mToken({
|
|
@@ -786,7 +1093,7 @@ var AuthorizationServer = class {
|
|
|
786
1093
|
}
|
|
787
1094
|
if (pending.codeChallenge) {
|
|
788
1095
|
const verifier = form.code_verifier ?? "";
|
|
789
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1096
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
790
1097
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
791
1098
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
792
1099
|
}
|
|
@@ -816,7 +1123,8 @@ var AuthorizationServer = class {
|
|
|
816
1123
|
scopes: grant.scope,
|
|
817
1124
|
clientId: grant.clientId,
|
|
818
1125
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
819
|
-
authTime: grant.authTime
|
|
1126
|
+
authTime: grant.authTime,
|
|
1127
|
+
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
820
1128
|
}),
|
|
821
1129
|
expires_in: this.testkit.accessTokenLifetime,
|
|
822
1130
|
scope: grant.scope.join(" "),
|
|
@@ -881,8 +1189,12 @@ var AuthorizationServer = class {
|
|
|
881
1189
|
if (seeded) return seeded;
|
|
882
1190
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
883
1191
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
884
|
-
this.signedUpUsers.
|
|
885
|
-
|
|
1192
|
+
if (!this.signedUpUsers.has(user.id)) {
|
|
1193
|
+
this.signedUpUsers.set(user.id, user);
|
|
1194
|
+
if (this.directory) this.seed.users.push(user);
|
|
1195
|
+
this.emit("user.created", user);
|
|
1196
|
+
}
|
|
1197
|
+
return this.signedUpUsers.get(user.id);
|
|
886
1198
|
}
|
|
887
1199
|
organization(code) {
|
|
888
1200
|
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
@@ -967,7 +1279,7 @@ function isHttpUrl(value) {
|
|
|
967
1279
|
}
|
|
968
1280
|
}
|
|
969
1281
|
function randomToken() {
|
|
970
|
-
return
|
|
1282
|
+
return randomBytes2(32).toString("base64url");
|
|
971
1283
|
}
|
|
972
1284
|
function safeEqual(a, b) {
|
|
973
1285
|
const left = Buffer.from(a);
|
|
@@ -991,6 +1303,687 @@ function sendJson(res, status, body) {
|
|
|
991
1303
|
res.end(JSON.stringify(body));
|
|
992
1304
|
}
|
|
993
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
|
+
|
|
994
1987
|
// src/failures.ts
|
|
995
1988
|
var MAX_DELAY_MS = 6e4;
|
|
996
1989
|
var FailureInjector = class {
|
|
@@ -1071,6 +2064,278 @@ function validate(rule) {
|
|
|
1071
2064
|
return problems;
|
|
1072
2065
|
}
|
|
1073
2066
|
|
|
2067
|
+
// src/webhooks.ts
|
|
2068
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
2069
|
+
var WEBHOOK_EVENT_TYPES = [
|
|
2070
|
+
"user.created",
|
|
2071
|
+
"user.updated",
|
|
2072
|
+
"user.deleted",
|
|
2073
|
+
"user.authenticated",
|
|
2074
|
+
"user.authentication_failed",
|
|
2075
|
+
"organization.created",
|
|
2076
|
+
"organization.updated",
|
|
2077
|
+
"organization.deleted",
|
|
2078
|
+
"role.created",
|
|
2079
|
+
"role.updated",
|
|
2080
|
+
"role.deleted",
|
|
2081
|
+
"permission.created",
|
|
2082
|
+
"permission.updated",
|
|
2083
|
+
"permission.deleted",
|
|
2084
|
+
"subscriber.created",
|
|
2085
|
+
"access_request.created"
|
|
2086
|
+
];
|
|
2087
|
+
var BILLING_EVENT_TYPES = [
|
|
2088
|
+
"customer.agreement_cancelled",
|
|
2089
|
+
"customer.agreement_created",
|
|
2090
|
+
"customer.invoice_overdue",
|
|
2091
|
+
"customer.meter_usage_updated",
|
|
2092
|
+
"customer.payment_failed",
|
|
2093
|
+
"customer.payment_succeeded",
|
|
2094
|
+
"customer.plan_assigned",
|
|
2095
|
+
"customer.plan_changed"
|
|
2096
|
+
];
|
|
2097
|
+
var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
|
|
2098
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
2099
|
+
var MAX_DUPLICATES = 10;
|
|
2100
|
+
var WebhookDispatcher = class {
|
|
2101
|
+
constructor(testkit, seed, endpoints = [], options = {}) {
|
|
2102
|
+
this.testkit = testkit;
|
|
2103
|
+
this.seed = seed;
|
|
2104
|
+
this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
2105
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
2106
|
+
for (const endpoint of endpoints) this.addEndpoint(endpoint);
|
|
2107
|
+
this.seededEndpoints = [...this.endpoints];
|
|
2108
|
+
}
|
|
2109
|
+
testkit;
|
|
2110
|
+
seed;
|
|
2111
|
+
endpoints = [];
|
|
2112
|
+
seededEndpoints = [];
|
|
2113
|
+
log = [];
|
|
2114
|
+
nextEndpoint = 1;
|
|
2115
|
+
retryDelaysMs;
|
|
2116
|
+
timeoutMs;
|
|
2117
|
+
addEndpoint(input) {
|
|
2118
|
+
if (!isHttpUrl2(input.url)) {
|
|
2119
|
+
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
2120
|
+
}
|
|
2121
|
+
if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
|
|
2122
|
+
throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
|
|
2123
|
+
}
|
|
2124
|
+
const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
|
|
2125
|
+
this.endpoints.push(endpoint);
|
|
2126
|
+
return { ...endpoint };
|
|
2127
|
+
}
|
|
2128
|
+
removeEndpoint(id) {
|
|
2129
|
+
const before = this.endpoints.length;
|
|
2130
|
+
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
2131
|
+
return this.endpoints.length < before;
|
|
2132
|
+
}
|
|
2133
|
+
listEndpoints() {
|
|
2134
|
+
return this.endpoints.map((e) => ({ ...e }));
|
|
2135
|
+
}
|
|
2136
|
+
deliveries() {
|
|
2137
|
+
return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
|
|
2138
|
+
}
|
|
2139
|
+
reset() {
|
|
2140
|
+
this.log = [];
|
|
2141
|
+
this.endpoints = [...this.seededEndpoints];
|
|
2142
|
+
}
|
|
2143
|
+
buildEvent(options) {
|
|
2144
|
+
if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
|
|
2145
|
+
throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
|
|
2146
|
+
}
|
|
2147
|
+
const now = /* @__PURE__ */ new Date();
|
|
2148
|
+
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
2149
|
+
const event = {
|
|
2150
|
+
data: options.data ?? this.buildData(options),
|
|
2151
|
+
event_id: `event_${randomBytes4(16).toString("hex")}`,
|
|
2152
|
+
event_timestamp: timestamp,
|
|
2153
|
+
source: options.source ?? "admin",
|
|
2154
|
+
timestamp,
|
|
2155
|
+
type: options.type
|
|
2156
|
+
};
|
|
2157
|
+
if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
|
|
2158
|
+
event.ip_address = options.ipAddress ?? "127.0.0.1";
|
|
2159
|
+
}
|
|
2160
|
+
return event;
|
|
2161
|
+
}
|
|
2162
|
+
async send(options) {
|
|
2163
|
+
const event = this.buildEvent(options);
|
|
2164
|
+
const copies = options.duplicate ?? 1;
|
|
2165
|
+
if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
|
|
2166
|
+
throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
|
|
2167
|
+
}
|
|
2168
|
+
const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
|
|
2169
|
+
if (options.to && !isHttpUrl2(options.to)) {
|
|
2170
|
+
throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
|
|
2171
|
+
}
|
|
2172
|
+
if (targets.length === 0) {
|
|
2173
|
+
throw new TestkitError(
|
|
2174
|
+
"INVALID_REQUEST",
|
|
2175
|
+
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
2176
|
+
);
|
|
2177
|
+
}
|
|
2178
|
+
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
2179
|
+
const signed = await this.testkit.signPayload(
|
|
2180
|
+
event,
|
|
2181
|
+
options.invalid === "stale" ? void 0 : options.invalid
|
|
2182
|
+
);
|
|
2183
|
+
const jobs = targets.flatMap((target) => {
|
|
2184
|
+
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
2185
|
+
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
2186
|
+
});
|
|
2187
|
+
return Promise.all(jobs);
|
|
2188
|
+
}
|
|
2189
|
+
async deliver(url, webhookId, body, event, copy) {
|
|
2190
|
+
const delivery = {
|
|
2191
|
+
webhookId,
|
|
2192
|
+
eventId: String(event.event_id),
|
|
2193
|
+
type: String(event.type),
|
|
2194
|
+
url,
|
|
2195
|
+
copy,
|
|
2196
|
+
delivered: false,
|
|
2197
|
+
attempts: [],
|
|
2198
|
+
payload: event
|
|
2199
|
+
};
|
|
2200
|
+
this.log.push(delivery);
|
|
2201
|
+
for (const [index, delay] of this.retryDelaysMs.entries()) {
|
|
2202
|
+
if (delay > 0) await sleep(delay);
|
|
2203
|
+
const started = Date.now();
|
|
2204
|
+
try {
|
|
2205
|
+
const response = await fetch(url, {
|
|
2206
|
+
method: "POST",
|
|
2207
|
+
headers: { "content-type": "application/jwt", "webhook-id": webhookId },
|
|
2208
|
+
body,
|
|
2209
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
2210
|
+
});
|
|
2211
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
2212
|
+
delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
|
|
2213
|
+
if (response.status === 200) {
|
|
2214
|
+
delivery.delivered = true;
|
|
2215
|
+
break;
|
|
2216
|
+
}
|
|
2217
|
+
} catch (error) {
|
|
2218
|
+
const name = error.name;
|
|
2219
|
+
delivery.attempts.push({
|
|
2220
|
+
attempt: index + 1,
|
|
2221
|
+
status: null,
|
|
2222
|
+
error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
|
|
2223
|
+
durationMs: Date.now() - started
|
|
2224
|
+
});
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
return { ...delivery, attempts: [...delivery.attempts] };
|
|
2228
|
+
}
|
|
2229
|
+
buildData(options) {
|
|
2230
|
+
const [subject] = options.type.split(".");
|
|
2231
|
+
switch (subject) {
|
|
2232
|
+
case "user":
|
|
2233
|
+
return { user: this.userData(options) };
|
|
2234
|
+
case "organization":
|
|
2235
|
+
return { organization: this.organizationData(options) };
|
|
2236
|
+
case "role":
|
|
2237
|
+
return { role: this.namedData(options, "role") };
|
|
2238
|
+
case "permission":
|
|
2239
|
+
return { permission: this.namedData(options, "permission") };
|
|
2240
|
+
case "subscriber": {
|
|
2241
|
+
const user = this.requireUser(options);
|
|
2242
|
+
return {
|
|
2243
|
+
subscriber: {
|
|
2244
|
+
email: user.email,
|
|
2245
|
+
first_name: user.givenName,
|
|
2246
|
+
id: stableId("sub", user.id),
|
|
2247
|
+
last_name: user.familyName,
|
|
2248
|
+
user_id: user.id
|
|
2249
|
+
}
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
case "access_request": {
|
|
2253
|
+
const user = this.requireUser(options);
|
|
2254
|
+
return {
|
|
2255
|
+
access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
|
|
2256
|
+
};
|
|
2257
|
+
}
|
|
2258
|
+
default:
|
|
2259
|
+
throw new TestkitError(
|
|
2260
|
+
"INVALID_REQUEST",
|
|
2261
|
+
`kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
|
|
2262
|
+
);
|
|
2263
|
+
}
|
|
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
|
+
}
|
|
2272
|
+
emitForUser(type, user) {
|
|
2273
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2274
|
+
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
2275
|
+
void this.send({ type, data, source: "user" }).catch(() => void 0);
|
|
2276
|
+
}
|
|
2277
|
+
userData(options) {
|
|
2278
|
+
const user = this.requireUser(options);
|
|
2279
|
+
if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
|
|
2280
|
+
return this.userPayload(user);
|
|
2281
|
+
}
|
|
2282
|
+
userPayload(user) {
|
|
2283
|
+
return {
|
|
2284
|
+
email: user.email,
|
|
2285
|
+
first_name: user.givenName,
|
|
2286
|
+
id: user.id,
|
|
2287
|
+
is_password_reset_requested: false,
|
|
2288
|
+
is_suspended: false,
|
|
2289
|
+
last_name: user.familyName,
|
|
2290
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
|
|
2291
|
+
code: m.organizationCode,
|
|
2292
|
+
permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
|
|
2293
|
+
roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
|
|
2294
|
+
})),
|
|
2295
|
+
phone: null,
|
|
2296
|
+
username: typeof user.claims.username === "string" ? user.claims.username : null
|
|
2297
|
+
};
|
|
2298
|
+
}
|
|
2299
|
+
organizationData(options) {
|
|
2300
|
+
if (!options.organization) {
|
|
2301
|
+
throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
|
|
2302
|
+
}
|
|
2303
|
+
const org = this.seed.organizations.find((o) => o.code === options.organization);
|
|
2304
|
+
if (options.type === "organization.deleted") return { code: options.organization };
|
|
2305
|
+
const name = org?.name ?? titleCase(options.organization);
|
|
2306
|
+
const data = { code: options.organization, external_id: null, handle: slug(name), name };
|
|
2307
|
+
if (options.type === "organization.updated") data.is_allow_registrations = false;
|
|
2308
|
+
return data;
|
|
2309
|
+
}
|
|
2310
|
+
namedData(options, kind) {
|
|
2311
|
+
const key = kind === "role" ? options.role : options.permission;
|
|
2312
|
+
if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
|
|
2313
|
+
const id = stableId(kind === "role" ? "role" : "perm", key);
|
|
2314
|
+
if (options.type.endsWith(".deleted")) return { id };
|
|
2315
|
+
const data = { description: "", id, key, name: titleCase(key) };
|
|
2316
|
+
if (kind === "role") data.is_default_role = false;
|
|
2317
|
+
return data;
|
|
2318
|
+
}
|
|
2319
|
+
requireUser(options) {
|
|
2320
|
+
if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
|
|
2321
|
+
const user = findUser(this.seed.users, options.user);
|
|
2322
|
+
if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
|
|
2323
|
+
return user;
|
|
2324
|
+
}
|
|
2325
|
+
};
|
|
2326
|
+
function isHttpUrl2(value) {
|
|
2327
|
+
if (typeof value !== "string") return false;
|
|
2328
|
+
try {
|
|
2329
|
+
const { protocol } = new URL(value);
|
|
2330
|
+
return protocol === "http:" || protocol === "https:";
|
|
2331
|
+
} catch {
|
|
2332
|
+
return false;
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
function sleep(ms) {
|
|
2336
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
2337
|
+
}
|
|
2338
|
+
|
|
1074
2339
|
// src/server.ts
|
|
1075
2340
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
1076
2341
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
@@ -1086,28 +2351,36 @@ async function startKindeTestkit(options = {}) {
|
|
|
1086
2351
|
const seed = resolveSeed(options.seed ?? {});
|
|
1087
2352
|
const failures = new FailureInjector();
|
|
1088
2353
|
let ready;
|
|
1089
|
-
const testkitReady = new Promise((
|
|
1090
|
-
const
|
|
2354
|
+
const testkitReady = new Promise((resolve3) => ready = resolve3);
|
|
2355
|
+
const listener = (req, res) => {
|
|
1091
2356
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1092
|
-
}
|
|
1093
|
-
|
|
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) => {
|
|
1094
2361
|
server.once("error", reject);
|
|
1095
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
2362
|
+
server.listen(options.port ?? 4400, host, () => resolve3());
|
|
1096
2363
|
});
|
|
1097
2364
|
const { port } = server.address();
|
|
1098
2365
|
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1099
|
-
const url =
|
|
2366
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1100
2367
|
const testkit = await KindeTestkit.create({
|
|
1101
2368
|
issuer: options.issuer ?? options.seed?.issuer ?? url,
|
|
1102
2369
|
audience: options.audience ?? options.seed?.audience,
|
|
1103
2370
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1104
2371
|
});
|
|
1105
|
-
const
|
|
2372
|
+
const directory = new Directory(seed);
|
|
2373
|
+
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
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);
|
|
1106
2377
|
const reset2 = () => {
|
|
1107
2378
|
auth.reset();
|
|
1108
2379
|
failures.clear();
|
|
2380
|
+
webhooks.reset();
|
|
2381
|
+
directory.restore();
|
|
1109
2382
|
};
|
|
1110
|
-
ready({ testkit, auth, seed, failures, reset: reset2 });
|
|
2383
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset: reset2 });
|
|
1111
2384
|
return {
|
|
1112
2385
|
url,
|
|
1113
2386
|
issuer: testkit.issuer,
|
|
@@ -1116,15 +2389,18 @@ async function startKindeTestkit(options = {}) {
|
|
|
1116
2389
|
testkit,
|
|
1117
2390
|
seed,
|
|
1118
2391
|
failures,
|
|
2392
|
+
webhooks,
|
|
2393
|
+
directory,
|
|
2394
|
+
certificatePath: certificate?.certPath ?? null,
|
|
1119
2395
|
reset: reset2,
|
|
1120
|
-
close: () => new Promise((
|
|
2396
|
+
close: () => new Promise((resolve3, reject) => {
|
|
1121
2397
|
server.closeAllConnections();
|
|
1122
|
-
server.close((error) => error ? reject(error) :
|
|
2398
|
+
server.close((error) => error ? reject(error) : resolve3());
|
|
1123
2399
|
})
|
|
1124
2400
|
};
|
|
1125
2401
|
}
|
|
1126
2402
|
async function handle(req, res, context) {
|
|
1127
|
-
const { testkit, auth, seed, failures } = context;
|
|
2403
|
+
const { testkit, auth, seed, failures, webhooks } = context;
|
|
1128
2404
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1129
2405
|
const { pathname } = url;
|
|
1130
2406
|
const method = req.method ?? "GET";
|
|
@@ -1132,53 +2408,77 @@ async function handle(req, res, context) {
|
|
|
1132
2408
|
const failure = failures.take(method, pathname);
|
|
1133
2409
|
if (failure) {
|
|
1134
2410
|
if (failure.hang) return;
|
|
1135
|
-
if (failure.delayMs > 0) await new Promise((
|
|
2411
|
+
if (failure.delayMs > 0) await new Promise((resolve3) => setTimeout(resolve3, failure.delayMs));
|
|
1136
2412
|
if (failure.status !== null) {
|
|
1137
2413
|
const headers = {};
|
|
1138
2414
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1139
|
-
return
|
|
2415
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1140
2416
|
}
|
|
1141
2417
|
}
|
|
1142
2418
|
}
|
|
1143
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
|
+
}
|
|
1144
2429
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1145
|
-
return
|
|
2430
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1146
2431
|
}
|
|
1147
2432
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1148
|
-
return
|
|
2433
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1149
2434
|
}
|
|
1150
2435
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1151
|
-
return
|
|
2436
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1152
2437
|
}
|
|
1153
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
2438
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
1154
2439
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1155
|
-
return
|
|
2440
|
+
return sendJson4(res, 200, seed.organizations);
|
|
1156
2441
|
}
|
|
1157
2442
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1158
|
-
return
|
|
2443
|
+
return sendJson4(res, 200, seed.memberships);
|
|
1159
2444
|
}
|
|
1160
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
2445
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1161
2446
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1162
|
-
return
|
|
2447
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1163
2448
|
}
|
|
1164
2449
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1165
2450
|
failures.clear();
|
|
1166
|
-
return
|
|
2451
|
+
return sendJson4(res, 200, { ok: true });
|
|
1167
2452
|
}
|
|
1168
2453
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1169
2454
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1170
|
-
return
|
|
2455
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
2456
|
+
}
|
|
2457
|
+
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
2458
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
2459
|
+
}
|
|
2460
|
+
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
2461
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
2462
|
+
}
|
|
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());
|
|
2465
|
+
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
2466
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
2467
|
+
}
|
|
2468
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
2469
|
+
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
2470
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1171
2471
|
}
|
|
1172
2472
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1173
2473
|
context.reset();
|
|
1174
|
-
return
|
|
2474
|
+
return sendJson4(res, 200, { ok: true });
|
|
1175
2475
|
}
|
|
1176
2476
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1177
2477
|
const body = await readJson(req);
|
|
1178
2478
|
const accessToken = await issueToken(testkit, seed, body);
|
|
1179
|
-
return
|
|
2479
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
1180
2480
|
}
|
|
1181
|
-
return
|
|
2481
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
1182
2482
|
}
|
|
1183
2483
|
function discovery(testkit) {
|
|
1184
2484
|
const base = testkit.issuer;
|
|
@@ -1237,7 +2537,11 @@ async function issueToken(testkit, seed, body) {
|
|
|
1237
2537
|
});
|
|
1238
2538
|
if (permissions) scenario.permissions = permissions;
|
|
1239
2539
|
if (roles) scenario.roles = roles;
|
|
1240
|
-
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
|
+
});
|
|
1241
2545
|
}
|
|
1242
2546
|
const options = {
|
|
1243
2547
|
subject: optionalString(input, "subject"),
|
|
@@ -1302,7 +2606,7 @@ async function readText(req) {
|
|
|
1302
2606
|
}
|
|
1303
2607
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1304
2608
|
}
|
|
1305
|
-
function
|
|
2609
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1306
2610
|
res.writeHead(status, {
|
|
1307
2611
|
"content-type": "application/json; charset=utf-8",
|
|
1308
2612
|
"cache-control": "no-store",
|
|
@@ -1316,10 +2620,10 @@ function sendError(res, error) {
|
|
|
1316
2620
|
return;
|
|
1317
2621
|
}
|
|
1318
2622
|
if (error instanceof TestkitError) {
|
|
1319
|
-
|
|
2623
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1320
2624
|
return;
|
|
1321
2625
|
}
|
|
1322
|
-
|
|
2626
|
+
sendJson4(res, 500, {
|
|
1323
2627
|
error: "server_error",
|
|
1324
2628
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1325
2629
|
});
|
|
@@ -1466,6 +2770,15 @@ async function runDoctor(options) {
|
|
|
1466
2770
|
} else {
|
|
1467
2771
|
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1468
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
|
+
}
|
|
1469
2782
|
const site = env.KINDE_SITE_URL;
|
|
1470
2783
|
if (!site) {
|
|
1471
2784
|
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
@@ -1506,6 +2819,8 @@ Usage
|
|
|
1506
2819
|
kinde-testkit doctor [options] Check your app's Kinde settings against the issuer
|
|
1507
2820
|
kinde-testkit fail <path> [options] Make an endpoint fail, slow down or hang
|
|
1508
2821
|
kinde-testkit reset Clear sign-in sessions and failure rules
|
|
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
|
|
1509
2824
|
|
|
1510
2825
|
start
|
|
1511
2826
|
--port <n> Port to listen on (default 4400)
|
|
@@ -1515,6 +2830,9 @@ start
|
|
|
1515
2830
|
--client-id <id> Value for azp
|
|
1516
2831
|
--seed <file> Seed file (default ./kinde-testkit.json when it exists)
|
|
1517
2832
|
--allow-public Allow binding to a non-loopback interface
|
|
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)
|
|
1518
2836
|
|
|
1519
2837
|
token
|
|
1520
2838
|
--url <url> Running issuer (default ${DEFAULT_URL})
|
|
@@ -1550,6 +2868,18 @@ fail <path> An exact path such as /oauth2/token, or a prefix such as
|
|
|
1550
2868
|
--method <verb> Only match this method
|
|
1551
2869
|
--list Show active rules
|
|
1552
2870
|
--clear Remove all rules
|
|
2871
|
+
|
|
2872
|
+
webhook <type> Any event type, such as user.created or customer.plan_assigned
|
|
2873
|
+
--user <id|email> Seeded user, for user.*, subscriber.* and access_request.*
|
|
2874
|
+
--org <code> Organization, for organization.*
|
|
2875
|
+
--role <key> Role, for role.*
|
|
2876
|
+
--permission <key> Permission, for permission.*
|
|
2877
|
+
--data <json> The event's data object. Needed for billing events
|
|
2878
|
+
--to <url> Send to this URL instead of the configured endpoints
|
|
2879
|
+
--duplicate <n> Send n copies with the same webhook-id
|
|
2880
|
+
--invalid <kind> bad-signature, unknown-key, unsigned or stale
|
|
2881
|
+
--types List the event types with built-in payloads
|
|
2882
|
+
--deliveries Show the delivery log
|
|
1553
2883
|
`;
|
|
1554
2884
|
async function main(argv) {
|
|
1555
2885
|
const [command, ...rest] = argv;
|
|
@@ -1571,6 +2901,11 @@ async function main(argv) {
|
|
|
1571
2901
|
return fail(rest);
|
|
1572
2902
|
case "reset":
|
|
1573
2903
|
return reset(rest);
|
|
2904
|
+
case "webhook":
|
|
2905
|
+
case "webhooks":
|
|
2906
|
+
return webhook(rest);
|
|
2907
|
+
case "cert":
|
|
2908
|
+
return cert(rest);
|
|
1574
2909
|
case void 0:
|
|
1575
2910
|
case "help":
|
|
1576
2911
|
case "--help":
|
|
@@ -1592,11 +2927,15 @@ async function start(args) {
|
|
|
1592
2927
|
"client-id": { type: "string" },
|
|
1593
2928
|
seed: { type: "string" },
|
|
1594
2929
|
"allow-public": { type: "boolean" },
|
|
2930
|
+
webhook: { type: "string", multiple: true },
|
|
2931
|
+
https: { type: "boolean" },
|
|
2932
|
+
"cert-dir": { type: "string" },
|
|
1595
2933
|
json: { type: "boolean" }
|
|
1596
2934
|
}
|
|
1597
2935
|
});
|
|
1598
|
-
const seedPath = values.seed ?? (
|
|
1599
|
-
const seed = seedPath ? readSeed(seedPath) : void 0;
|
|
2936
|
+
const seedPath = values.seed ?? (existsSync2(DEFAULT_SEED_FILE) ? DEFAULT_SEED_FILE : void 0);
|
|
2937
|
+
const seed = seedPath ? readSeed(seedPath) : values.webhook ? {} : void 0;
|
|
2938
|
+
if (seed && values.webhook) seed.webhooks = [...seed.webhooks ?? [], ...values.webhook.map((url) => ({ url }))];
|
|
1600
2939
|
const running = await startKindeTestkit({
|
|
1601
2940
|
port: values.port ? Number(values.port) : void 0,
|
|
1602
2941
|
host: values.host,
|
|
@@ -1604,7 +2943,8 @@ async function start(args) {
|
|
|
1604
2943
|
audience: values.audience ? csv(values.audience) : void 0,
|
|
1605
2944
|
clientId: values["client-id"],
|
|
1606
2945
|
seed,
|
|
1607
|
-
allowPublic: values["allow-public"]
|
|
2946
|
+
allowPublic: values["allow-public"],
|
|
2947
|
+
https: values.https ? { certDirectory: values["cert-dir"] } : void 0
|
|
1608
2948
|
});
|
|
1609
2949
|
if (values.json) {
|
|
1610
2950
|
process.stdout.write(
|
|
@@ -1632,9 +2972,11 @@ async function start(args) {
|
|
|
1632
2972
|
`Sign-in page: ${running.url}/oauth2/auth`,
|
|
1633
2973
|
`Token: POST ${running.url}/testkit/token`,
|
|
1634
2974
|
"",
|
|
1635
|
-
`Seed: ${seedPath ?
|
|
2975
|
+
`Seed: ${seedPath ? resolve2(seedPath) : "none"}`,
|
|
1636
2976
|
`Users: ${running.seed.users.length}`,
|
|
1637
2977
|
`Organizations: ${running.seed.organizations.length}`,
|
|
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}`] : [],
|
|
1638
2980
|
"",
|
|
1639
2981
|
"Test tokens only. Press Ctrl+C to stop.",
|
|
1640
2982
|
""
|
|
@@ -1740,14 +3082,14 @@ async function doctor(args) {
|
|
|
1740
3082
|
json: { type: "boolean" }
|
|
1741
3083
|
}
|
|
1742
3084
|
});
|
|
1743
|
-
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));
|
|
1744
3086
|
const env = {};
|
|
1745
3087
|
for (const file of files) {
|
|
1746
|
-
if (!
|
|
1747
|
-
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")));
|
|
1748
3090
|
}
|
|
1749
3091
|
for (const [key, value] of Object.entries(process.env)) {
|
|
1750
|
-
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;
|
|
1751
3093
|
}
|
|
1752
3094
|
const report = await runDoctor({ url: values.url ?? DEFAULT_URL, env });
|
|
1753
3095
|
if (values.json) {
|
|
@@ -1831,6 +3173,106 @@ async function readStdin() {
|
|
|
1831
3173
|
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
1832
3174
|
return Buffer.concat(chunks).toString("utf8");
|
|
1833
3175
|
}
|
|
3176
|
+
async function webhook(args) {
|
|
3177
|
+
const { values, positionals } = parseArgs({
|
|
3178
|
+
args,
|
|
3179
|
+
allowPositionals: true,
|
|
3180
|
+
options: {
|
|
3181
|
+
url: { type: "string" },
|
|
3182
|
+
user: { type: "string" },
|
|
3183
|
+
org: { type: "string" },
|
|
3184
|
+
role: { type: "string" },
|
|
3185
|
+
permission: { type: "string" },
|
|
3186
|
+
data: { type: "string" },
|
|
3187
|
+
to: { type: "string" },
|
|
3188
|
+
duplicate: { type: "string" },
|
|
3189
|
+
invalid: { type: "string" },
|
|
3190
|
+
types: { type: "boolean" },
|
|
3191
|
+
deliveries: { type: "boolean" },
|
|
3192
|
+
json: { type: "boolean" }
|
|
3193
|
+
}
|
|
3194
|
+
});
|
|
3195
|
+
const base = values.url ?? DEFAULT_URL;
|
|
3196
|
+
if (values.types) {
|
|
3197
|
+
const types = await request(base, "/testkit/webhooks/types");
|
|
3198
|
+
process.stdout.write(
|
|
3199
|
+
values.json ? `${JSON.stringify(types)}
|
|
3200
|
+
` : `Built-in payloads:
|
|
3201
|
+
${types.built_in.map((t) => ` ${t}`).join("\n")}
|
|
3202
|
+
|
|
3203
|
+
Billing events (pass --data):
|
|
3204
|
+
${types.billing.map((t) => ` ${t}`).join("\n")}
|
|
3205
|
+
`
|
|
3206
|
+
);
|
|
3207
|
+
return;
|
|
3208
|
+
}
|
|
3209
|
+
if (values.deliveries || positionals.length === 0) {
|
|
3210
|
+
const log = await request(base, "/testkit/webhooks/deliveries");
|
|
3211
|
+
if (values.json) {
|
|
3212
|
+
process.stdout.write(`${JSON.stringify(log)}
|
|
3213
|
+
`);
|
|
3214
|
+
} else if (log.length === 0) {
|
|
3215
|
+
process.stdout.write("No webhooks sent yet.\n");
|
|
3216
|
+
} else {
|
|
3217
|
+
for (const delivery of log) process.stdout.write(`${describeDelivery(delivery)}
|
|
3218
|
+
`);
|
|
3219
|
+
}
|
|
3220
|
+
return;
|
|
3221
|
+
}
|
|
3222
|
+
let data;
|
|
3223
|
+
if (values.data !== void 0) {
|
|
3224
|
+
try {
|
|
3225
|
+
data = JSON.parse(values.data);
|
|
3226
|
+
} catch {
|
|
3227
|
+
throw new TestkitError("INVALID_REQUEST", `--data must be a JSON object, for example '{"customer_id":"c_1"}'.`);
|
|
3228
|
+
}
|
|
3229
|
+
}
|
|
3230
|
+
const deliveries = await request(base, "/testkit/webhooks", {
|
|
3231
|
+
method: "POST",
|
|
3232
|
+
headers: { "content-type": "application/json" },
|
|
3233
|
+
body: JSON.stringify({
|
|
3234
|
+
type: positionals[0],
|
|
3235
|
+
user: values.user,
|
|
3236
|
+
organization: values.org,
|
|
3237
|
+
role: values.role,
|
|
3238
|
+
permission: values.permission,
|
|
3239
|
+
data,
|
|
3240
|
+
to: values.to,
|
|
3241
|
+
duplicate: values.duplicate !== void 0 ? Number(values.duplicate) : void 0,
|
|
3242
|
+
invalid: values.invalid
|
|
3243
|
+
})
|
|
3244
|
+
});
|
|
3245
|
+
if (values.json) {
|
|
3246
|
+
process.stdout.write(`${JSON.stringify(deliveries)}
|
|
3247
|
+
`);
|
|
3248
|
+
return;
|
|
3249
|
+
}
|
|
3250
|
+
for (const delivery of deliveries) process.stdout.write(`${describeDelivery(delivery)}
|
|
3251
|
+
`);
|
|
3252
|
+
if (deliveries.some((d) => !d.delivered)) process.exitCode = 1;
|
|
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
|
+
}
|
|
3270
|
+
function describeDelivery(delivery) {
|
|
3271
|
+
const attempts = delivery.attempts ?? [];
|
|
3272
|
+
const outcome = attempts.map((a) => a.status === null ? "no answer" : String(a.status)).join(", ");
|
|
3273
|
+
const mark = delivery.delivered ? "\u2713" : "\u2717";
|
|
3274
|
+
return `${mark} ${String(delivery.type)} to ${String(delivery.url)} (${String(delivery.webhookId)}): ${outcome}`;
|
|
3275
|
+
}
|
|
1834
3276
|
function describeRule(rule) {
|
|
1835
3277
|
const parts = [`${String(rule.id)}: ${rule.method ? `${String(rule.method)} ` : ""}${String(rule.path)}`];
|
|
1836
3278
|
if (rule.status !== null) parts.push(`answers ${String(rule.status)}`);
|
|
@@ -1892,9 +3334,9 @@ ${details.map((d) => ` - ${d}
|
|
|
1892
3334
|
}
|
|
1893
3335
|
function readSeed(path) {
|
|
1894
3336
|
try {
|
|
1895
|
-
return JSON.parse(
|
|
3337
|
+
return JSON.parse(readFileSync2(path, "utf8"));
|
|
1896
3338
|
} catch (error) {
|
|
1897
|
-
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)}.`, [
|
|
1898
3340
|
error instanceof Error ? error.message : String(error)
|
|
1899
3341
|
]);
|
|
1900
3342
|
}
|
|
@@ -1902,7 +3344,27 @@ function readSeed(path) {
|
|
|
1902
3344
|
function csv(value) {
|
|
1903
3345
|
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
1904
3346
|
}
|
|
1905
|
-
|
|
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) => {
|
|
1906
3368
|
if (error instanceof TestkitError) {
|
|
1907
3369
|
process.stderr.write(`${error.toString()}
|
|
1908
3370
|
`);
|