kinde-testkit 0.4.0 → 0.6.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 +235 -11
- package/dist/cli.js +2160 -267
- package/dist/cypress-support.d.ts +98 -0
- package/dist/cypress-support.js +119 -0
- package/dist/cypress-support.js.map +1 -0
- package/dist/cypress.cjs +4249 -0
- package/dist/cypress.cjs.map +1 -0
- package/dist/cypress.d.cts +118 -0
- package/dist/cypress.d.ts +118 -0
- package/dist/cypress.js +3324 -0
- package/dist/cypress.js.map +1 -0
- package/dist/index.cjs +3270 -314
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +326 -2
- package/dist/index.d.ts +326 -2
- package/dist/index.js +1954 -150
- package/dist/index.js.map +1 -1
- package/dist/jest.cjs +4318 -0
- package/dist/jest.cjs.map +1 -0
- package/dist/jest.d.cts +567 -0
- package/dist/jest.d.ts +567 -0
- package/dist/jest.js +3392 -0
- package/dist/jest.js.map +1 -0
- package/dist/vitest.d.ts +236 -1
- package/dist/vitest.js +1853 -155
- package/dist/vitest.js.map +1 -1
- package/package.json +36 -3
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 existsSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
|
|
6
|
+
import { resolve as resolve4 } 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
|
-
function stableId(prefix,
|
|
45
|
-
return `${prefix}_${
|
|
183
|
+
function stableId(prefix, seed2) {
|
|
184
|
+
return `${prefix}_${createHash2("sha256").update(seed2).digest("hex").slice(0, 16)}`;
|
|
46
185
|
}
|
|
47
186
|
function nextSequence(prefix) {
|
|
48
187
|
const next = (counters.get(prefix) ?? 0) + 1;
|
|
@@ -136,6 +275,20 @@ var INVALID_TOKEN_KINDS = [
|
|
|
136
275
|
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
137
276
|
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
138
277
|
var KindeTestkit = class _KindeTestkit {
|
|
278
|
+
observers = [];
|
|
279
|
+
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
280
|
+
observe(observer) {
|
|
281
|
+
this.observers.push(observer);
|
|
282
|
+
return () => {
|
|
283
|
+
this.observers = this.observers.filter((o) => o !== observer);
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
async signAccess(payload, invalid2, now) {
|
|
287
|
+
const final = applyInvalidClaims(payload, invalid2, now);
|
|
288
|
+
const token2 = await this.sign(final, invalid2);
|
|
289
|
+
for (const observer of this.observers) observer.accessToken?.(final, invalid2, token2);
|
|
290
|
+
return token2;
|
|
291
|
+
}
|
|
139
292
|
issuer;
|
|
140
293
|
audience;
|
|
141
294
|
clientId;
|
|
@@ -195,7 +348,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
195
348
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
196
349
|
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
197
350
|
Object.assign(payload, options.claims ?? {});
|
|
198
|
-
return this.
|
|
351
|
+
return this.signAccess(payload, options.invalid, now);
|
|
199
352
|
}
|
|
200
353
|
async m2mToken(options = {}) {
|
|
201
354
|
const now = this.clock();
|
|
@@ -216,10 +369,13 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
216
369
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
217
370
|
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
218
371
|
Object.assign(payload, options.claims ?? {});
|
|
219
|
-
return this.
|
|
372
|
+
return this.signAccess(payload, options.invalid, now);
|
|
220
373
|
}
|
|
221
374
|
async tokenFor(scenario, overrides = {}) {
|
|
222
|
-
if (scenario.kind === "unauthenticated")
|
|
375
|
+
if (scenario.kind === "unauthenticated") {
|
|
376
|
+
for (const observer of this.observers) observer.anonymous?.();
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
223
379
|
return this.token({
|
|
224
380
|
subject: scenario.user.id,
|
|
225
381
|
organizationCode: scenario.organization?.code ?? null,
|
|
@@ -261,7 +417,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
261
417
|
for (const key of Object.keys(payload)) {
|
|
262
418
|
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
263
419
|
}
|
|
264
|
-
|
|
420
|
+
const token2 = await this.sign(payload);
|
|
421
|
+
for (const observer of this.observers) observer.idToken?.(payload, token2);
|
|
422
|
+
return token2;
|
|
265
423
|
}
|
|
266
424
|
async headersFor(scenario, overrides = {}) {
|
|
267
425
|
const token2 = await this.tokenFor(scenario, overrides);
|
|
@@ -358,7 +516,91 @@ function warnIfRealKindeDomain(issuer) {
|
|
|
358
516
|
}
|
|
359
517
|
}
|
|
360
518
|
|
|
519
|
+
// src/login-page.ts
|
|
520
|
+
var STYLE = `
|
|
521
|
+
: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}
|
|
522
|
+
@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}}
|
|
523
|
+
*{box-sizing:border-box}
|
|
524
|
+
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}
|
|
525
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
526
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
527
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
528
|
+
p{margin:0;color:var(--muted)}
|
|
529
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
530
|
+
form{margin:0}
|
|
531
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
532
|
+
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}
|
|
533
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
534
|
+
.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}
|
|
535
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
536
|
+
.list{display:grid;gap:8px}
|
|
537
|
+
.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}
|
|
538
|
+
.option:hover{border-color:var(--muted)}
|
|
539
|
+
.option strong{display:block;font-weight:500}
|
|
540
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
541
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
542
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
543
|
+
`;
|
|
544
|
+
function escapeHtml(value) {
|
|
545
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
546
|
+
}
|
|
547
|
+
function layout(title, body) {
|
|
548
|
+
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>`;
|
|
549
|
+
}
|
|
550
|
+
function displayName(user) {
|
|
551
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
552
|
+
}
|
|
553
|
+
function renderSignIn(options) {
|
|
554
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
555
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
556
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
557
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
558
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
559
|
+
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>`;
|
|
560
|
+
}).join("");
|
|
561
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
562
|
+
return layout(
|
|
563
|
+
"Sign in",
|
|
564
|
+
`<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>`
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
function renderOrganizationPicker(options) {
|
|
568
|
+
const choices = options.organizations.map(
|
|
569
|
+
(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>`
|
|
570
|
+
).join("");
|
|
571
|
+
return layout(
|
|
572
|
+
"Choose an organization",
|
|
573
|
+
`<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>`
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
function renderMessage(title, message) {
|
|
577
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
578
|
+
}
|
|
579
|
+
|
|
361
580
|
// src/seed.ts
|
|
581
|
+
function roleRecord(key, extra = {}) {
|
|
582
|
+
return {
|
|
583
|
+
id: stableId("role", key),
|
|
584
|
+
key,
|
|
585
|
+
name: extra.name ?? titleCase(key),
|
|
586
|
+
description: extra.description ?? null,
|
|
587
|
+
isDefault: extra.isDefault ?? false,
|
|
588
|
+
permissions: [...extra.permissions ?? []]
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
function permissionRecord(key, extra = {}) {
|
|
592
|
+
return {
|
|
593
|
+
id: stableId("perm", key),
|
|
594
|
+
key,
|
|
595
|
+
name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
|
|
596
|
+
description: extra.description ?? null
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
function effectivePermissions(seed2, membership) {
|
|
600
|
+
if (!membership) return [];
|
|
601
|
+
const fromRoles = membership.roles.flatMap((key) => seed2.roles.find((role) => role.key === key)?.permissions ?? []);
|
|
602
|
+
return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
|
|
603
|
+
}
|
|
362
604
|
function resolveSeed(input) {
|
|
363
605
|
const problems = [];
|
|
364
606
|
if (!isRecord(input)) {
|
|
@@ -369,6 +611,10 @@ function resolveSeed(input) {
|
|
|
369
611
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
370
612
|
const rawApplications = listOf(input.applications, "applications", problems);
|
|
371
613
|
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
614
|
+
const rawRoles = listOf(input.roles, "roles", problems);
|
|
615
|
+
const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
|
|
616
|
+
const rawPlans = listOf(input.plans, "plans", problems);
|
|
617
|
+
const rawPermissions = listOf(input.permissions, "permissions", problems);
|
|
372
618
|
const webhooks = [];
|
|
373
619
|
rawWebhooks.forEach((raw, index) => {
|
|
374
620
|
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
@@ -472,23 +718,123 @@ function resolveSeed(input) {
|
|
|
472
718
|
if (problems.length > 0) {
|
|
473
719
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
474
720
|
}
|
|
475
|
-
|
|
721
|
+
const permissions = [];
|
|
722
|
+
rawPermissions.forEach((raw, index) => {
|
|
723
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
724
|
+
problems.push(`permissions[${index}] needs a string "key".`);
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
if (permissions.some((p) => p.key === raw.key)) {
|
|
728
|
+
problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
permissions.push(
|
|
732
|
+
permissionRecord(raw.key, {
|
|
733
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
734
|
+
description: typeof raw.description === "string" ? raw.description : void 0
|
|
735
|
+
})
|
|
736
|
+
);
|
|
737
|
+
});
|
|
738
|
+
const roles = [];
|
|
739
|
+
rawRoles.forEach((raw, index) => {
|
|
740
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
741
|
+
problems.push(`roles[${index}] needs a string "key".`);
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
if (roles.some((r) => r.key === raw.key)) {
|
|
745
|
+
problems.push(`roles[${index}] repeats the key "${raw.key}".`);
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
|
|
749
|
+
problems.push(`roles[${index}].permissions must be a list of permission keys.`);
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
roles.push(
|
|
753
|
+
roleRecord(raw.key, {
|
|
754
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
755
|
+
description: typeof raw.description === "string" ? raw.description : void 0,
|
|
756
|
+
isDefault: raw.isDefault === true,
|
|
757
|
+
permissions: raw.permissions ?? []
|
|
758
|
+
})
|
|
759
|
+
);
|
|
760
|
+
});
|
|
761
|
+
if (problems.length > 0) {
|
|
762
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
763
|
+
}
|
|
764
|
+
const featureFlags = [];
|
|
765
|
+
rawFlags.forEach((raw, index) => {
|
|
766
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
|
|
767
|
+
problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
|
|
771
|
+
featureFlags.push({
|
|
772
|
+
id: stableId("flag", raw.key),
|
|
773
|
+
key: raw.key,
|
|
774
|
+
name: typeof raw.name === "string" ? raw.name : raw.key,
|
|
775
|
+
type,
|
|
776
|
+
value: raw.value,
|
|
777
|
+
organizations: isRecord(raw.organizations) ? raw.organizations : {}
|
|
778
|
+
});
|
|
779
|
+
});
|
|
780
|
+
const plans = [];
|
|
781
|
+
rawPlans.forEach((raw, index) => {
|
|
782
|
+
if (!isRecord(raw) || typeof raw.key !== "string") {
|
|
783
|
+
problems.push(`plans[${index}] needs a string "key".`);
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
|
|
787
|
+
plans.push({
|
|
788
|
+
key: raw.key,
|
|
789
|
+
name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
|
|
790
|
+
subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
|
|
791
|
+
subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
792
|
+
entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
|
|
793
|
+
id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
|
|
794
|
+
featureKey: e.featureKey,
|
|
795
|
+
featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
|
|
796
|
+
priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
|
|
797
|
+
fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
|
|
798
|
+
unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
|
|
799
|
+
limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
|
|
800
|
+
limitMin: typeof e.limitMin === "number" ? e.limitMin : null
|
|
801
|
+
}))
|
|
802
|
+
});
|
|
803
|
+
});
|
|
804
|
+
const userProperties = {};
|
|
805
|
+
rawUsers.forEach((raw) => {
|
|
806
|
+
if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
|
|
807
|
+
userProperties[raw.id] = raw.properties;
|
|
808
|
+
}
|
|
809
|
+
});
|
|
810
|
+
if (problems.length > 0) {
|
|
811
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
812
|
+
}
|
|
813
|
+
const usedRoles = new Set(memberships.flatMap((m) => m.roles));
|
|
814
|
+
for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
|
|
815
|
+
const usedPermissions = /* @__PURE__ */ new Set([
|
|
816
|
+
...memberships.flatMap((m) => m.permissions),
|
|
817
|
+
...roles.flatMap((r) => r.permissions),
|
|
818
|
+
...applications.flatMap((a) => a.permissions ?? [])
|
|
819
|
+
]);
|
|
820
|
+
for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
|
|
821
|
+
return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
|
|
476
822
|
}
|
|
477
823
|
function findUser(users, ref) {
|
|
478
824
|
const needle = ref.toLowerCase();
|
|
479
825
|
return users.find((user) => user.id === ref || user.email?.toLowerCase() === needle);
|
|
480
826
|
}
|
|
481
|
-
function seedScenario(
|
|
482
|
-
const user = findUser(
|
|
827
|
+
function seedScenario(seed2, ref) {
|
|
828
|
+
const user = findUser(seed2.users, ref.user);
|
|
483
829
|
if (!user) {
|
|
484
830
|
throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${ref.user}".`, [
|
|
485
|
-
`Known users: ${
|
|
831
|
+
`Known users: ${seed2.users.map((u) => u.email ?? u.id).join(", ") || "none"}`
|
|
486
832
|
]);
|
|
487
833
|
}
|
|
488
|
-
const userMemberships =
|
|
834
|
+
const userMemberships = seed2.memberships.filter((m) => m.userId === user.id);
|
|
489
835
|
let membership;
|
|
490
836
|
if (ref.organization) {
|
|
491
|
-
if (!
|
|
837
|
+
if (!seed2.organizations.some((org) => org.code === ref.organization)) {
|
|
492
838
|
throw new TestkitError(
|
|
493
839
|
"SEED_UNKNOWN_ORGANIZATION",
|
|
494
840
|
`No seeded organization has the code "${ref.organization}".`
|
|
@@ -511,13 +857,13 @@ function seedScenario(seed, ref) {
|
|
|
511
857
|
[`Organizations: ${userMemberships.map((m) => m.organizationCode).join(", ")}`]
|
|
512
858
|
);
|
|
513
859
|
}
|
|
514
|
-
const organization = membership ?
|
|
860
|
+
const organization = membership ? seed2.organizations.find((org) => org.code === membership.organizationCode) ?? null : null;
|
|
515
861
|
return {
|
|
516
862
|
kind: "authenticated",
|
|
517
863
|
user,
|
|
518
864
|
organization,
|
|
519
865
|
roles: [...membership?.roles ?? []],
|
|
520
|
-
permissions:
|
|
866
|
+
permissions: effectivePermissions(seed2, membership),
|
|
521
867
|
claims: {}
|
|
522
868
|
};
|
|
523
869
|
}
|
|
@@ -532,72 +878,18 @@ function listOf(value, field, problems) {
|
|
|
532
878
|
function isRecord(value) {
|
|
533
879
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
534
880
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
*{box-sizing:border-box}
|
|
544
|
-
body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;padding:24px}
|
|
545
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
546
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
547
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
548
|
-
p{margin:0;color:var(--muted)}
|
|
549
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
550
|
-
form{margin:0}
|
|
551
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
552
|
-
input[type=email]{width:100%;height:42px;padding:0 12px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit}
|
|
553
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
554
|
-
.primary{margin-top:12px;width:100%;height:42px;border:0;border-radius:8px;background:var(--accent);color:var(--accent-ink);font-family:inherit;font-size:15px;font-weight:600;cursor:pointer}
|
|
555
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
556
|
-
.list{display:grid;gap:8px}
|
|
557
|
-
.option{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;padding:11px 12px;border:1px solid var(--line);border-radius:8px;background:transparent;color:var(--ink);font:inherit;cursor:pointer}
|
|
558
|
-
.option:hover{border-color:var(--muted)}
|
|
559
|
-
.option strong{display:block;font-weight:500}
|
|
560
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
561
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
562
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
563
|
-
`;
|
|
564
|
-
function escapeHtml(value) {
|
|
565
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
566
|
-
}
|
|
567
|
-
function layout(title, body) {
|
|
568
|
-
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body><main><div class="brand">kinde-testkit</div>${body}</main></body></html>`;
|
|
569
|
-
}
|
|
570
|
-
function displayName(user) {
|
|
571
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
572
|
-
}
|
|
573
|
-
function renderSignIn(options) {
|
|
574
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
575
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
576
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
577
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
578
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
579
|
-
return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag}</span></button>`;
|
|
580
|
-
}).join("");
|
|
581
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
582
|
-
return layout(
|
|
583
|
-
"Sign in",
|
|
584
|
-
`<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}</form>`
|
|
585
|
-
);
|
|
586
|
-
}
|
|
587
|
-
function renderOrganizationPicker(options) {
|
|
588
|
-
const choices = options.organizations.map(
|
|
589
|
-
(org) => `<button class="option" type="submit" name="org" value="${escapeHtml(org.code)}"><span><strong>${escapeHtml(org.name)}</strong><small>${escapeHtml(org.code)}</small></span></button>`
|
|
590
|
-
).join("");
|
|
591
|
-
return layout(
|
|
592
|
-
"Choose an organization",
|
|
593
|
-
`<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}"><div class="list" style="margin-top:20px">${choices}</div></form>`
|
|
594
|
-
);
|
|
595
|
-
}
|
|
596
|
-
function renderMessage(title, message) {
|
|
597
|
-
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
881
|
+
function featureFlagsFor(seed2, organizationCode) {
|
|
882
|
+
if (seed2.featureFlags.length === 0) return void 0;
|
|
883
|
+
const claim = {};
|
|
884
|
+
for (const flag of seed2.featureFlags) {
|
|
885
|
+
const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
|
|
886
|
+
claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
|
|
887
|
+
}
|
|
888
|
+
return claim;
|
|
598
889
|
}
|
|
599
890
|
|
|
600
891
|
// src/oauth.ts
|
|
892
|
+
import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
601
893
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
602
894
|
var OAuthError = class extends Error {
|
|
603
895
|
constructor(status, error, description) {
|
|
@@ -609,14 +901,18 @@ var OAuthError = class extends Error {
|
|
|
609
901
|
error;
|
|
610
902
|
};
|
|
611
903
|
var AuthorizationServer = class {
|
|
612
|
-
constructor(testkit,
|
|
904
|
+
constructor(testkit, seed2, emit = () => void 0, directory, observe = () => void 0) {
|
|
613
905
|
this.testkit = testkit;
|
|
614
|
-
this.seed =
|
|
906
|
+
this.seed = seed2;
|
|
615
907
|
this.emit = emit;
|
|
908
|
+
this.directory = directory;
|
|
909
|
+
this.observe = observe;
|
|
616
910
|
}
|
|
617
911
|
testkit;
|
|
618
912
|
seed;
|
|
619
913
|
emit;
|
|
914
|
+
directory;
|
|
915
|
+
observe;
|
|
620
916
|
codes = /* @__PURE__ */ new Map();
|
|
621
917
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
622
918
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -653,6 +949,7 @@ var AuthorizationServer = class {
|
|
|
653
949
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
654
950
|
}
|
|
655
951
|
if (params.get("prompt") === "none") {
|
|
952
|
+
this.observe("session.silent");
|
|
656
953
|
return redirectWithError(res, request2, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
657
954
|
}
|
|
658
955
|
sendHtml(
|
|
@@ -666,15 +963,15 @@ var AuthorizationServer = class {
|
|
|
666
963
|
})
|
|
667
964
|
);
|
|
668
965
|
}
|
|
669
|
-
login(res,
|
|
966
|
+
login(res, form2) {
|
|
670
967
|
let request2;
|
|
671
968
|
try {
|
|
672
|
-
request2 = decodeRequest(
|
|
969
|
+
request2 = decodeRequest(form2.request ?? "");
|
|
673
970
|
} catch {
|
|
674
971
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
675
972
|
}
|
|
676
973
|
const encoded = encodeRequest(request2);
|
|
677
|
-
const ref = (
|
|
974
|
+
const ref = (form2.user || form2.email || "").trim();
|
|
678
975
|
if (!ref) {
|
|
679
976
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
|
|
680
977
|
}
|
|
@@ -682,11 +979,25 @@ var AuthorizationServer = class {
|
|
|
682
979
|
if (!user) {
|
|
683
980
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
684
981
|
}
|
|
982
|
+
if (this.directory?.isSuspended(user.id)) {
|
|
983
|
+
this.observe("identity.suspended");
|
|
984
|
+
return sendHtml(
|
|
985
|
+
res,
|
|
986
|
+
403,
|
|
987
|
+
renderSignIn({
|
|
988
|
+
request: encoded,
|
|
989
|
+
users: this.loginPageUsers(),
|
|
990
|
+
requiredOrganization: request2.orgCode ?? void 0,
|
|
991
|
+
error: `${user.email ?? user.id} is suspended and cannot sign in.`
|
|
992
|
+
})
|
|
993
|
+
);
|
|
994
|
+
}
|
|
685
995
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
686
|
-
const wanted = request2.orgCode ??
|
|
996
|
+
const wanted = request2.orgCode ?? form2.org ?? null;
|
|
687
997
|
let organizationCode = null;
|
|
688
998
|
if (wanted) {
|
|
689
999
|
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
1000
|
+
this.observe("organization.non-member");
|
|
690
1001
|
return sendHtml(
|
|
691
1002
|
res,
|
|
692
1003
|
403,
|
|
@@ -718,7 +1029,7 @@ var AuthorizationServer = class {
|
|
|
718
1029
|
user,
|
|
719
1030
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
720
1031
|
roles: [...membership?.roles ?? []],
|
|
721
|
-
permissions:
|
|
1032
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
722
1033
|
claims: {}
|
|
723
1034
|
};
|
|
724
1035
|
const code = randomToken();
|
|
@@ -734,24 +1045,27 @@ var AuthorizationServer = class {
|
|
|
734
1045
|
codeChallengeMethod: request2.codeChallengeMethod,
|
|
735
1046
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
736
1047
|
});
|
|
1048
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
737
1049
|
this.emit("user.authenticated", user);
|
|
738
1050
|
const target = new URL(request2.redirectUri);
|
|
739
1051
|
target.searchParams.set("code", code);
|
|
740
1052
|
if (request2.state !== null) target.searchParams.set("state", request2.state);
|
|
741
1053
|
redirect(res, target.toString());
|
|
742
1054
|
}
|
|
743
|
-
async token(req, res,
|
|
1055
|
+
async token(req, res, form2) {
|
|
744
1056
|
try {
|
|
745
|
-
const clientId = clientIdFrom(req,
|
|
746
|
-
const grantType =
|
|
1057
|
+
const clientId = clientIdFrom(req, form2);
|
|
1058
|
+
const grantType = form2.grant_type;
|
|
747
1059
|
if (grantType === "client_credentials") {
|
|
748
|
-
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req,
|
|
1060
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
|
|
749
1061
|
}
|
|
750
1062
|
let grant;
|
|
751
1063
|
if (grantType === "authorization_code") {
|
|
752
|
-
grant = this.redeemCode(
|
|
1064
|
+
grant = this.redeemCode(form2, clientId);
|
|
1065
|
+
this.observe("session.sign-in");
|
|
753
1066
|
} else if (grantType === "refresh_token") {
|
|
754
|
-
grant = this.redeemRefreshToken(
|
|
1067
|
+
grant = this.redeemRefreshToken(form2, clientId);
|
|
1068
|
+
this.observe("session.refresh");
|
|
755
1069
|
} else {
|
|
756
1070
|
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
757
1071
|
}
|
|
@@ -763,14 +1077,14 @@ var AuthorizationServer = class {
|
|
|
763
1077
|
throw error;
|
|
764
1078
|
}
|
|
765
1079
|
}
|
|
766
|
-
async clientCredentials(clientId, clientSecret,
|
|
1080
|
+
async clientCredentials(clientId, clientSecret, form2) {
|
|
767
1081
|
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
768
1082
|
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
769
1083
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
770
1084
|
}
|
|
771
|
-
const requested = (
|
|
772
|
-
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
773
|
-
const audience = (
|
|
1085
|
+
const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
|
|
1086
|
+
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1087
|
+
const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
|
|
774
1088
|
return {
|
|
775
1089
|
access_token: await this.testkit.m2mToken({
|
|
776
1090
|
clientId,
|
|
@@ -790,8 +1104,8 @@ var AuthorizationServer = class {
|
|
|
790
1104
|
this.refreshTokens.clear();
|
|
791
1105
|
this.signedUpUsers.clear();
|
|
792
1106
|
}
|
|
793
|
-
redeemCode(
|
|
794
|
-
const code =
|
|
1107
|
+
redeemCode(form2, clientId) {
|
|
1108
|
+
const code = form2.code ?? "";
|
|
795
1109
|
const pending = this.codes.get(code);
|
|
796
1110
|
this.codes.delete(code);
|
|
797
1111
|
if (!pending || pending.expiresAt < Date.now()) {
|
|
@@ -800,20 +1114,20 @@ var AuthorizationServer = class {
|
|
|
800
1114
|
if (pending.clientId !== clientId) {
|
|
801
1115
|
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
802
1116
|
}
|
|
803
|
-
if (
|
|
1117
|
+
if (form2.redirect_uri !== pending.redirectUri) {
|
|
804
1118
|
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
805
1119
|
}
|
|
806
1120
|
if (pending.codeChallenge) {
|
|
807
|
-
const verifier =
|
|
808
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1121
|
+
const verifier = form2.code_verifier ?? "";
|
|
1122
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
809
1123
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
810
1124
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
811
1125
|
}
|
|
812
1126
|
}
|
|
813
1127
|
return pending;
|
|
814
1128
|
}
|
|
815
|
-
redeemRefreshToken(
|
|
816
|
-
const token2 =
|
|
1129
|
+
redeemRefreshToken(form2, clientId) {
|
|
1130
|
+
const token2 = form2.refresh_token ?? "";
|
|
817
1131
|
const grant = this.refreshTokens.get(token2);
|
|
818
1132
|
this.refreshTokens.delete(token2);
|
|
819
1133
|
if (!grant) {
|
|
@@ -835,7 +1149,8 @@ var AuthorizationServer = class {
|
|
|
835
1149
|
scopes: grant.scope,
|
|
836
1150
|
clientId: grant.clientId,
|
|
837
1151
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
838
|
-
authTime: grant.authTime
|
|
1152
|
+
authTime: grant.authTime,
|
|
1153
|
+
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
839
1154
|
}),
|
|
840
1155
|
expires_in: this.testkit.accessTokenLifetime,
|
|
841
1156
|
scope: grant.scope.join(" "),
|
|
@@ -886,11 +1201,13 @@ var AuthorizationServer = class {
|
|
|
886
1201
|
phone: null
|
|
887
1202
|
});
|
|
888
1203
|
}
|
|
889
|
-
revoke(res,
|
|
890
|
-
if (
|
|
1204
|
+
revoke(res, form2) {
|
|
1205
|
+
if (form2.token) this.refreshTokens.delete(form2.token);
|
|
1206
|
+
this.observe("session.revoke");
|
|
891
1207
|
sendJson(res, 200, {});
|
|
892
1208
|
}
|
|
893
1209
|
logout(res, params) {
|
|
1210
|
+
this.observe("session.sign-out");
|
|
894
1211
|
const target = params.get("redirect");
|
|
895
1212
|
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
896
1213
|
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
@@ -902,6 +1219,8 @@ var AuthorizationServer = class {
|
|
|
902
1219
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
903
1220
|
if (!this.signedUpUsers.has(user.id)) {
|
|
904
1221
|
this.signedUpUsers.set(user.id, user);
|
|
1222
|
+
this.observe("identity.unseeded");
|
|
1223
|
+
if (this.directory) this.seed.users.push(user);
|
|
905
1224
|
this.emit("user.created", user);
|
|
906
1225
|
}
|
|
907
1226
|
return this.signedUpUsers.get(user.id);
|
|
@@ -923,92 +1242,789 @@ function parseAuthorizeRequest(params) {
|
|
|
923
1242
|
if (!redirectUri || !isHttpUrl(redirectUri)) {
|
|
924
1243
|
throw new Error("redirect_uri must be an absolute http or https URL.");
|
|
925
1244
|
}
|
|
926
|
-
if (params.get("response_type") !== "code") {
|
|
927
|
-
throw new Error('response_type must be "code".');
|
|
1245
|
+
if (params.get("response_type") !== "code") {
|
|
1246
|
+
throw new Error('response_type must be "code".');
|
|
1247
|
+
}
|
|
1248
|
+
const method = params.get("code_challenge_method");
|
|
1249
|
+
const challenge = params.get("code_challenge");
|
|
1250
|
+
if (challenge && method && method !== "S256" && method !== "plain") {
|
|
1251
|
+
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
1252
|
+
}
|
|
1253
|
+
return {
|
|
1254
|
+
clientId,
|
|
1255
|
+
redirectUri,
|
|
1256
|
+
state: params.get("state"),
|
|
1257
|
+
scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
|
|
1258
|
+
nonce: params.get("nonce"),
|
|
1259
|
+
audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
|
|
1260
|
+
orgCode: params.get("org_code"),
|
|
1261
|
+
loginHint: params.get("login_hint"),
|
|
1262
|
+
codeChallenge: challenge,
|
|
1263
|
+
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
function encodeRequest(request2) {
|
|
1267
|
+
return Buffer.from(JSON.stringify(request2)).toString("base64url");
|
|
1268
|
+
}
|
|
1269
|
+
function decodeRequest(value) {
|
|
1270
|
+
const request2 = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
1271
|
+
if (!request2.clientId || !request2.redirectUri || !isHttpUrl(request2.redirectUri)) {
|
|
1272
|
+
throw new Error("invalid request");
|
|
1273
|
+
}
|
|
1274
|
+
return request2;
|
|
1275
|
+
}
|
|
1276
|
+
function clientIdFrom(req, form2) {
|
|
1277
|
+
const header = req.headers.authorization ?? "";
|
|
1278
|
+
if (header.startsWith("Basic ")) {
|
|
1279
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1280
|
+
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
1281
|
+
if (id) return id;
|
|
1282
|
+
}
|
|
1283
|
+
if (form2.client_id) return form2.client_id;
|
|
1284
|
+
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
1285
|
+
}
|
|
1286
|
+
function clientSecretFrom(req, form2) {
|
|
1287
|
+
const header = req.headers.authorization ?? "";
|
|
1288
|
+
if (header.startsWith("Basic ")) {
|
|
1289
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1290
|
+
const index = decoded.indexOf(":");
|
|
1291
|
+
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1292
|
+
}
|
|
1293
|
+
return form2.client_secret ?? null;
|
|
1294
|
+
}
|
|
1295
|
+
function redirectWithError(res, request2, error, description) {
|
|
1296
|
+
const target = new URL(request2.redirectUri);
|
|
1297
|
+
target.searchParams.set("error", error);
|
|
1298
|
+
target.searchParams.set("error_description", description);
|
|
1299
|
+
if (request2.state !== null) target.searchParams.set("state", request2.state);
|
|
1300
|
+
redirect(res, target.toString());
|
|
1301
|
+
}
|
|
1302
|
+
function isHttpUrl(value) {
|
|
1303
|
+
try {
|
|
1304
|
+
const { protocol } = new URL(value);
|
|
1305
|
+
return protocol === "http:" || protocol === "https:";
|
|
1306
|
+
} catch {
|
|
1307
|
+
return false;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
function randomToken() {
|
|
1311
|
+
return randomBytes2(32).toString("base64url");
|
|
1312
|
+
}
|
|
1313
|
+
function safeEqual(a, b) {
|
|
1314
|
+
const left = Buffer.from(a);
|
|
1315
|
+
const right = Buffer.from(b);
|
|
1316
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
1317
|
+
}
|
|
1318
|
+
function redirect(res, location) {
|
|
1319
|
+
res.writeHead(303, { location, "cache-control": "no-store" });
|
|
1320
|
+
res.end();
|
|
1321
|
+
}
|
|
1322
|
+
function sendHtml(res, status, html) {
|
|
1323
|
+
res.writeHead(status, {
|
|
1324
|
+
"content-type": "text/html; charset=utf-8",
|
|
1325
|
+
"cache-control": "no-store",
|
|
1326
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
1327
|
+
});
|
|
1328
|
+
res.end(html);
|
|
1329
|
+
}
|
|
1330
|
+
function sendJson(res, status, body) {
|
|
1331
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1332
|
+
res.end(JSON.stringify(body));
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
// src/account.ts
|
|
1336
|
+
var DEFAULT_PAGE_SIZE = 10;
|
|
1337
|
+
var AccountApi = class {
|
|
1338
|
+
constructor(testkit, directory) {
|
|
1339
|
+
this.testkit = testkit;
|
|
1340
|
+
this.directory = directory;
|
|
1341
|
+
}
|
|
1342
|
+
testkit;
|
|
1343
|
+
directory;
|
|
1344
|
+
async handle(req, res, url) {
|
|
1345
|
+
if (!url.pathname.startsWith("/account_api/v1/")) return false;
|
|
1346
|
+
if ((req.method ?? "GET") !== "GET") {
|
|
1347
|
+
sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
|
|
1348
|
+
return true;
|
|
1349
|
+
}
|
|
1350
|
+
const header = req.headers.authorization ?? "";
|
|
1351
|
+
let token2;
|
|
1352
|
+
try {
|
|
1353
|
+
if (!header.startsWith("Bearer ")) throw new Error("missing");
|
|
1354
|
+
token2 = await this.testkit.verify(header.slice(7));
|
|
1355
|
+
} catch {
|
|
1356
|
+
sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
|
|
1357
|
+
return true;
|
|
1358
|
+
}
|
|
1359
|
+
if (typeof token2.sub !== "string" || Array.isArray(token2.gty) && token2.gty.includes("client_credentials")) {
|
|
1360
|
+
sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
|
|
1361
|
+
return true;
|
|
1362
|
+
}
|
|
1363
|
+
const userId = token2.sub;
|
|
1364
|
+
const orgCode = typeof token2.org_code === "string" ? token2.org_code : null;
|
|
1365
|
+
const path = url.pathname.slice("/account_api/v1/".length);
|
|
1366
|
+
const d = this.directory;
|
|
1367
|
+
const membership = orgCode ? d.membership(userId, orgCode) : void 0;
|
|
1368
|
+
if (path === "permissions") {
|
|
1369
|
+
const items = effectivePermissions(d.seed, membership).map((key) => {
|
|
1370
|
+
const p = d.ensurePermission(key);
|
|
1371
|
+
return { id: p.id, name: p.name, key: p.key };
|
|
1372
|
+
});
|
|
1373
|
+
sendPage(res, url, "permissions", items, { org_code: orgCode });
|
|
1374
|
+
return true;
|
|
1375
|
+
}
|
|
1376
|
+
if (path.startsWith("permission/")) {
|
|
1377
|
+
const key = decodeURIComponent(path.slice("permission/".length));
|
|
1378
|
+
sendJson2(res, 200, {
|
|
1379
|
+
data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
|
|
1380
|
+
});
|
|
1381
|
+
return true;
|
|
1382
|
+
}
|
|
1383
|
+
if (path === "roles") {
|
|
1384
|
+
const items = (membership?.roles ?? []).map((key) => {
|
|
1385
|
+
const r = d.ensureRole(key);
|
|
1386
|
+
return { id: r.id, name: r.name, key: r.key };
|
|
1387
|
+
});
|
|
1388
|
+
sendPage(res, url, "roles", items, { org_code: orgCode });
|
|
1389
|
+
return true;
|
|
1390
|
+
}
|
|
1391
|
+
if (path === "feature_flags") {
|
|
1392
|
+
const items = d.seed.featureFlags.map((flag) => ({
|
|
1393
|
+
id: flag.id,
|
|
1394
|
+
name: flag.name,
|
|
1395
|
+
key: flag.key,
|
|
1396
|
+
type: flag.type,
|
|
1397
|
+
value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
|
|
1398
|
+
}));
|
|
1399
|
+
sendPage(res, url, "feature_flags", items, {});
|
|
1400
|
+
return true;
|
|
1401
|
+
}
|
|
1402
|
+
if (path === "properties") {
|
|
1403
|
+
const values = d.seed.userProperties[userId] ?? {};
|
|
1404
|
+
const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
|
|
1405
|
+
sendPage(res, url, "properties", items, {});
|
|
1406
|
+
return true;
|
|
1407
|
+
}
|
|
1408
|
+
if (path === "entitlements" || path.startsWith("entitlement")) {
|
|
1409
|
+
const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
|
|
1410
|
+
const entitlements = (plan?.entitlements ?? []).map((e) => ({
|
|
1411
|
+
id: e.id,
|
|
1412
|
+
fixed_charge: e.fixedCharge,
|
|
1413
|
+
price_name: e.priceName,
|
|
1414
|
+
unit_amount: e.unitAmount,
|
|
1415
|
+
feature_key: e.featureKey,
|
|
1416
|
+
feature_name: e.featureName,
|
|
1417
|
+
entitlement_limit_max: e.limitMax,
|
|
1418
|
+
entitlement_limit_min: e.limitMin
|
|
1419
|
+
}));
|
|
1420
|
+
if (path === "entitlements") {
|
|
1421
|
+
const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
|
|
1422
|
+
sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
|
|
1423
|
+
return true;
|
|
1424
|
+
}
|
|
1425
|
+
const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
|
|
1426
|
+
const entitlement = entitlements.find((e) => e.feature_key === key);
|
|
1427
|
+
if (!entitlement) {
|
|
1428
|
+
sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
|
|
1429
|
+
} else {
|
|
1430
|
+
sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
|
|
1431
|
+
}
|
|
1432
|
+
return true;
|
|
1433
|
+
}
|
|
1434
|
+
if (path === "portal_link") {
|
|
1435
|
+
sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
|
|
1436
|
+
return true;
|
|
1437
|
+
}
|
|
1438
|
+
sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
|
|
1439
|
+
return true;
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1442
|
+
function sendPage(res, url, field, items, extra) {
|
|
1443
|
+
const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
|
|
1444
|
+
const after = url.searchParams.get("starting_after");
|
|
1445
|
+
const start2 = after ? items.findIndex((item) => item.id === after) + 1 : 0;
|
|
1446
|
+
const page = items.slice(start2, start2 + size);
|
|
1447
|
+
const hasMore = start2 + size < items.length;
|
|
1448
|
+
sendJson2(res, 200, {
|
|
1449
|
+
data: { ...extra, [field]: page },
|
|
1450
|
+
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
function errors(code, message) {
|
|
1454
|
+
return { errors: [{ code, message }] };
|
|
1455
|
+
}
|
|
1456
|
+
function sendJson2(res, status, body) {
|
|
1457
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1458
|
+
res.end(JSON.stringify(body));
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
// src/directory.ts
|
|
1462
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1463
|
+
var Directory = class {
|
|
1464
|
+
constructor(seed2) {
|
|
1465
|
+
this.seed = seed2;
|
|
1466
|
+
this.snapshot = JSON.stringify(seed2);
|
|
1467
|
+
}
|
|
1468
|
+
seed;
|
|
1469
|
+
userMeta = /* @__PURE__ */ new Map();
|
|
1470
|
+
orgMeta = /* @__PURE__ */ new Map();
|
|
1471
|
+
snapshot;
|
|
1472
|
+
restore() {
|
|
1473
|
+
const original = JSON.parse(this.snapshot);
|
|
1474
|
+
for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
|
|
1475
|
+
this.seed[key].splice(0, this.seed[key].length, ...original[key]);
|
|
1476
|
+
}
|
|
1477
|
+
this.userMeta.clear();
|
|
1478
|
+
this.orgMeta.clear();
|
|
1479
|
+
}
|
|
1480
|
+
/** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
|
|
1481
|
+
load(next) {
|
|
1482
|
+
for (const key of Object.keys(next)) {
|
|
1483
|
+
const current = this.seed[key];
|
|
1484
|
+
if (Array.isArray(current)) {
|
|
1485
|
+
current.splice(0, current.length, ...next[key]);
|
|
1486
|
+
} else {
|
|
1487
|
+
const record = current;
|
|
1488
|
+
for (const name of Object.keys(record)) delete record[name];
|
|
1489
|
+
Object.assign(record, next[key]);
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
this.snapshot = JSON.stringify(this.seed);
|
|
1493
|
+
this.userMeta.clear();
|
|
1494
|
+
this.orgMeta.clear();
|
|
1495
|
+
}
|
|
1496
|
+
user(id) {
|
|
1497
|
+
return this.seed.users.find((user) => user.id === id);
|
|
1498
|
+
}
|
|
1499
|
+
meta(user) {
|
|
1500
|
+
let meta = this.userMeta.get(user.id);
|
|
1501
|
+
if (!meta) {
|
|
1502
|
+
meta = {
|
|
1503
|
+
providedId: null,
|
|
1504
|
+
isSuspended: false,
|
|
1505
|
+
isPasswordResetRequested: false,
|
|
1506
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1507
|
+
totalSignIns: 0,
|
|
1508
|
+
lastSignedIn: null
|
|
1509
|
+
};
|
|
1510
|
+
this.userMeta.set(user.id, meta);
|
|
1511
|
+
}
|
|
1512
|
+
return meta;
|
|
1513
|
+
}
|
|
1514
|
+
isSuspended(userId) {
|
|
1515
|
+
return this.userMeta.get(userId)?.isSuspended ?? false;
|
|
1516
|
+
}
|
|
1517
|
+
recordSignIn(user, organizationCode) {
|
|
1518
|
+
const meta = this.meta(user);
|
|
1519
|
+
meta.totalSignIns += 1;
|
|
1520
|
+
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
1521
|
+
void organizationCode;
|
|
1522
|
+
}
|
|
1523
|
+
createUser(input) {
|
|
1524
|
+
const user = createKindeUser({
|
|
1525
|
+
id: `kp_${randomBytes3(16).toString("hex")}`,
|
|
1526
|
+
email: input.email ?? null,
|
|
1527
|
+
givenName: input.givenName ?? null,
|
|
1528
|
+
familyName: input.familyName ?? null,
|
|
1529
|
+
picture: input.picture ?? null
|
|
1530
|
+
});
|
|
1531
|
+
this.seed.users.push(user);
|
|
1532
|
+
this.meta(user).providedId = input.providedId ?? null;
|
|
1533
|
+
return user;
|
|
1534
|
+
}
|
|
1535
|
+
deleteUser(id) {
|
|
1536
|
+
const index = this.seed.users.findIndex((user) => user.id === id);
|
|
1537
|
+
if (index < 0) return false;
|
|
1538
|
+
this.seed.users.splice(index, 1);
|
|
1539
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1540
|
+
if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
|
|
1541
|
+
}
|
|
1542
|
+
this.userMeta.delete(id);
|
|
1543
|
+
return true;
|
|
1544
|
+
}
|
|
1545
|
+
organization(code) {
|
|
1546
|
+
return this.seed.organizations.find((org) => org.code === code);
|
|
1547
|
+
}
|
|
1548
|
+
orgInfo(org) {
|
|
1549
|
+
let meta = this.orgMeta.get(org.code);
|
|
1550
|
+
if (!meta) {
|
|
1551
|
+
meta = {
|
|
1552
|
+
externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
|
|
1553
|
+
handle: slug(org.name),
|
|
1554
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1555
|
+
isAllowRegistrations: false
|
|
1556
|
+
};
|
|
1557
|
+
this.orgMeta.set(org.code, meta);
|
|
1558
|
+
}
|
|
1559
|
+
return meta;
|
|
1560
|
+
}
|
|
1561
|
+
createOrganization(input) {
|
|
1562
|
+
const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
|
|
1563
|
+
this.seed.organizations.push(org);
|
|
1564
|
+
const meta = this.orgInfo(org);
|
|
1565
|
+
meta.externalId = input.externalId ?? null;
|
|
1566
|
+
if (input.handle) meta.handle = input.handle;
|
|
1567
|
+
return org;
|
|
1568
|
+
}
|
|
1569
|
+
deleteOrganization(code) {
|
|
1570
|
+
const index = this.seed.organizations.findIndex((org) => org.code === code);
|
|
1571
|
+
if (index < 0) return false;
|
|
1572
|
+
this.seed.organizations.splice(index, 1);
|
|
1573
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1574
|
+
if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
|
|
1575
|
+
}
|
|
1576
|
+
this.orgMeta.delete(code);
|
|
1577
|
+
return true;
|
|
1578
|
+
}
|
|
1579
|
+
membership(userId, organizationCode) {
|
|
1580
|
+
return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1581
|
+
}
|
|
1582
|
+
addMembership(userId, organizationCode, roles = [], permissions = []) {
|
|
1583
|
+
const existing = this.membership(userId, organizationCode);
|
|
1584
|
+
if (existing) return existing;
|
|
1585
|
+
const membership = createMembership({ userId, organizationCode, roles, permissions });
|
|
1586
|
+
this.seed.memberships.push(membership);
|
|
1587
|
+
for (const key of roles) this.ensureRole(key);
|
|
1588
|
+
for (const key of permissions) this.ensurePermission(key);
|
|
1589
|
+
return membership;
|
|
1590
|
+
}
|
|
1591
|
+
removeMembership(userId, organizationCode) {
|
|
1592
|
+
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1593
|
+
if (index < 0) return false;
|
|
1594
|
+
this.seed.memberships.splice(index, 1);
|
|
1595
|
+
return true;
|
|
1596
|
+
}
|
|
1597
|
+
role(idOrKey) {
|
|
1598
|
+
return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
|
|
1599
|
+
}
|
|
1600
|
+
permission(idOrKey) {
|
|
1601
|
+
return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
|
|
1602
|
+
}
|
|
1603
|
+
ensureRole(key, extra = {}) {
|
|
1604
|
+
const existing = this.role(key);
|
|
1605
|
+
if (existing) return existing;
|
|
1606
|
+
const role = roleRecord(key, extra);
|
|
1607
|
+
this.seed.roles.push(role);
|
|
1608
|
+
return role;
|
|
1609
|
+
}
|
|
1610
|
+
ensurePermission(key, extra = {}) {
|
|
1611
|
+
const existing = this.permission(key);
|
|
1612
|
+
if (existing) return existing;
|
|
1613
|
+
const permission = permissionRecord(key, extra);
|
|
1614
|
+
this.seed.permissions.push(permission);
|
|
1615
|
+
return permission;
|
|
1616
|
+
}
|
|
1617
|
+
deleteRole(id) {
|
|
1618
|
+
const role = this.role(id);
|
|
1619
|
+
if (!role) return void 0;
|
|
1620
|
+
this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
|
|
1621
|
+
for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
|
|
1622
|
+
return role;
|
|
1623
|
+
}
|
|
1624
|
+
deletePermission(id) {
|
|
1625
|
+
const permission = this.permission(id);
|
|
1626
|
+
if (!permission) return void 0;
|
|
1627
|
+
this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
|
|
1628
|
+
for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
|
|
1629
|
+
for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
|
|
1630
|
+
return permission;
|
|
1631
|
+
}
|
|
1632
|
+
};
|
|
1633
|
+
|
|
1634
|
+
// src/management.ts
|
|
1635
|
+
var OK = { code: "OK", message: "Success" };
|
|
1636
|
+
var DEFAULT_PAGE_SIZE2 = 10;
|
|
1637
|
+
var MAX_PAGE_SIZE = 500;
|
|
1638
|
+
var ManagementApi = class {
|
|
1639
|
+
constructor(testkit, directory, webhooks) {
|
|
1640
|
+
this.testkit = testkit;
|
|
1641
|
+
this.directory = directory;
|
|
1642
|
+
this.webhooks = webhooks;
|
|
1643
|
+
this.register();
|
|
1644
|
+
}
|
|
1645
|
+
testkit;
|
|
1646
|
+
directory;
|
|
1647
|
+
webhooks;
|
|
1648
|
+
routes = [];
|
|
1649
|
+
async handle(req, res, url, readBody) {
|
|
1650
|
+
if (!url.pathname.startsWith("/api/v1/")) return false;
|
|
1651
|
+
const method = req.method ?? "GET";
|
|
1652
|
+
const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
1653
|
+
if (!route) {
|
|
1654
|
+
sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
|
|
1655
|
+
return true;
|
|
1656
|
+
}
|
|
1657
|
+
const token2 = await this.authenticate(req.headers.authorization);
|
|
1658
|
+
if ("error" in token2) {
|
|
1659
|
+
sendJson3(res, 403, errors2(token2.code, token2.error));
|
|
1660
|
+
return true;
|
|
1661
|
+
}
|
|
1662
|
+
const granted = typeof token2.payload.scope === "string" ? token2.payload.scope.split(" ").filter(Boolean) : [];
|
|
1663
|
+
if (granted.length > 0 && !granted.includes(route.scope)) {
|
|
1664
|
+
sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
|
|
1665
|
+
return true;
|
|
1666
|
+
}
|
|
1667
|
+
const match = route.pattern.exec(url.pathname);
|
|
1668
|
+
const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
|
|
1669
|
+
const body = method === "GET" || method === "DELETE" ? {} : await readBody();
|
|
1670
|
+
const [status, payload] = await route.handler({ params, query: url.searchParams, body });
|
|
1671
|
+
sendJson3(res, status, payload);
|
|
1672
|
+
return true;
|
|
1673
|
+
}
|
|
1674
|
+
async authenticate(header) {
|
|
1675
|
+
if (!header?.startsWith("Bearer ")) {
|
|
1676
|
+
return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
|
|
1677
|
+
}
|
|
1678
|
+
let payload;
|
|
1679
|
+
try {
|
|
1680
|
+
payload = await this.testkit.verify(header.slice(7));
|
|
1681
|
+
} catch {
|
|
1682
|
+
return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
|
|
1683
|
+
}
|
|
1684
|
+
const audience = `${this.testkit.issuer}/api`;
|
|
1685
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
1686
|
+
if (!aud.includes(audience)) {
|
|
1687
|
+
return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
|
|
1688
|
+
}
|
|
1689
|
+
if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
|
|
1690
|
+
return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
|
|
1691
|
+
}
|
|
1692
|
+
return { payload };
|
|
1693
|
+
}
|
|
1694
|
+
route(method, path, scope, handler) {
|
|
1695
|
+
const keys = [];
|
|
1696
|
+
const pattern = new RegExp(
|
|
1697
|
+
`^${path.replace(/\{(\w+)\}/g, (_, key) => {
|
|
1698
|
+
keys.push(key);
|
|
1699
|
+
return "([^/]+)";
|
|
1700
|
+
})}$`
|
|
1701
|
+
);
|
|
1702
|
+
this.routes.push({ method, pattern, keys, scope, handler });
|
|
1703
|
+
}
|
|
1704
|
+
register() {
|
|
1705
|
+
const d = this.directory;
|
|
1706
|
+
this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
|
|
1707
|
+
let users = [...d.seed.users];
|
|
1708
|
+
const userId = query.get("user_id");
|
|
1709
|
+
const email = query.get("email")?.toLowerCase();
|
|
1710
|
+
if (userId) users = users.filter((u) => u.id === userId);
|
|
1711
|
+
if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
|
|
1712
|
+
const page = paginate(users, query);
|
|
1713
|
+
return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
|
|
1714
|
+
});
|
|
1715
|
+
this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
|
|
1716
|
+
const user = d.user(query.get("id") ?? "");
|
|
1717
|
+
return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
|
|
1718
|
+
});
|
|
1719
|
+
this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
|
|
1720
|
+
const profile = body.profile ?? {};
|
|
1721
|
+
const identities = Array.isArray(body.identities) ? body.identities : [];
|
|
1722
|
+
const emailIdentity = identities.find((i) => i.type === "email");
|
|
1723
|
+
const email = (emailIdentity?.details ?? {}).email;
|
|
1724
|
+
if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
|
|
1725
|
+
return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
|
|
1726
|
+
}
|
|
1727
|
+
const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
|
|
1728
|
+
if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
|
|
1729
|
+
const user = d.createUser({
|
|
1730
|
+
email: typeof email === "string" ? email : null,
|
|
1731
|
+
givenName: str(profile.given_name),
|
|
1732
|
+
familyName: str(profile.family_name),
|
|
1733
|
+
picture: str(profile.picture),
|
|
1734
|
+
providedId: str(body.provided_id)
|
|
1735
|
+
});
|
|
1736
|
+
if (orgCode) d.addMembership(user.id, orgCode);
|
|
1737
|
+
this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
|
|
1738
|
+
return [
|
|
1739
|
+
200,
|
|
1740
|
+
{ id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
|
|
1741
|
+
];
|
|
1742
|
+
});
|
|
1743
|
+
this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
|
|
1744
|
+
const user = d.user(query.get("id") ?? "");
|
|
1745
|
+
if (!user) return notFound("USER_INVALID", "No user has that id.");
|
|
1746
|
+
if (typeof body.given_name === "string") user.givenName = body.given_name;
|
|
1747
|
+
if (typeof body.family_name === "string") user.familyName = body.family_name;
|
|
1748
|
+
if (typeof body.picture === "string") user.picture = body.picture;
|
|
1749
|
+
const meta = d.meta(user);
|
|
1750
|
+
if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
|
|
1751
|
+
if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
|
|
1752
|
+
if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
|
|
1753
|
+
this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
|
|
1754
|
+
return [
|
|
1755
|
+
200,
|
|
1756
|
+
{
|
|
1757
|
+
id: user.id,
|
|
1758
|
+
given_name: user.givenName,
|
|
1759
|
+
family_name: user.familyName,
|
|
1760
|
+
email: user.email,
|
|
1761
|
+
is_suspended: meta.isSuspended,
|
|
1762
|
+
is_password_reset_requested: meta.isPasswordResetRequested,
|
|
1763
|
+
picture: user.picture
|
|
1764
|
+
}
|
|
1765
|
+
];
|
|
1766
|
+
});
|
|
1767
|
+
this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
|
|
1768
|
+
const id = query.get("id") ?? "";
|
|
1769
|
+
if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
|
|
1770
|
+
this.webhooks.emit("user.deleted", { user: { id } });
|
|
1771
|
+
return [200, OK];
|
|
1772
|
+
});
|
|
1773
|
+
this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
|
|
1774
|
+
const page = paginate(d.seed.organizations, query);
|
|
1775
|
+
return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
|
|
1776
|
+
});
|
|
1777
|
+
this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
|
|
1778
|
+
const org = d.organization(query.get("code") ?? "");
|
|
1779
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1780
|
+
const meta = d.orgInfo(org);
|
|
1781
|
+
return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
|
|
1782
|
+
});
|
|
1783
|
+
this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
|
|
1784
|
+
if (typeof body.name !== "string" || body.name.trim() === "") {
|
|
1785
|
+
return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
|
|
1786
|
+
}
|
|
1787
|
+
const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
|
|
1788
|
+
if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
|
|
1789
|
+
this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
|
|
1790
|
+
return [200, { ...OK, organization: { code: org.code } }];
|
|
1791
|
+
});
|
|
1792
|
+
this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
|
|
1793
|
+
const org = d.organization(params.org_code);
|
|
1794
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1795
|
+
const meta = d.orgInfo(org);
|
|
1796
|
+
if (typeof body.name === "string") org.name = body.name;
|
|
1797
|
+
if (typeof body.external_id === "string") meta.externalId = body.external_id;
|
|
1798
|
+
if (typeof body.handle === "string") meta.handle = body.handle;
|
|
1799
|
+
if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
|
|
1800
|
+
this.webhooks.emit("organization.updated", {
|
|
1801
|
+
organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
|
|
1802
|
+
});
|
|
1803
|
+
return [200, OK];
|
|
1804
|
+
});
|
|
1805
|
+
this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
|
|
1806
|
+
if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1807
|
+
this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
|
|
1808
|
+
return [200, OK];
|
|
1809
|
+
});
|
|
1810
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
|
|
1811
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1812
|
+
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);
|
|
1813
|
+
const page = paginate(members, query);
|
|
1814
|
+
return [
|
|
1815
|
+
200,
|
|
1816
|
+
{
|
|
1817
|
+
...OK,
|
|
1818
|
+
organization_users: page.items.map(({ membership, user }) => ({
|
|
1819
|
+
id: user.id,
|
|
1820
|
+
email: user.email,
|
|
1821
|
+
full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
|
|
1822
|
+
last_name: user.familyName,
|
|
1823
|
+
first_name: user.givenName,
|
|
1824
|
+
picture: user.picture,
|
|
1825
|
+
joined_on: d.meta(user).createdOn,
|
|
1826
|
+
last_accessed_on: d.meta(user).lastSignedIn,
|
|
1827
|
+
is_suspended: d.meta(user).isSuspended,
|
|
1828
|
+
roles: [...membership.roles]
|
|
1829
|
+
})),
|
|
1830
|
+
next_token: page.nextToken
|
|
1831
|
+
}
|
|
1832
|
+
];
|
|
1833
|
+
});
|
|
1834
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
|
|
1835
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1836
|
+
const users = Array.isArray(body.users) ? body.users : [];
|
|
1837
|
+
const added = [];
|
|
1838
|
+
const blocked = [];
|
|
1839
|
+
for (const entry of users) {
|
|
1840
|
+
const id = typeof entry.id === "string" ? entry.id : "";
|
|
1841
|
+
if (!d.user(id)) {
|
|
1842
|
+
blocked.push(id);
|
|
1843
|
+
continue;
|
|
1844
|
+
}
|
|
1845
|
+
d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
|
|
1846
|
+
added.push(id);
|
|
1847
|
+
}
|
|
1848
|
+
return [200, { ...OK, users_added: added, users_blocked: blocked }];
|
|
1849
|
+
});
|
|
1850
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
|
|
1851
|
+
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}.`);
|
|
1852
|
+
});
|
|
1853
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
|
|
1854
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1855
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1856
|
+
const roles = membership.roles.map((key) => d.ensureRole(key));
|
|
1857
|
+
return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
|
|
1858
|
+
});
|
|
1859
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
|
|
1860
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1861
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1862
|
+
const role = d.role(str(body.role_id) ?? "");
|
|
1863
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1864
|
+
if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
|
|
1865
|
+
return [200, OK];
|
|
1866
|
+
});
|
|
1867
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
|
|
1868
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1869
|
+
const role = d.role(params.role_id);
|
|
1870
|
+
if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
|
|
1871
|
+
membership.roles = membership.roles.filter((key) => key !== role.key);
|
|
1872
|
+
return [200, OK];
|
|
1873
|
+
});
|
|
1874
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
|
|
1875
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1876
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1877
|
+
const permissions = effectivePermissions(d.seed, membership).map((key) => {
|
|
1878
|
+
const permission = d.ensurePermission(key);
|
|
1879
|
+
const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
|
|
1880
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
|
|
1881
|
+
});
|
|
1882
|
+
return [200, { ...OK, permissions }];
|
|
1883
|
+
});
|
|
1884
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
|
|
1885
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1886
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1887
|
+
const permission = d.permission(str(body.permission_id) ?? "");
|
|
1888
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1889
|
+
if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
|
|
1890
|
+
return [200, OK];
|
|
1891
|
+
});
|
|
1892
|
+
this.route(
|
|
1893
|
+
"DELETE",
|
|
1894
|
+
"/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
|
|
1895
|
+
"delete:organization_user_permissions",
|
|
1896
|
+
({ params }) => {
|
|
1897
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1898
|
+
const permission = d.permission(params.permission_id);
|
|
1899
|
+
if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
|
|
1900
|
+
membership.permissions = membership.permissions.filter((key) => key !== permission.key);
|
|
1901
|
+
return [200, OK];
|
|
1902
|
+
}
|
|
1903
|
+
);
|
|
1904
|
+
this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
|
|
1905
|
+
const page = paginate(d.seed.roles, query);
|
|
1906
|
+
return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
|
|
1907
|
+
});
|
|
1908
|
+
this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
|
|
1909
|
+
const key = str(body.key);
|
|
1910
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
|
|
1911
|
+
if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
|
|
1912
|
+
const role = d.ensureRole(key, {
|
|
1913
|
+
name: str(body.name) ?? void 0,
|
|
1914
|
+
description: str(body.description) ?? void 0,
|
|
1915
|
+
isDefault: body.is_default_role === true
|
|
1916
|
+
});
|
|
1917
|
+
this.webhooks.emit("role.created", {
|
|
1918
|
+
role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
|
|
1919
|
+
});
|
|
1920
|
+
return [201, { ...OK, role: { id: role.id } }];
|
|
1921
|
+
});
|
|
1922
|
+
this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
|
|
1923
|
+
const role = d.role(params.role_id);
|
|
1924
|
+
return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
|
|
1925
|
+
});
|
|
1926
|
+
this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
|
|
1927
|
+
const role = d.deleteRole(params.role_id);
|
|
1928
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1929
|
+
this.webhooks.emit("role.deleted", { role: { id: role.id } });
|
|
1930
|
+
return [200, OK];
|
|
1931
|
+
});
|
|
1932
|
+
this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
|
|
1933
|
+
const role = d.role(params.role_id);
|
|
1934
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1935
|
+
return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
|
|
1936
|
+
});
|
|
1937
|
+
this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
|
|
1938
|
+
const page = paginate(d.seed.permissions, query);
|
|
1939
|
+
return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
|
|
1940
|
+
});
|
|
1941
|
+
this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
|
|
1942
|
+
const key = str(body.key);
|
|
1943
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
|
|
1944
|
+
if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
|
|
1945
|
+
const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
|
|
1946
|
+
this.webhooks.emit("permission.created", {
|
|
1947
|
+
permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
|
|
1948
|
+
});
|
|
1949
|
+
return [201, OK];
|
|
1950
|
+
});
|
|
1951
|
+
this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
|
|
1952
|
+
const permission = d.deletePermission(params.permission_id);
|
|
1953
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1954
|
+
this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
|
|
1955
|
+
return [200, OK];
|
|
1956
|
+
});
|
|
1957
|
+
}
|
|
1958
|
+
userListItem(user) {
|
|
1959
|
+
const meta = this.directory.meta(user);
|
|
1960
|
+
return {
|
|
1961
|
+
id: user.id,
|
|
1962
|
+
provided_id: meta.providedId,
|
|
1963
|
+
email: user.email,
|
|
1964
|
+
phone: null,
|
|
1965
|
+
username: null,
|
|
1966
|
+
last_name: user.familyName,
|
|
1967
|
+
first_name: user.givenName,
|
|
1968
|
+
is_suspended: meta.isSuspended,
|
|
1969
|
+
picture: user.picture,
|
|
1970
|
+
total_sign_ins: meta.totalSignIns,
|
|
1971
|
+
failed_sign_ins: 0,
|
|
1972
|
+
last_signed_in: meta.lastSignedIn,
|
|
1973
|
+
created_on: meta.createdOn,
|
|
1974
|
+
organizations: this.organizationsOf(user),
|
|
1975
|
+
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
1976
|
+
};
|
|
928
1977
|
}
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
1978
|
+
userDetail(user) {
|
|
1979
|
+
const { email, ...rest } = this.userListItem(user);
|
|
1980
|
+
return { ...rest, preferred_email: email };
|
|
933
1981
|
}
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
redirectUri,
|
|
937
|
-
state: params.get("state"),
|
|
938
|
-
scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
|
|
939
|
-
nonce: params.get("nonce"),
|
|
940
|
-
audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
|
|
941
|
-
orgCode: params.get("org_code"),
|
|
942
|
-
loginHint: params.get("login_hint"),
|
|
943
|
-
codeChallenge: challenge,
|
|
944
|
-
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
945
|
-
};
|
|
946
|
-
}
|
|
947
|
-
function encodeRequest(request2) {
|
|
948
|
-
return Buffer.from(JSON.stringify(request2)).toString("base64url");
|
|
949
|
-
}
|
|
950
|
-
function decodeRequest(value) {
|
|
951
|
-
const request2 = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
952
|
-
if (!request2.clientId || !request2.redirectUri || !isHttpUrl(request2.redirectUri)) {
|
|
953
|
-
throw new Error("invalid request");
|
|
1982
|
+
organizationsOf(user) {
|
|
1983
|
+
return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
|
|
954
1984
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
1985
|
+
organizationItem(org) {
|
|
1986
|
+
const meta = this.directory.orgInfo(org);
|
|
1987
|
+
return {
|
|
1988
|
+
code: org.code,
|
|
1989
|
+
name: org.name,
|
|
1990
|
+
handle: meta.handle,
|
|
1991
|
+
is_default: false,
|
|
1992
|
+
external_id: meta.externalId,
|
|
1993
|
+
is_auto_membership_enabled: false
|
|
1994
|
+
};
|
|
963
1995
|
}
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
}
|
|
967
|
-
function clientSecretFrom(req, form) {
|
|
968
|
-
const header = req.headers.authorization ?? "";
|
|
969
|
-
if (header.startsWith("Basic ")) {
|
|
970
|
-
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
971
|
-
const index = decoded.indexOf(":");
|
|
972
|
-
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1996
|
+
organizationEvent(org) {
|
|
1997
|
+
const meta = this.directory.orgInfo(org);
|
|
1998
|
+
return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
|
|
973
1999
|
}
|
|
974
|
-
|
|
975
|
-
}
|
|
976
|
-
function redirectWithError(res, request2, error, description) {
|
|
977
|
-
const target = new URL(request2.redirectUri);
|
|
978
|
-
target.searchParams.set("error", error);
|
|
979
|
-
target.searchParams.set("error_description", description);
|
|
980
|
-
if (request2.state !== null) target.searchParams.set("state", request2.state);
|
|
981
|
-
redirect(res, target.toString());
|
|
982
|
-
}
|
|
983
|
-
function isHttpUrl(value) {
|
|
984
|
-
try {
|
|
985
|
-
const { protocol } = new URL(value);
|
|
986
|
-
return protocol === "http:" || protocol === "https:";
|
|
987
|
-
} catch {
|
|
988
|
-
return false;
|
|
2000
|
+
roleItem(role) {
|
|
2001
|
+
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
989
2002
|
}
|
|
2003
|
+
permissionItem(permission) {
|
|
2004
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
2005
|
+
}
|
|
2006
|
+
};
|
|
2007
|
+
function paginate(items, query) {
|
|
2008
|
+
const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
|
|
2009
|
+
const token2 = query.get("next_token");
|
|
2010
|
+
const offset = token2 ? Number(Buffer.from(token2, "base64url").toString("utf8")) || 0 : 0;
|
|
2011
|
+
const page = items.slice(offset, offset + size);
|
|
2012
|
+
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
2013
|
+
return { items: page, nextToken: next };
|
|
990
2014
|
}
|
|
991
|
-
function
|
|
992
|
-
return
|
|
2015
|
+
function errors2(code, message) {
|
|
2016
|
+
return { errors: [{ code, message }] };
|
|
993
2017
|
}
|
|
994
|
-
function
|
|
995
|
-
|
|
996
|
-
const right = Buffer.from(b);
|
|
997
|
-
return left.length === right.length && timingSafeEqual(left, right);
|
|
2018
|
+
function notFound(code, message) {
|
|
2019
|
+
return [404, errors2(code, message)];
|
|
998
2020
|
}
|
|
999
|
-
function
|
|
1000
|
-
|
|
1001
|
-
res.end();
|
|
2021
|
+
function str(value) {
|
|
2022
|
+
return typeof value === "string" ? value : null;
|
|
1002
2023
|
}
|
|
1003
|
-
function
|
|
1004
|
-
|
|
1005
|
-
"content-type": "text/html; charset=utf-8",
|
|
1006
|
-
"cache-control": "no-store",
|
|
1007
|
-
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
1008
|
-
});
|
|
1009
|
-
res.end(html);
|
|
2024
|
+
function strings(value) {
|
|
2025
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
1010
2026
|
}
|
|
1011
|
-
function
|
|
2027
|
+
function sendJson3(res, status, body) {
|
|
1012
2028
|
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1013
2029
|
res.end(JSON.stringify(body));
|
|
1014
2030
|
}
|
|
@@ -1094,7 +2110,7 @@ function validate(rule) {
|
|
|
1094
2110
|
}
|
|
1095
2111
|
|
|
1096
2112
|
// src/webhooks.ts
|
|
1097
|
-
import { randomBytes as
|
|
2113
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
1098
2114
|
var WEBHOOK_EVENT_TYPES = [
|
|
1099
2115
|
"user.created",
|
|
1100
2116
|
"user.updated",
|
|
@@ -1127,9 +2143,9 @@ var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
|
|
|
1127
2143
|
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
1128
2144
|
var MAX_DUPLICATES = 10;
|
|
1129
2145
|
var WebhookDispatcher = class {
|
|
1130
|
-
constructor(testkit,
|
|
2146
|
+
constructor(testkit, seed2, endpoints = [], options = {}) {
|
|
1131
2147
|
this.testkit = testkit;
|
|
1132
|
-
this.seed =
|
|
2148
|
+
this.seed = seed2;
|
|
1133
2149
|
this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
1134
2150
|
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1135
2151
|
for (const endpoint of endpoints) this.addEndpoint(endpoint);
|
|
@@ -1143,6 +2159,8 @@ var WebhookDispatcher = class {
|
|
|
1143
2159
|
nextEndpoint = 1;
|
|
1144
2160
|
retryDelaysMs;
|
|
1145
2161
|
timeoutMs;
|
|
2162
|
+
/** Set by the server to record coverage. */
|
|
2163
|
+
observe = () => void 0;
|
|
1146
2164
|
addEndpoint(input) {
|
|
1147
2165
|
if (!isHttpUrl2(input.url)) {
|
|
1148
2166
|
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
@@ -1154,6 +2172,14 @@ var WebhookDispatcher = class {
|
|
|
1154
2172
|
this.endpoints.push(endpoint);
|
|
1155
2173
|
return { ...endpoint };
|
|
1156
2174
|
}
|
|
2175
|
+
/** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
|
|
2176
|
+
replaceSeededEndpoints(endpoints) {
|
|
2177
|
+
const seeded = new Set(this.seededEndpoints.map((e) => e.id));
|
|
2178
|
+
this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
|
|
2179
|
+
const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
|
|
2180
|
+
const ids = new Set(added.map((e) => e.id));
|
|
2181
|
+
this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
|
|
2182
|
+
}
|
|
1157
2183
|
removeEndpoint(id) {
|
|
1158
2184
|
const before = this.endpoints.length;
|
|
1159
2185
|
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
@@ -1177,7 +2203,7 @@ var WebhookDispatcher = class {
|
|
|
1177
2203
|
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1178
2204
|
const event = {
|
|
1179
2205
|
data: options.data ?? this.buildData(options),
|
|
1180
|
-
event_id: `event_${
|
|
2206
|
+
event_id: `event_${randomBytes4(16).toString("hex")}`,
|
|
1181
2207
|
event_timestamp: timestamp,
|
|
1182
2208
|
source: options.source ?? "admin",
|
|
1183
2209
|
timestamp,
|
|
@@ -1204,16 +2230,23 @@ var WebhookDispatcher = class {
|
|
|
1204
2230
|
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
1205
2231
|
);
|
|
1206
2232
|
}
|
|
2233
|
+
if (copies > 1) this.observe("webhook.duplicate");
|
|
2234
|
+
if (options.invalid === "stale") this.observe("webhook.stale");
|
|
2235
|
+
else if (options.invalid) this.observe("webhook.forged");
|
|
1207
2236
|
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
1208
2237
|
const signed = await this.testkit.signPayload(
|
|
1209
2238
|
event,
|
|
1210
2239
|
options.invalid === "stale" ? void 0 : options.invalid
|
|
1211
2240
|
);
|
|
1212
2241
|
const jobs = targets.flatMap((target) => {
|
|
1213
|
-
const webhookId = `wh_${
|
|
2242
|
+
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
1214
2243
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1215
2244
|
});
|
|
1216
|
-
|
|
2245
|
+
const deliveries = await Promise.all(jobs);
|
|
2246
|
+
if (!options.invalid) {
|
|
2247
|
+
for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
|
|
2248
|
+
}
|
|
2249
|
+
return deliveries;
|
|
1217
2250
|
}
|
|
1218
2251
|
async deliver(url, webhookId, body, event, copy) {
|
|
1219
2252
|
const delivery = {
|
|
@@ -1291,6 +2324,13 @@ var WebhookDispatcher = class {
|
|
|
1291
2324
|
);
|
|
1292
2325
|
}
|
|
1293
2326
|
}
|
|
2327
|
+
emit(type, data, source = "api") {
|
|
2328
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2329
|
+
void this.send({ type, data, source }).catch(() => void 0);
|
|
2330
|
+
}
|
|
2331
|
+
userEventData(user) {
|
|
2332
|
+
return this.userPayload(user);
|
|
2333
|
+
}
|
|
1294
2334
|
emitForUser(type, user) {
|
|
1295
2335
|
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1296
2336
|
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
@@ -1355,7 +2395,511 @@ function isHttpUrl2(value) {
|
|
|
1355
2395
|
}
|
|
1356
2396
|
}
|
|
1357
2397
|
function sleep(ms) {
|
|
1358
|
-
return new Promise((
|
|
2398
|
+
return new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
2399
|
+
}
|
|
2400
|
+
|
|
2401
|
+
// src/activity.ts
|
|
2402
|
+
var LIMIT = 200;
|
|
2403
|
+
var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
|
|
2404
|
+
var ActivityLog = class {
|
|
2405
|
+
requestLog = [];
|
|
2406
|
+
tokenLog = [];
|
|
2407
|
+
request(entry) {
|
|
2408
|
+
const query = new URLSearchParams(entry.query);
|
|
2409
|
+
for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
|
|
2410
|
+
const search = query.toString();
|
|
2411
|
+
push(this.requestLog, {
|
|
2412
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2413
|
+
method: entry.method,
|
|
2414
|
+
path: search ? `${entry.path}?${search}` : entry.path,
|
|
2415
|
+
status: entry.status,
|
|
2416
|
+
durationMs: entry.durationMs,
|
|
2417
|
+
injected: entry.injected
|
|
2418
|
+
});
|
|
2419
|
+
}
|
|
2420
|
+
token(kind, claims, invalid2, token2) {
|
|
2421
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
2422
|
+
push(this.tokenLog, {
|
|
2423
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2424
|
+
kind,
|
|
2425
|
+
subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
|
|
2426
|
+
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
2427
|
+
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
2428
|
+
roles,
|
|
2429
|
+
invalid: invalid2 ?? null,
|
|
2430
|
+
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
2431
|
+
claims,
|
|
2432
|
+
token: token2
|
|
2433
|
+
});
|
|
2434
|
+
}
|
|
2435
|
+
requests() {
|
|
2436
|
+
return [...this.requestLog];
|
|
2437
|
+
}
|
|
2438
|
+
tokens() {
|
|
2439
|
+
return [...this.tokenLog];
|
|
2440
|
+
}
|
|
2441
|
+
reset() {
|
|
2442
|
+
this.requestLog = [];
|
|
2443
|
+
this.tokenLog = [];
|
|
2444
|
+
}
|
|
2445
|
+
};
|
|
2446
|
+
function push(list2, entry) {
|
|
2447
|
+
list2.push(entry);
|
|
2448
|
+
if (list2.length > LIMIT) list2.splice(0, list2.length - LIMIT);
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
// src/coverage.ts
|
|
2452
|
+
import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
2453
|
+
import { join as join2, resolve as resolve2 } from "path";
|
|
2454
|
+
var COVERAGE_GROUPS = [
|
|
2455
|
+
{
|
|
2456
|
+
name: "Identity",
|
|
2457
|
+
items: [
|
|
2458
|
+
{ id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
|
|
2459
|
+
{ id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
|
|
2460
|
+
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
2461
|
+
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
2462
|
+
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
2463
|
+
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
|
|
2464
|
+
]
|
|
2465
|
+
},
|
|
2466
|
+
{
|
|
2467
|
+
name: "Organizations",
|
|
2468
|
+
items: [
|
|
2469
|
+
{ id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
|
|
2470
|
+
{ id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
|
|
2471
|
+
{ id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
|
|
2472
|
+
{ id: "organization.non-member", label: "Non-member refused", hint: "Ask for a token or sign-in for an organization the user does not belong to." },
|
|
2473
|
+
{ id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
|
|
2474
|
+
]
|
|
2475
|
+
},
|
|
2476
|
+
{
|
|
2477
|
+
name: "Permissions",
|
|
2478
|
+
items: [
|
|
2479
|
+
{ id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
|
|
2480
|
+
{ id: "permission.different-sets", label: "Different permissions in one organization", hint: "Mint tokens for two users in one organization with different permissions, such as an admin and a viewer." },
|
|
2481
|
+
{ id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
|
|
2482
|
+
{ id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
|
|
2483
|
+
{ id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
|
|
2484
|
+
]
|
|
2485
|
+
},
|
|
2486
|
+
{
|
|
2487
|
+
name: "Token validation",
|
|
2488
|
+
items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
|
|
2489
|
+
(kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
|
|
2490
|
+
)
|
|
2491
|
+
},
|
|
2492
|
+
{
|
|
2493
|
+
name: "Sessions",
|
|
2494
|
+
items: [
|
|
2495
|
+
{ id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
|
|
2496
|
+
{ id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
|
|
2497
|
+
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
2498
|
+
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
2499
|
+
{ id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
|
|
2500
|
+
]
|
|
2501
|
+
},
|
|
2502
|
+
{
|
|
2503
|
+
name: "Machine-to-machine",
|
|
2504
|
+
items: [
|
|
2505
|
+
{ id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
|
|
2506
|
+
{ id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
|
|
2507
|
+
{ id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
|
|
2508
|
+
{ id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
|
|
2509
|
+
]
|
|
2510
|
+
},
|
|
2511
|
+
{
|
|
2512
|
+
name: "Kinde APIs",
|
|
2513
|
+
items: [
|
|
2514
|
+
{ id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
|
|
2515
|
+
{ id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
|
|
2516
|
+
{ id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
|
|
2517
|
+
{ id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
|
|
2518
|
+
]
|
|
2519
|
+
},
|
|
2520
|
+
{
|
|
2521
|
+
name: "Webhooks",
|
|
2522
|
+
items: [
|
|
2523
|
+
{ id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
|
|
2524
|
+
{ id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
|
|
2525
|
+
{ id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
|
|
2526
|
+
{ id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
|
|
2527
|
+
{ id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
|
|
2528
|
+
]
|
|
2529
|
+
},
|
|
2530
|
+
{
|
|
2531
|
+
name: "Outages",
|
|
2532
|
+
items: [
|
|
2533
|
+
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
2534
|
+
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
2535
|
+
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
2536
|
+
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
|
|
2537
|
+
]
|
|
2538
|
+
}
|
|
2539
|
+
];
|
|
2540
|
+
var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
|
|
2541
|
+
function tokenLabel(kind) {
|
|
2542
|
+
return {
|
|
2543
|
+
expired: "Expired token",
|
|
2544
|
+
"future-iat": "Token issued in the future",
|
|
2545
|
+
"wrong-issuer": "Wrong issuer",
|
|
2546
|
+
"wrong-audience": "Wrong audience",
|
|
2547
|
+
"bad-signature": "Tampered signature",
|
|
2548
|
+
"unknown-key": "Unknown signing key",
|
|
2549
|
+
unsigned: "Unsigned token",
|
|
2550
|
+
"missing-subject": "No subject"
|
|
2551
|
+
}[kind];
|
|
2552
|
+
}
|
|
2553
|
+
var CoverageRecorder = class {
|
|
2554
|
+
hits = /* @__PURE__ */ new Map();
|
|
2555
|
+
userOrganizations = /* @__PURE__ */ new Map();
|
|
2556
|
+
organizationUsers = /* @__PURE__ */ new Map();
|
|
2557
|
+
organizationPermissionSets = /* @__PURE__ */ new Map();
|
|
2558
|
+
hit(id) {
|
|
2559
|
+
if (!ALL_IDS.has(id)) return;
|
|
2560
|
+
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
2561
|
+
}
|
|
2562
|
+
/** Called for every access token the testkit signs. */
|
|
2563
|
+
observeAccessToken(payload, invalid2) {
|
|
2564
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
2565
|
+
this.hit("m2m.token");
|
|
2566
|
+
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
2567
|
+
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
2568
|
+
if (invalid2) this.hit("m2m.invalid");
|
|
2569
|
+
return;
|
|
2570
|
+
}
|
|
2571
|
+
if (invalid2 === "missing-organization") return this.hit("organization.missing");
|
|
2572
|
+
if (invalid2 === "missing-permissions") return this.hit("permission.none");
|
|
2573
|
+
if (invalid2) return this.hit(`token.${invalid2}`);
|
|
2574
|
+
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
2575
|
+
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
2576
|
+
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
2577
|
+
if (subject) this.hit("identity.user");
|
|
2578
|
+
if (!organization) this.hit("identity.no-organization");
|
|
2579
|
+
if (permissions.length > 0) this.hit("permission.granted");
|
|
2580
|
+
else this.hit("permission.none");
|
|
2581
|
+
if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
|
|
2582
|
+
if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
|
|
2583
|
+
if (!organization) return;
|
|
2584
|
+
this.hit("organization.token");
|
|
2585
|
+
if (subject) {
|
|
2586
|
+
const organizations = add(this.userOrganizations, subject, organization);
|
|
2587
|
+
if (organizations.size > 1) this.hit("organization.two-for-one-user");
|
|
2588
|
+
add(this.organizationUsers, organization, subject);
|
|
2589
|
+
const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
|
|
2590
|
+
const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
|
|
2591
|
+
if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
|
|
2592
|
+
}
|
|
2593
|
+
const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
|
|
2594
|
+
if (sets.size > 1) this.hit("permission.different-sets");
|
|
2595
|
+
}
|
|
2596
|
+
report() {
|
|
2597
|
+
return buildReport(Object.fromEntries(this.hits));
|
|
2598
|
+
}
|
|
2599
|
+
snapshot() {
|
|
2600
|
+
return { version: 1, hits: Object.fromEntries(this.hits) };
|
|
2601
|
+
}
|
|
2602
|
+
reset() {
|
|
2603
|
+
this.hits.clear();
|
|
2604
|
+
this.userOrganizations.clear();
|
|
2605
|
+
this.organizationUsers.clear();
|
|
2606
|
+
this.organizationPermissionSets.clear();
|
|
2607
|
+
}
|
|
2608
|
+
/** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
|
|
2609
|
+
write(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2610
|
+
const folder = resolve2(directory);
|
|
2611
|
+
mkdirSync2(folder, { recursive: true });
|
|
2612
|
+
const file = join2(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
|
|
2613
|
+
writeFileSync2(file, `${JSON.stringify(this.snapshot())}
|
|
2614
|
+
`);
|
|
2615
|
+
return file;
|
|
2616
|
+
}
|
|
2617
|
+
};
|
|
2618
|
+
var DEFAULT_COVERAGE_DIRECTORY = join2(".kinde-testkit", "coverage");
|
|
2619
|
+
function add(map, key, value) {
|
|
2620
|
+
let set2 = map.get(key);
|
|
2621
|
+
if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
|
|
2622
|
+
set2.add(value);
|
|
2623
|
+
return set2;
|
|
2624
|
+
}
|
|
2625
|
+
function buildReport(hits) {
|
|
2626
|
+
const groups = COVERAGE_GROUPS.map((group) => {
|
|
2627
|
+
const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
|
|
2628
|
+
return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
|
|
2629
|
+
});
|
|
2630
|
+
return {
|
|
2631
|
+
covered: groups.reduce((sum, g) => sum + g.covered, 0),
|
|
2632
|
+
total: groups.reduce((sum, g) => sum + g.total, 0),
|
|
2633
|
+
groups
|
|
2634
|
+
};
|
|
2635
|
+
}
|
|
2636
|
+
function mergeSnapshots(snapshots) {
|
|
2637
|
+
const hits = {};
|
|
2638
|
+
for (const snapshot of snapshots) {
|
|
2639
|
+
for (const [id, count2] of Object.entries(snapshot.hits ?? {})) hits[id] = (hits[id] ?? 0) + count2;
|
|
2640
|
+
}
|
|
2641
|
+
return hits;
|
|
2642
|
+
}
|
|
2643
|
+
function readCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2644
|
+
const folder = resolve2(directory);
|
|
2645
|
+
let names = [];
|
|
2646
|
+
try {
|
|
2647
|
+
names = readdirSync(folder).filter((name) => name.endsWith(".json"));
|
|
2648
|
+
} catch {
|
|
2649
|
+
}
|
|
2650
|
+
const snapshots = names.map((name) => JSON.parse(readFileSync2(join2(folder, name), "utf8")));
|
|
2651
|
+
return { files: names.length, report: buildReport(mergeSnapshots(snapshots)) };
|
|
2652
|
+
}
|
|
2653
|
+
function clearCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2654
|
+
rmSync(resolve2(directory), { recursive: true, force: true });
|
|
2655
|
+
}
|
|
2656
|
+
function formatCoverageReport(report, options = {}) {
|
|
2657
|
+
const width = Math.max(...report.groups.map((g) => g.name.length)) + 3;
|
|
2658
|
+
const lines = ["Kinde authentication coverage", ""];
|
|
2659
|
+
for (const group of report.groups) {
|
|
2660
|
+
lines.push(`${group.name.padEnd(width)}${String(group.covered).padStart(2)}/${group.total}`);
|
|
2661
|
+
}
|
|
2662
|
+
lines.push("", `Overall: ${report.covered}/${report.total}`);
|
|
2663
|
+
if (options.missing !== false) {
|
|
2664
|
+
const missing = report.groups.flatMap((g) => g.items.filter((i) => !i.covered).map((i) => ({ group: g.name, ...i })));
|
|
2665
|
+
if (missing.length > 0) {
|
|
2666
|
+
lines.push("", "Not covered:");
|
|
2667
|
+
for (const item of missing) lines.push(` ${item.group}: ${item.label}. ${item.hint}`);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
return lines.join("\n");
|
|
2671
|
+
}
|
|
2672
|
+
|
|
2673
|
+
// src/dashboard.ts
|
|
2674
|
+
var STYLE2 = `
|
|
2675
|
+
:root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--ok:#1d7a46;--bad:#b42318;--soft:#f0f0ec}
|
|
2676
|
+
@media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--ok:#5cc78a;--bad:#f0817a;--soft:#232327}}
|
|
2677
|
+
*{box-sizing:border-box}
|
|
2678
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
2679
|
+
header{position:sticky;top:0;z-index:1;display:flex;flex-wrap:wrap;gap:16px;align-items:center;justify-content:space-between;padding:14px 28px;background:var(--card);border-bottom:1px solid var(--line)}
|
|
2680
|
+
header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
|
|
2681
|
+
header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2682
|
+
nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
|
|
2683
|
+
nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
|
|
2684
|
+
main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
|
|
2685
|
+
section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
|
|
2686
|
+
h2{margin:0 0 4px;font-size:16px;font-weight:600}
|
|
2687
|
+
.sub{margin:0 0 14px;color:var(--muted);font-size:13px}
|
|
2688
|
+
table{width:100%;border-collapse:collapse;font-size:13px}
|
|
2689
|
+
th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
|
|
2690
|
+
td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
|
|
2691
|
+
tr:last-child td{border-bottom:0}
|
|
2692
|
+
code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2693
|
+
.chips{display:flex;flex-wrap:wrap;gap:4px}
|
|
2694
|
+
.chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
|
|
2695
|
+
.ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
|
|
2696
|
+
.empty{color:var(--muted);font-size:13px;margin:0}
|
|
2697
|
+
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
|
|
2698
|
+
label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
|
|
2699
|
+
input,select{height:32px;padding:0 8px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:13px ui-sans-serif,system-ui,sans-serif}
|
|
2700
|
+
input[type=checkbox]{height:auto}
|
|
2701
|
+
button{height:32px;padding:0 12px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:500 13px ui-sans-serif,system-ui,sans-serif;cursor:pointer}
|
|
2702
|
+
button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
|
|
2703
|
+
button:hover{border-color:var(--muted)}
|
|
2704
|
+
details summary{cursor:pointer;color:var(--muted)}
|
|
2705
|
+
pre{margin:8px 0 0;padding:10px;background:var(--soft);border-radius:6px;overflow:auto;max-height:320px;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-all}
|
|
2706
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
|
|
2707
|
+
.group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
|
|
2708
|
+
.group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
|
|
2709
|
+
.notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
|
|
2710
|
+
.split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
|
|
2711
|
+
`;
|
|
2712
|
+
function renderDashboard(data) {
|
|
2713
|
+
const e = escapeHtml;
|
|
2714
|
+
const { seed: seed2 } = data;
|
|
2715
|
+
const orgName = (code) => seed2.organizations.find((o) => o.code === code)?.name ?? code;
|
|
2716
|
+
const userLabel = (id) => seed2.users.find((u) => u.id === id)?.email ?? id;
|
|
2717
|
+
const users = seed2.users.length ? table(
|
|
2718
|
+
["User", "ID", "Organizations", "Sign-ins", "Status"],
|
|
2719
|
+
seed2.users.map((user) => [
|
|
2720
|
+
e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
|
|
2721
|
+
`<code>${e(user.id)}</code>`,
|
|
2722
|
+
chips(seed2.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
|
|
2723
|
+
String(data.signIns(user.id)),
|
|
2724
|
+
data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
|
|
2725
|
+
])
|
|
2726
|
+
) : empty("No users yet. Seed some, or sign in with any email.");
|
|
2727
|
+
const organizations = seed2.organizations.length ? table(
|
|
2728
|
+
["Organization", "Code", "Members"],
|
|
2729
|
+
seed2.organizations.map((org) => [
|
|
2730
|
+
e(org.name),
|
|
2731
|
+
`<code>${e(org.code)}</code>`,
|
|
2732
|
+
String(seed2.memberships.filter((m) => m.organizationCode === org.code).length)
|
|
2733
|
+
])
|
|
2734
|
+
) : empty("No organizations.");
|
|
2735
|
+
const memberships = seed2.memberships.length ? table(
|
|
2736
|
+
["User", "Organization", "Roles", "Permissions in the token"],
|
|
2737
|
+
seed2.memberships.map((m) => [
|
|
2738
|
+
e(userLabel(m.userId)),
|
|
2739
|
+
e(orgName(m.organizationCode)),
|
|
2740
|
+
chips(m.roles),
|
|
2741
|
+
chips(effectivePermissions(seed2, m))
|
|
2742
|
+
])
|
|
2743
|
+
) : empty("No memberships.");
|
|
2744
|
+
const applications = seed2.applications.length ? table(
|
|
2745
|
+
["Client ID", "Organization", "Scopes"],
|
|
2746
|
+
seed2.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
|
|
2747
|
+
) : "";
|
|
2748
|
+
const tokens = data.tokens.length ? table(
|
|
2749
|
+
["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
|
|
2750
|
+
[...data.tokens].reverse().slice(0, 50).map((t) => [
|
|
2751
|
+
time(t.at),
|
|
2752
|
+
t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
|
|
2753
|
+
`<code>${e(t.subject ?? "none")}</code>`,
|
|
2754
|
+
e(t.organization ?? "none"),
|
|
2755
|
+
chips(t.permissions),
|
|
2756
|
+
`<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
|
|
2757
|
+
])
|
|
2758
|
+
) : empty("No tokens issued yet.");
|
|
2759
|
+
const requests = data.requests.length ? table(
|
|
2760
|
+
["Time", "Request", "Status", "Time taken"],
|
|
2761
|
+
[...data.requests].reverse().slice(0, 100).map((r) => [
|
|
2762
|
+
time(r.at),
|
|
2763
|
+
`<code>${e(r.method)} ${e(r.path)}</code>`,
|
|
2764
|
+
`<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
|
|
2765
|
+
`${r.durationMs} ms`
|
|
2766
|
+
])
|
|
2767
|
+
) : empty("No requests yet.");
|
|
2768
|
+
const deliveries = data.deliveries.length ? table(
|
|
2769
|
+
["Event", "Endpoint", "Copy", "Result"],
|
|
2770
|
+
[...data.deliveries].reverse().slice(0, 50).map((d) => [
|
|
2771
|
+
`<code>${e(d.type)}</code>`,
|
|
2772
|
+
`<code>${e(d.url)}</code>`,
|
|
2773
|
+
String(d.copy),
|
|
2774
|
+
d.delivered ? `<span class="ok">Delivered</span>` : `<span class="bad">${e(d.attempts.map((a) => a.status === null ? a.error ?? "error" : String(a.status)).join(", ") || "Not sent")}</span>`
|
|
2775
|
+
])
|
|
2776
|
+
) : empty("No webhooks sent yet.");
|
|
2777
|
+
const endpoints = data.endpoints.length ? `<p class="sub">Endpoints: ${data.endpoints.map((x) => `<code>${e(x.url)}</code>`).join(", ")}</p>` : `<p class="sub">No webhook endpoints. Add one in the seed, with <code>start --webhook</code> or <code>addEndpoint()</code>.</p>`;
|
|
2778
|
+
const webhookForm = data.endpoints.length ? form(
|
|
2779
|
+
"/dashboard/webhooks",
|
|
2780
|
+
`<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
|
|
2781
|
+
<label>User<select name="user"><option value="">First seeded user</option>${seed2.users.map((u) => `<option value="${e(u.id)}">${e(u.email ?? u.id)}</option>`).join("")}</select></label>
|
|
2782
|
+
<label>Variant<select name="invalid"><option value="">Valid</option><option>bad-signature</option><option>unknown-key</option><option>unsigned</option><option>stale</option></select></label>
|
|
2783
|
+
<label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
|
|
2784
|
+
<button class="primary">Send</button>`
|
|
2785
|
+
) : "";
|
|
2786
|
+
const failures = data.failures.length ? table(
|
|
2787
|
+
["Path", "Method", "Effect", "Remaining", "Hits", ""],
|
|
2788
|
+
data.failures.map((f) => [
|
|
2789
|
+
`<code>${e(f.path)}</code>`,
|
|
2790
|
+
e(f.method ?? "any"),
|
|
2791
|
+
e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
|
|
2792
|
+
f.remaining === null ? "Until removed" : String(f.remaining),
|
|
2793
|
+
String(f.hits),
|
|
2794
|
+
form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
|
|
2795
|
+
])
|
|
2796
|
+
) : empty("No failure rules.");
|
|
2797
|
+
const coverage2 = `<div class="grid">${data.coverage.groups.map(
|
|
2798
|
+
(g) => `<div><div class="group"><span>${e(g.name)}</span><span class="${g.covered === g.total ? "ok" : "muted"}">${g.covered}/${g.total}</span></div><ul>${g.items.map((i) => `<li title="${e(i.hint)}"><span class="${i.covered ? "ok" : "muted"}">${i.covered ? "\u2713" : "\u25CB"}</span> ${e(i.label)}</li>`).join("")}</ul></div>`
|
|
2799
|
+
).join("")}</div>`;
|
|
2800
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2801
|
+
${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
|
|
2802
|
+
<title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
|
|
2803
|
+
<header>
|
|
2804
|
+
<div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
|
|
2805
|
+
<nav><a href="#users">Users</a><a href="#tokens">Tokens</a><a href="#requests">Requests</a><a href="#webhooks">Webhooks</a><a href="#failures">Failures</a><a href="#coverage">Coverage</a></nav>
|
|
2806
|
+
<div class="row">
|
|
2807
|
+
<a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
|
|
2808
|
+
${form("/dashboard/reset", `<button>Reset state</button>`)}
|
|
2809
|
+
</div>
|
|
2810
|
+
</header>
|
|
2811
|
+
<main>
|
|
2812
|
+
${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
|
|
2813
|
+
<section id="users"><h2>Users</h2><p class="sub">Seeded users, users created through the Management API, and emails that signed in.</p>${users}</section>
|
|
2814
|
+
<div class="split">
|
|
2815
|
+
<section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
|
|
2816
|
+
<section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
|
|
2817
|
+
</div>
|
|
2818
|
+
${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
|
|
2819
|
+
<section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
|
|
2820
|
+
<section id="requests"><h2>Requests</h2><p class="sub">The latest 100 requests your app and tests made. Codes, secrets and refresh tokens are hidden.</p>${requests}</section>
|
|
2821
|
+
<section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
|
|
2822
|
+
<section id="failures"><h2>Failures</h2><p class="sub">Make an endpoint fail, slow down or hang. Applies to Kinde endpoints, not <code>/testkit</code> or this page.</p>
|
|
2823
|
+
${form(
|
|
2824
|
+
"/dashboard/failures",
|
|
2825
|
+
`<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
|
|
2826
|
+
<label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
|
|
2827
|
+
<label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
|
|
2828
|
+
<label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
|
|
2829
|
+
<label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
|
|
2830
|
+
<label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
|
|
2831
|
+
<button class="primary">Add rule</button>`
|
|
2832
|
+
)}
|
|
2833
|
+
<div style="margin-top:14px">${failures}</div>
|
|
2834
|
+
${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
|
|
2835
|
+
</section>
|
|
2836
|
+
<section id="coverage"><h2>Coverage: ${data.coverage.covered}/${data.coverage.total}</h2><p class="sub">Authentication scenarios the testkit produced since it started or was reset. Hover an item to see how to cover it.</p>${coverage2}
|
|
2837
|
+
<div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
|
|
2838
|
+
</main></body></html>`;
|
|
2839
|
+
}
|
|
2840
|
+
function table(headers, rows) {
|
|
2841
|
+
return `<table><thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
|
|
2842
|
+
}
|
|
2843
|
+
function chips(values) {
|
|
2844
|
+
if (values.length === 0) return `<span class="muted">none</span>`;
|
|
2845
|
+
return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
|
|
2846
|
+
}
|
|
2847
|
+
function empty(text) {
|
|
2848
|
+
return `<p class="empty">${escapeHtml(text)}</p>`;
|
|
2849
|
+
}
|
|
2850
|
+
function time(iso) {
|
|
2851
|
+
return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
|
|
2852
|
+
}
|
|
2853
|
+
function form(action, body) {
|
|
2854
|
+
return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
// src/seed-file.ts
|
|
2858
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
2859
|
+
import { extname, resolve as resolve3 } from "path";
|
|
2860
|
+
import { pathToFileURL } from "url";
|
|
2861
|
+
import { parse as parseYaml } from "yaml";
|
|
2862
|
+
var DEFAULT_SEED_FILES = [
|
|
2863
|
+
"kinde-testkit.json",
|
|
2864
|
+
"kinde-testkit.yaml",
|
|
2865
|
+
"kinde-testkit.yml",
|
|
2866
|
+
"kinde-testkit.ts",
|
|
2867
|
+
"kinde-testkit.mts",
|
|
2868
|
+
"kinde-testkit.js",
|
|
2869
|
+
"kinde-testkit.mjs"
|
|
2870
|
+
];
|
|
2871
|
+
function findSeedFile(directory = ".") {
|
|
2872
|
+
return DEFAULT_SEED_FILES.map((name) => resolve3(directory, name)).find((path) => existsSync2(path));
|
|
2873
|
+
}
|
|
2874
|
+
async function loadSeedFile(path) {
|
|
2875
|
+
const file = resolve3(path);
|
|
2876
|
+
const extension = extname(file).toLowerCase();
|
|
2877
|
+
let value;
|
|
2878
|
+
try {
|
|
2879
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
2880
|
+
value = parseYaml(readFileSync3(file, "utf8"));
|
|
2881
|
+
} else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
|
|
2882
|
+
const module = await import(pathToFileURL(file).href);
|
|
2883
|
+
value = module.seed ?? module.default;
|
|
2884
|
+
if (value && typeof value === "object" && "default" in value && !("users" in value)) {
|
|
2885
|
+
value = value.default;
|
|
2886
|
+
}
|
|
2887
|
+
} else {
|
|
2888
|
+
value = JSON.parse(readFileSync3(file, "utf8"));
|
|
2889
|
+
}
|
|
2890
|
+
} catch (error) {
|
|
2891
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2892
|
+
const details = [message];
|
|
2893
|
+
if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message)) {
|
|
2894
|
+
details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
|
|
2895
|
+
}
|
|
2896
|
+
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
|
|
2897
|
+
}
|
|
2898
|
+
if (value === null || value === void 0) value = {};
|
|
2899
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
2900
|
+
throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
|
|
2901
|
+
}
|
|
2902
|
+
return value;
|
|
1359
2903
|
}
|
|
1360
2904
|
|
|
1361
2905
|
// src/server.ts
|
|
@@ -1370,120 +2914,301 @@ async function startKindeTestkit(options = {}) {
|
|
|
1370
2914
|
`kinde-testkit will not listen on ${host}. It signs tokens for any identity, so it stays on localhost unless you pass --allow-public (allowPublic: true in code).`
|
|
1371
2915
|
);
|
|
1372
2916
|
}
|
|
1373
|
-
const
|
|
2917
|
+
const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
|
|
2918
|
+
const seed2 = resolveSeed(seedInput);
|
|
1374
2919
|
const failures = new FailureInjector();
|
|
1375
2920
|
let ready;
|
|
1376
|
-
const testkitReady = new Promise((
|
|
1377
|
-
const
|
|
2921
|
+
const testkitReady = new Promise((resolve5) => ready = resolve5);
|
|
2922
|
+
const listener = (req, res) => {
|
|
1378
2923
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1379
|
-
}
|
|
1380
|
-
|
|
2924
|
+
};
|
|
2925
|
+
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
2926
|
+
const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
|
|
2927
|
+
await new Promise((resolve5, reject) => {
|
|
1381
2928
|
server.once("error", reject);
|
|
1382
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
2929
|
+
server.listen(options.port ?? 4400, host, () => resolve5());
|
|
1383
2930
|
});
|
|
1384
2931
|
const { port } = server.address();
|
|
1385
|
-
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1386
|
-
const url =
|
|
2932
|
+
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
2933
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1387
2934
|
const testkit = await KindeTestkit.create({
|
|
1388
|
-
issuer: options.issuer ??
|
|
1389
|
-
audience: options.audience ??
|
|
1390
|
-
clientId: options.clientId ??
|
|
2935
|
+
issuer: options.issuer ?? seedInput.issuer ?? url,
|
|
2936
|
+
audience: options.audience ?? seedInput.audience,
|
|
2937
|
+
clientId: options.clientId ?? seedInput.clientId
|
|
2938
|
+
});
|
|
2939
|
+
const coverage2 = new CoverageRecorder();
|
|
2940
|
+
const activity = new ActivityLog();
|
|
2941
|
+
testkit.observe({
|
|
2942
|
+
accessToken(payload, invalid2, token2) {
|
|
2943
|
+
coverage2.observeAccessToken(payload, invalid2);
|
|
2944
|
+
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
2945
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid2, token2);
|
|
2946
|
+
},
|
|
2947
|
+
idToken(payload, token2) {
|
|
2948
|
+
coverage2.hit("identity.id-token");
|
|
2949
|
+
activity.token("id", payload, void 0, token2);
|
|
2950
|
+
},
|
|
2951
|
+
anonymous() {
|
|
2952
|
+
coverage2.hit("identity.anonymous");
|
|
2953
|
+
}
|
|
1391
2954
|
});
|
|
1392
|
-
const
|
|
1393
|
-
const
|
|
2955
|
+
const observe = (id) => coverage2.hit(id);
|
|
2956
|
+
const directory = new Directory(seed2);
|
|
2957
|
+
const webhooks = new WebhookDispatcher(testkit, seed2, seed2.webhooks, options.webhooks);
|
|
2958
|
+
webhooks.observe = observe;
|
|
2959
|
+
const auth = new AuthorizationServer(testkit, seed2, (type, user) => webhooks.emitForUser(type, user), directory, observe);
|
|
2960
|
+
const management = new ManagementApi(testkit, directory, webhooks);
|
|
2961
|
+
const account = new AccountApi(testkit, directory);
|
|
1394
2962
|
const reset2 = () => {
|
|
1395
2963
|
auth.reset();
|
|
1396
2964
|
failures.clear();
|
|
1397
2965
|
webhooks.reset();
|
|
2966
|
+
directory.restore();
|
|
2967
|
+
};
|
|
2968
|
+
const loadSeed = (input) => {
|
|
2969
|
+
const next = resolveSeed(input);
|
|
2970
|
+
directory.load(next);
|
|
2971
|
+
webhooks.replaceSeededEndpoints(next.webhooks);
|
|
2972
|
+
reset2();
|
|
1398
2973
|
};
|
|
1399
|
-
|
|
2974
|
+
let closed = false;
|
|
2975
|
+
const close = () => new Promise((resolve5, reject) => {
|
|
2976
|
+
if (closed) return resolve5();
|
|
2977
|
+
closed = true;
|
|
2978
|
+
if (options.coverage) {
|
|
2979
|
+
coverage2.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
|
|
2980
|
+
}
|
|
2981
|
+
server.closeAllConnections();
|
|
2982
|
+
server.close((error) => error ? reject(error) : resolve5());
|
|
2983
|
+
});
|
|
2984
|
+
ready({ testkit, auth, seed: seed2, failures, webhooks, management, account, reset: reset2, coverage: coverage2, activity, directory, loadSeed, close });
|
|
1400
2985
|
return {
|
|
1401
2986
|
url,
|
|
1402
2987
|
issuer: testkit.issuer,
|
|
1403
2988
|
discoveryUrl: `${url}/.well-known/openid-configuration`,
|
|
1404
2989
|
jwksUri: `${url}/.well-known/jwks`,
|
|
1405
2990
|
testkit,
|
|
1406
|
-
seed,
|
|
2991
|
+
seed: seed2,
|
|
1407
2992
|
failures,
|
|
1408
2993
|
webhooks,
|
|
2994
|
+
directory,
|
|
2995
|
+
certificatePath: certificate?.certPath ?? null,
|
|
2996
|
+
coverage: coverage2,
|
|
2997
|
+
activity,
|
|
2998
|
+
loadSeed,
|
|
1409
2999
|
reset: reset2,
|
|
1410
|
-
close
|
|
1411
|
-
server.closeAllConnections();
|
|
1412
|
-
server.close((error) => error ? reject(error) : resolve2());
|
|
1413
|
-
})
|
|
3000
|
+
close
|
|
1414
3001
|
};
|
|
1415
3002
|
}
|
|
1416
3003
|
async function handle(req, res, context) {
|
|
1417
|
-
const { testkit, auth, seed, failures, webhooks } = context;
|
|
3004
|
+
const { testkit, auth, seed: seed2, failures, webhooks, coverage: coverage2 } = context;
|
|
1418
3005
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1419
3006
|
const { pathname } = url;
|
|
1420
3007
|
const method = req.method ?? "GET";
|
|
1421
|
-
|
|
3008
|
+
const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
|
|
3009
|
+
let injected = false;
|
|
3010
|
+
if (!internal && pathname !== "/favicon.ico") {
|
|
3011
|
+
const started = Date.now();
|
|
3012
|
+
res.once("close", () => {
|
|
3013
|
+
context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
|
|
3014
|
+
});
|
|
3015
|
+
}
|
|
3016
|
+
if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
|
|
3017
|
+
if (!internal) {
|
|
1422
3018
|
const failure = failures.take(method, pathname);
|
|
1423
3019
|
if (failure) {
|
|
3020
|
+
injected = true;
|
|
3021
|
+
if (failure.hang) coverage2.hit("outage.timeout");
|
|
3022
|
+
else if (failure.status === 429) coverage2.hit("outage.rate-limit");
|
|
3023
|
+
else if (failure.status !== null) coverage2.hit("outage.error");
|
|
3024
|
+
if (failure.delayMs > 0) coverage2.hit("outage.slow");
|
|
1424
3025
|
if (failure.hang) return;
|
|
1425
|
-
if (failure.delayMs > 0) await new Promise((
|
|
3026
|
+
if (failure.delayMs > 0) await new Promise((resolve5) => setTimeout(resolve5, failure.delayMs));
|
|
1426
3027
|
if (failure.status !== null) {
|
|
1427
3028
|
const headers = {};
|
|
1428
3029
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1429
|
-
return
|
|
3030
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1430
3031
|
}
|
|
1431
3032
|
}
|
|
1432
3033
|
}
|
|
1433
3034
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
3035
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) {
|
|
3036
|
+
if (res.statusCode === 401 || res.statusCode === 403) coverage2.hit("api.management-denied");
|
|
3037
|
+
else if (res.statusCode < 400) coverage2.hit(method === "GET" ? "api.management-read" : "api.management-write");
|
|
3038
|
+
return;
|
|
3039
|
+
}
|
|
3040
|
+
if (await context.account.handle(req, res, url)) {
|
|
3041
|
+
if (res.statusCode < 400) coverage2.hit("api.account");
|
|
3042
|
+
return;
|
|
3043
|
+
}
|
|
3044
|
+
if (method === "GET" && pathname === "/testkit/portal") {
|
|
3045
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
3046
|
+
res.end(
|
|
3047
|
+
`<!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>`
|
|
3048
|
+
);
|
|
3049
|
+
return;
|
|
3050
|
+
}
|
|
1434
3051
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1435
|
-
return
|
|
3052
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1436
3053
|
}
|
|
1437
3054
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1438
|
-
return
|
|
3055
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1439
3056
|
}
|
|
1440
3057
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1441
|
-
return
|
|
3058
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1442
3059
|
}
|
|
1443
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
3060
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed2.users);
|
|
1444
3061
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1445
|
-
return
|
|
3062
|
+
return sendJson4(res, 200, seed2.organizations);
|
|
1446
3063
|
}
|
|
1447
3064
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1448
|
-
return
|
|
3065
|
+
return sendJson4(res, 200, seed2.memberships);
|
|
1449
3066
|
}
|
|
1450
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
3067
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1451
3068
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1452
|
-
return
|
|
3069
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1453
3070
|
}
|
|
1454
3071
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1455
3072
|
failures.clear();
|
|
1456
|
-
return
|
|
3073
|
+
return sendJson4(res, 200, { ok: true });
|
|
1457
3074
|
}
|
|
1458
3075
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1459
3076
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1460
|
-
return
|
|
3077
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1461
3078
|
}
|
|
1462
3079
|
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1463
|
-
return
|
|
3080
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
1464
3081
|
}
|
|
1465
3082
|
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1466
|
-
return
|
|
3083
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1467
3084
|
}
|
|
1468
|
-
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return
|
|
1469
|
-
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return
|
|
3085
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
|
|
3086
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
|
|
1470
3087
|
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1471
|
-
return
|
|
3088
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1472
3089
|
}
|
|
1473
3090
|
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1474
3091
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1475
|
-
return
|
|
3092
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1476
3093
|
}
|
|
1477
3094
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1478
3095
|
context.reset();
|
|
1479
|
-
return
|
|
3096
|
+
return sendJson4(res, 200, { ok: true });
|
|
1480
3097
|
}
|
|
1481
3098
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1482
3099
|
const body = await readJson(req);
|
|
1483
|
-
|
|
1484
|
-
|
|
3100
|
+
let accessToken;
|
|
3101
|
+
try {
|
|
3102
|
+
accessToken = await issueToken(testkit, seed2, body);
|
|
3103
|
+
} catch (error) {
|
|
3104
|
+
if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage2.hit("organization.non-member");
|
|
3105
|
+
throw error;
|
|
3106
|
+
}
|
|
3107
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
3108
|
+
}
|
|
3109
|
+
if (method === "GET" && pathname === "/testkit/coverage") {
|
|
3110
|
+
return sendJson4(res, 200, { report: coverage2.report(), snapshot: coverage2.snapshot() });
|
|
3111
|
+
}
|
|
3112
|
+
if (method === "DELETE" && pathname === "/testkit/coverage") {
|
|
3113
|
+
coverage2.reset();
|
|
3114
|
+
return sendJson4(res, 200, { ok: true });
|
|
3115
|
+
}
|
|
3116
|
+
if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
|
|
3117
|
+
if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
|
|
3118
|
+
if (method === "POST" && pathname === "/testkit/seed") {
|
|
3119
|
+
const body = await readJson(req);
|
|
3120
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
3121
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
3122
|
+
}
|
|
3123
|
+
context.loadSeed(body);
|
|
3124
|
+
return sendJson4(res, 200, {
|
|
3125
|
+
ok: true,
|
|
3126
|
+
users: seed2.users.length,
|
|
3127
|
+
organizations: seed2.organizations.length,
|
|
3128
|
+
memberships: seed2.memberships.length
|
|
3129
|
+
});
|
|
3130
|
+
}
|
|
3131
|
+
if (method === "POST" && pathname === "/testkit/stop") {
|
|
3132
|
+
sendJson4(res, 200, { ok: true });
|
|
3133
|
+
res.once("finish", () => void context.close().catch(() => void 0));
|
|
3134
|
+
return;
|
|
3135
|
+
}
|
|
3136
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3137
|
+
}
|
|
3138
|
+
async function dashboard(req, res, url, context) {
|
|
3139
|
+
const method = req.method ?? "GET";
|
|
3140
|
+
const { pathname } = url;
|
|
3141
|
+
if (method === "GET" && pathname === "/dashboard") {
|
|
3142
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
3143
|
+
res.end(
|
|
3144
|
+
renderDashboard({
|
|
3145
|
+
issuer: context.testkit.issuer,
|
|
3146
|
+
seed: context.seed,
|
|
3147
|
+
suspended: (id) => context.directory.isSuspended(id),
|
|
3148
|
+
signIns: (id) => {
|
|
3149
|
+
const user = context.directory.user(id);
|
|
3150
|
+
return user ? context.directory.meta(user).totalSignIns : 0;
|
|
3151
|
+
},
|
|
3152
|
+
tokens: context.activity.tokens(),
|
|
3153
|
+
requests: context.activity.requests(),
|
|
3154
|
+
deliveries: context.webhooks.deliveries(),
|
|
3155
|
+
endpoints: context.webhooks.listEndpoints(),
|
|
3156
|
+
failures: context.failures.list(),
|
|
3157
|
+
coverage: context.coverage.report(),
|
|
3158
|
+
webhookTypes: WEBHOOK_EVENT_TYPES,
|
|
3159
|
+
live: url.searchParams.has("live"),
|
|
3160
|
+
notice: url.searchParams.get("notice")
|
|
3161
|
+
})
|
|
3162
|
+
);
|
|
3163
|
+
return;
|
|
3164
|
+
}
|
|
3165
|
+
if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3166
|
+
const origin = req.headers.origin;
|
|
3167
|
+
if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
|
|
3168
|
+
return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
|
|
3169
|
+
}
|
|
3170
|
+
const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
|
|
3171
|
+
let notice = "Done.";
|
|
3172
|
+
try {
|
|
3173
|
+
if (pathname === "/dashboard/reset") {
|
|
3174
|
+
context.reset();
|
|
3175
|
+
notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
|
|
3176
|
+
} else if (pathname === "/dashboard/coverage/reset") {
|
|
3177
|
+
context.coverage.reset();
|
|
3178
|
+
notice = "Cleared coverage.";
|
|
3179
|
+
} else if (pathname === "/dashboard/failures/clear") {
|
|
3180
|
+
context.failures.clear();
|
|
3181
|
+
notice = "Removed every failure rule.";
|
|
3182
|
+
} else if (pathname === "/dashboard/failures") {
|
|
3183
|
+
const rule = { path: form2.path ?? "" };
|
|
3184
|
+
if (form2.method) rule.method = form2.method;
|
|
3185
|
+
if (form2.status) rule.status = Number(form2.status);
|
|
3186
|
+
if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
|
|
3187
|
+
if (form2.times) rule.times = Number(form2.times);
|
|
3188
|
+
if (form2.hang) rule.hang = true;
|
|
3189
|
+
const added = context.failures.add(rule);
|
|
3190
|
+
notice = `Added ${added.id} for ${added.path}.`;
|
|
3191
|
+
} else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
|
|
3192
|
+
const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
|
|
3193
|
+
notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
|
|
3194
|
+
} else if (pathname === "/dashboard/webhooks") {
|
|
3195
|
+
const deliveries = await context.webhooks.send({
|
|
3196
|
+
type: form2.type ?? "",
|
|
3197
|
+
user: form2.user || void 0,
|
|
3198
|
+
invalid: form2.invalid || void 0,
|
|
3199
|
+
duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
|
|
3200
|
+
});
|
|
3201
|
+
const delivered = deliveries.filter((d) => d.delivered).length;
|
|
3202
|
+
notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
|
|
3203
|
+
} else {
|
|
3204
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
|
|
3205
|
+
}
|
|
3206
|
+
} catch (error) {
|
|
3207
|
+
notice = error.message.replace(/\s+/g, " ").trim();
|
|
1485
3208
|
}
|
|
1486
|
-
|
|
3209
|
+
const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
|
|
3210
|
+
res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
|
|
3211
|
+
res.end();
|
|
1487
3212
|
}
|
|
1488
3213
|
function discovery(testkit) {
|
|
1489
3214
|
const base = testkit.issuer;
|
|
@@ -1505,7 +3230,7 @@ function discovery(testkit) {
|
|
|
1505
3230
|
claims_supported: ["aud", "exp", "iat", "iss", "sub", "org_code", "permissions", "roles", "scp"]
|
|
1506
3231
|
};
|
|
1507
3232
|
}
|
|
1508
|
-
async function issueToken(testkit,
|
|
3233
|
+
async function issueToken(testkit, seed2, body) {
|
|
1509
3234
|
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
1510
3235
|
throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
|
|
1511
3236
|
}
|
|
@@ -1519,7 +3244,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
1519
3244
|
const expiresIn = input.expiresIn;
|
|
1520
3245
|
if (input.m2m === true) {
|
|
1521
3246
|
const clientId = optionalString(input, "clientId");
|
|
1522
|
-
const app = clientId ?
|
|
3247
|
+
const app = clientId ? seed2.applications.find((a) => a.clientId === clientId) : void 0;
|
|
1523
3248
|
const scopes = optionalStrings(input, "scopes") ?? [];
|
|
1524
3249
|
return testkit.m2mToken({
|
|
1525
3250
|
clientId,
|
|
@@ -1536,13 +3261,17 @@ async function issueToken(testkit, seed, body) {
|
|
|
1536
3261
|
const roles = optionalStrings(input, "roles");
|
|
1537
3262
|
const userRef = optionalString(input, "user");
|
|
1538
3263
|
if (userRef) {
|
|
1539
|
-
const scenario = seedScenario(
|
|
3264
|
+
const scenario = seedScenario(seed2, {
|
|
1540
3265
|
user: userRef,
|
|
1541
3266
|
organization: optionalString(input, "organization") ?? null
|
|
1542
3267
|
});
|
|
1543
3268
|
if (permissions) scenario.permissions = permissions;
|
|
1544
3269
|
if (roles) scenario.roles = roles;
|
|
1545
|
-
return await testkit.tokenFor(scenario, {
|
|
3270
|
+
return await testkit.tokenFor(scenario, {
|
|
3271
|
+
expiresIn,
|
|
3272
|
+
invalid: invalid2,
|
|
3273
|
+
featureFlags: featureFlagsFor(seed2, scenario.organization?.code ?? null)
|
|
3274
|
+
});
|
|
1546
3275
|
}
|
|
1547
3276
|
const options = {
|
|
1548
3277
|
subject: optionalString(input, "subject"),
|
|
@@ -1607,7 +3336,7 @@ async function readText(req) {
|
|
|
1607
3336
|
}
|
|
1608
3337
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1609
3338
|
}
|
|
1610
|
-
function
|
|
3339
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1611
3340
|
res.writeHead(status, {
|
|
1612
3341
|
"content-type": "application/json; charset=utf-8",
|
|
1613
3342
|
"cache-control": "no-store",
|
|
@@ -1621,10 +3350,10 @@ function sendError(res, error) {
|
|
|
1621
3350
|
return;
|
|
1622
3351
|
}
|
|
1623
3352
|
if (error instanceof TestkitError) {
|
|
1624
|
-
|
|
3353
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1625
3354
|
return;
|
|
1626
3355
|
}
|
|
1627
|
-
|
|
3356
|
+
sendJson4(res, 500, {
|
|
1628
3357
|
error: "server_error",
|
|
1629
3358
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1630
3359
|
});
|
|
@@ -1771,6 +3500,15 @@ async function runDoctor(options) {
|
|
|
1771
3500
|
} else {
|
|
1772
3501
|
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1773
3502
|
}
|
|
3503
|
+
if (issuer?.startsWith("https://")) {
|
|
3504
|
+
checks.push(
|
|
3505
|
+
env.NODE_EXTRA_CA_CERTS ? { name: "NODE_EXTRA_CA_CERTS", status: "pass", detail: `${env.NODE_EXTRA_CA_CERTS}.` } : {
|
|
3506
|
+
name: "NODE_EXTRA_CA_CERTS",
|
|
3507
|
+
status: "warn",
|
|
3508
|
+
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."
|
|
3509
|
+
}
|
|
3510
|
+
);
|
|
3511
|
+
}
|
|
1774
3512
|
const site = env.KINDE_SITE_URL;
|
|
1775
3513
|
if (!site) {
|
|
1776
3514
|
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
@@ -1799,19 +3537,23 @@ function parseEnvFile(text) {
|
|
|
1799
3537
|
|
|
1800
3538
|
// src/cli.ts
|
|
1801
3539
|
var DEFAULT_URL = process.env.KINDE_TESTKIT_URL ?? "http://localhost:4400";
|
|
1802
|
-
var DEFAULT_SEED_FILE = "kinde-testkit.json";
|
|
1803
3540
|
var HELP = `kinde-testkit: a local Kinde issuer for testing apps
|
|
1804
3541
|
|
|
1805
3542
|
Usage
|
|
1806
3543
|
kinde-testkit start [options] Start the local issuer
|
|
3544
|
+
kinde-testkit stop Stop a running issuer
|
|
3545
|
+
kinde-testkit seed <file> Replace a running issuer's seed with a JSON, YAML, JS or TS file
|
|
1807
3546
|
kinde-testkit token [options] Print a signed test access token
|
|
1808
3547
|
kinde-testkit users [--json] List seeded users
|
|
1809
3548
|
kinde-testkit organizations [--json] List seeded organizations
|
|
1810
3549
|
kinde-testkit inspect [token] Decode a token and check it (reads stdin when no token)
|
|
3550
|
+
kinde-testkit inspect --requests Show the latest requests the issuer answered
|
|
3551
|
+
kinde-testkit coverage [options] Show which authentication scenarios your tests covered
|
|
1811
3552
|
kinde-testkit doctor [options] Check your app's Kinde settings against the issuer
|
|
1812
3553
|
kinde-testkit fail <path> [options] Make an endpoint fail, slow down or hang
|
|
1813
|
-
kinde-testkit reset Clear
|
|
3554
|
+
kinde-testkit reset Clear sessions, failure rules, deliveries and API changes
|
|
1814
3555
|
kinde-testkit webhook <type> [options] Send a signed webhook event
|
|
3556
|
+
kinde-testkit cert [--dir <dir>] Create the local HTTPS certificate and print its path
|
|
1815
3557
|
|
|
1816
3558
|
start
|
|
1817
3559
|
--port <n> Port to listen on (default 4400)
|
|
@@ -1819,9 +3561,13 @@ start
|
|
|
1819
3561
|
--issuer <url> Issuer to put in tokens (default http://localhost:<port>)
|
|
1820
3562
|
--audience <a,b> Audience values for access tokens
|
|
1821
3563
|
--client-id <id> Value for azp
|
|
1822
|
-
--seed <file> Seed file (default ./kinde-testkit.json
|
|
3564
|
+
--seed <file> Seed file: JSON, YAML, JS or TS (default ./kinde-testkit.json,
|
|
3565
|
+
.yaml, .yml, .ts, .mts, .js or .mjs, the first that exists)
|
|
1823
3566
|
--allow-public Allow binding to a non-loopback interface
|
|
1824
3567
|
--webhook <url> Send webhooks to this URL (repeatable)
|
|
3568
|
+
--https Serve HTTPS with a local certificate (needed by @kinde/management-api-js)
|
|
3569
|
+
--cert-dir <dir> Where to keep that certificate (default ./.kinde-testkit)
|
|
3570
|
+
--coverage Write authentication coverage to ./.kinde-testkit/coverage when it stops
|
|
1825
3571
|
|
|
1826
3572
|
token
|
|
1827
3573
|
--url <url> Running issuer (default ${DEFAULT_URL})
|
|
@@ -1841,6 +3587,15 @@ token
|
|
|
1841
3587
|
|
|
1842
3588
|
inspect
|
|
1843
3589
|
--url <url> Also verify the issuer and signature against a running issuer
|
|
3590
|
+
--requests List the latest requests instead of checking a token
|
|
3591
|
+
--tokens List the latest issued tokens instead of checking a token
|
|
3592
|
+
--json Print JSON
|
|
3593
|
+
|
|
3594
|
+
coverage
|
|
3595
|
+
--url <url> Read a running issuer instead of the coverage folder
|
|
3596
|
+
--dir <dir> Coverage folder (default ./${DEFAULT_COVERAGE_DIRECTORY.replace(/\\/g, "/")})
|
|
3597
|
+
--min <n> Exit with an error when fewer than n scenarios are covered
|
|
3598
|
+
--clear Delete the coverage folder, or clear a running issuer's coverage
|
|
1844
3599
|
--json Print JSON
|
|
1845
3600
|
|
|
1846
3601
|
doctor
|
|
@@ -1893,6 +3648,14 @@ async function main(argv) {
|
|
|
1893
3648
|
case "webhook":
|
|
1894
3649
|
case "webhooks":
|
|
1895
3650
|
return webhook(rest);
|
|
3651
|
+
case "cert":
|
|
3652
|
+
return cert(rest);
|
|
3653
|
+
case "stop":
|
|
3654
|
+
return stop(rest);
|
|
3655
|
+
case "seed":
|
|
3656
|
+
return seed(rest);
|
|
3657
|
+
case "coverage":
|
|
3658
|
+
return coverage(rest);
|
|
1896
3659
|
case void 0:
|
|
1897
3660
|
case "help":
|
|
1898
3661
|
case "--help":
|
|
@@ -1915,20 +3678,25 @@ async function start(args) {
|
|
|
1915
3678
|
seed: { type: "string" },
|
|
1916
3679
|
"allow-public": { type: "boolean" },
|
|
1917
3680
|
webhook: { type: "string", multiple: true },
|
|
3681
|
+
https: { type: "boolean" },
|
|
3682
|
+
"cert-dir": { type: "string" },
|
|
3683
|
+
coverage: { type: "boolean" },
|
|
1918
3684
|
json: { type: "boolean" }
|
|
1919
3685
|
}
|
|
1920
3686
|
});
|
|
1921
|
-
const seedPath = values.seed ?? (
|
|
1922
|
-
const
|
|
1923
|
-
if (
|
|
3687
|
+
const seedPath = values.seed ?? findSeedFile();
|
|
3688
|
+
const seed2 = seedPath ? await loadSeedFile(seedPath) : values.webhook ? {} : void 0;
|
|
3689
|
+
if (seed2 && values.webhook) seed2.webhooks = [...seed2.webhooks ?? [], ...values.webhook.map((url) => ({ url }))];
|
|
1924
3690
|
const running = await startKindeTestkit({
|
|
1925
3691
|
port: values.port ? Number(values.port) : void 0,
|
|
1926
3692
|
host: values.host,
|
|
1927
3693
|
issuer: values.issuer,
|
|
1928
3694
|
audience: values.audience ? csv(values.audience) : void 0,
|
|
1929
3695
|
clientId: values["client-id"],
|
|
1930
|
-
seed,
|
|
1931
|
-
allowPublic: values["allow-public"]
|
|
3696
|
+
seed: seed2,
|
|
3697
|
+
allowPublic: values["allow-public"],
|
|
3698
|
+
https: values.https ? { certDirectory: values["cert-dir"] } : void 0,
|
|
3699
|
+
coverage: values.coverage
|
|
1932
3700
|
});
|
|
1933
3701
|
if (values.json) {
|
|
1934
3702
|
process.stdout.write(
|
|
@@ -1937,6 +3705,7 @@ async function start(args) {
|
|
|
1937
3705
|
issuer: running.issuer,
|
|
1938
3706
|
discovery: running.discoveryUrl,
|
|
1939
3707
|
jwks: running.jwksUri,
|
|
3708
|
+
dashboard: `${running.url}/dashboard`,
|
|
1940
3709
|
users: running.seed.users.length,
|
|
1941
3710
|
organizations: running.seed.organizations.length
|
|
1942
3711
|
})}
|
|
@@ -1955,22 +3724,24 @@ async function start(args) {
|
|
|
1955
3724
|
`JWKS: ${running.jwksUri}`,
|
|
1956
3725
|
`Sign-in page: ${running.url}/oauth2/auth`,
|
|
1957
3726
|
`Token: POST ${running.url}/testkit/token`,
|
|
3727
|
+
`Dashboard: ${running.url}/dashboard`,
|
|
1958
3728
|
"",
|
|
1959
|
-
`Seed: ${seedPath ?
|
|
3729
|
+
`Seed: ${seedPath ? resolve4(seedPath) : "none"}`,
|
|
1960
3730
|
`Users: ${running.seed.users.length}`,
|
|
1961
3731
|
`Organizations: ${running.seed.organizations.length}`,
|
|
1962
3732
|
`Webhooks: ${running.webhooks.listEndpoints().map((e) => e.url).join(", ") || "none"}`,
|
|
3733
|
+
...running.certificatePath ? ["", "HTTPS uses a local certificate. Start Node processes that call the testkit with:", ` NODE_EXTRA_CA_CERTS=${running.certificatePath}`] : [],
|
|
1963
3734
|
"",
|
|
1964
3735
|
"Test tokens only. Press Ctrl+C to stop.",
|
|
1965
3736
|
""
|
|
1966
3737
|
].join("\n")
|
|
1967
3738
|
);
|
|
1968
3739
|
}
|
|
1969
|
-
const
|
|
3740
|
+
const stop2 = () => {
|
|
1970
3741
|
running.close().finally(() => process.exit(0));
|
|
1971
3742
|
};
|
|
1972
|
-
process.once("SIGINT",
|
|
1973
|
-
process.once("SIGTERM",
|
|
3743
|
+
process.once("SIGINT", stop2);
|
|
3744
|
+
process.once("SIGTERM", stop2);
|
|
1974
3745
|
}
|
|
1975
3746
|
async function token(args) {
|
|
1976
3747
|
const { values } = parseArgs({
|
|
@@ -2021,8 +3792,31 @@ async function inspect(args) {
|
|
|
2021
3792
|
const { values, positionals } = parseArgs({
|
|
2022
3793
|
args,
|
|
2023
3794
|
allowPositionals: true,
|
|
2024
|
-
options: { url: { type: "string" }, json: { type: "boolean" } }
|
|
3795
|
+
options: { url: { type: "string" }, json: { type: "boolean" }, requests: { type: "boolean" }, tokens: { type: "boolean" } }
|
|
2025
3796
|
});
|
|
3797
|
+
if (values.requests) {
|
|
3798
|
+
const entries = await request(values.url ?? DEFAULT_URL, "/testkit/requests");
|
|
3799
|
+
if (values.json) return void process.stdout.write(`${JSON.stringify(entries, null, 2)}
|
|
3800
|
+
`);
|
|
3801
|
+
if (entries.length === 0) return void process.stdout.write("No requests yet.\n");
|
|
3802
|
+
for (const e of entries) {
|
|
3803
|
+
process.stdout.write(`${e.at.slice(11, 19)} ${String(e.status).padEnd(4)}${e.injected ? "injected " : ""}${e.method.padEnd(7)}${e.path} ${e.durationMs}ms
|
|
3804
|
+
`);
|
|
3805
|
+
}
|
|
3806
|
+
return;
|
|
3807
|
+
}
|
|
3808
|
+
if (values.tokens) {
|
|
3809
|
+
const entries = await request(values.url ?? DEFAULT_URL, "/testkit/tokens");
|
|
3810
|
+
if (values.json) return void process.stdout.write(`${JSON.stringify(entries, null, 2)}
|
|
3811
|
+
`);
|
|
3812
|
+
if (entries.length === 0) return void process.stdout.write("No tokens issued yet.\n");
|
|
3813
|
+
for (const e of entries) {
|
|
3814
|
+
const parts = [e.kind, e.subject ?? "no subject", e.organization ?? "no organization", e.permissions.join(",") || "no permissions"];
|
|
3815
|
+
process.stdout.write(`${e.at.slice(11, 19)} ${parts.join(" ")}${e.invalid ? ` invalid: ${e.invalid}` : ""}
|
|
3816
|
+
`);
|
|
3817
|
+
}
|
|
3818
|
+
return;
|
|
3819
|
+
}
|
|
2026
3820
|
const raw = positionals[0] ?? (process.stdin.isTTY ? "" : await readStdin());
|
|
2027
3821
|
const token2 = raw.trim().replace(/^Bearer\s+/i, "");
|
|
2028
3822
|
if (!token2) {
|
|
@@ -2065,14 +3859,14 @@ async function doctor(args) {
|
|
|
2065
3859
|
json: { type: "boolean" }
|
|
2066
3860
|
}
|
|
2067
3861
|
});
|
|
2068
|
-
const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) =>
|
|
3862
|
+
const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) => existsSync3(file));
|
|
2069
3863
|
const env = {};
|
|
2070
3864
|
for (const file of files) {
|
|
2071
|
-
if (!
|
|
2072
|
-
Object.assign(env, parseEnvFile(
|
|
3865
|
+
if (!existsSync3(file)) throw new TestkitError("INVALID_REQUEST", `No env file at ${resolve4(file)}.`);
|
|
3866
|
+
Object.assign(env, parseEnvFile(readFileSync4(file, "utf8")));
|
|
2073
3867
|
}
|
|
2074
3868
|
for (const [key, value] of Object.entries(process.env)) {
|
|
2075
|
-
if (key.startsWith("KINDE_") && value !== void 0) env[key] = value;
|
|
3869
|
+
if ((key.startsWith("KINDE_") || key === "NODE_EXTRA_CA_CERTS") && value !== void 0) env[key] = value;
|
|
2076
3870
|
}
|
|
2077
3871
|
const report = await runDoctor({ url: values.url ?? DEFAULT_URL, env });
|
|
2078
3872
|
if (values.json) {
|
|
@@ -2149,7 +3943,79 @@ async function fail(args) {
|
|
|
2149
3943
|
async function reset(args) {
|
|
2150
3944
|
const { values } = parseArgs({ args, options: { url: { type: "string" } } });
|
|
2151
3945
|
await request(values.url ?? DEFAULT_URL, "/testkit/reset", { method: "POST" });
|
|
2152
|
-
process.stdout.write("Cleared sign-in
|
|
3946
|
+
process.stdout.write("Cleared sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.\n");
|
|
3947
|
+
}
|
|
3948
|
+
async function stop(args) {
|
|
3949
|
+
const { values } = parseArgs({ args, options: { url: { type: "string" } } });
|
|
3950
|
+
const url = values.url ?? DEFAULT_URL;
|
|
3951
|
+
await request(url, "/testkit/stop", { method: "POST" });
|
|
3952
|
+
process.stdout.write(`Stopped the issuer at ${url}.
|
|
3953
|
+
`);
|
|
3954
|
+
}
|
|
3955
|
+
async function seed(args) {
|
|
3956
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { url: { type: "string" }, json: { type: "boolean" } } });
|
|
3957
|
+
const path = positionals[0] ?? findSeedFile();
|
|
3958
|
+
if (!path) throw new TestkitError("INVALID_REQUEST", "Pass a seed file: kinde-testkit seed kinde-testkit.yaml");
|
|
3959
|
+
const body = await loadSeedFile(path);
|
|
3960
|
+
const result = await request(values.url ?? DEFAULT_URL, "/testkit/seed", {
|
|
3961
|
+
method: "POST",
|
|
3962
|
+
headers: { "content-type": "application/json" },
|
|
3963
|
+
body: JSON.stringify(body)
|
|
3964
|
+
});
|
|
3965
|
+
if (values.json) return void process.stdout.write(`${JSON.stringify(result)}
|
|
3966
|
+
`);
|
|
3967
|
+
process.stdout.write(
|
|
3968
|
+
`Loaded ${resolve4(path)}: ${count(result.users, "user")}, ${count(result.organizations, "organization")}, ${count(result.memberships, "membership")}.
|
|
3969
|
+
Sessions, failure rules and deliveries were cleared. The issuer, audience and signing key did not change.
|
|
3970
|
+
`
|
|
3971
|
+
);
|
|
3972
|
+
}
|
|
3973
|
+
function count(n, noun) {
|
|
3974
|
+
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
3975
|
+
}
|
|
3976
|
+
async function coverage(args) {
|
|
3977
|
+
const { values } = parseArgs({
|
|
3978
|
+
args,
|
|
3979
|
+
options: { url: { type: "string" }, dir: { type: "string" }, min: { type: "string" }, clear: { type: "boolean" }, json: { type: "boolean" } }
|
|
3980
|
+
});
|
|
3981
|
+
const directory = values.dir ?? DEFAULT_COVERAGE_DIRECTORY;
|
|
3982
|
+
if (values.clear) {
|
|
3983
|
+
if (values.url) await request(values.url, "/testkit/coverage", { method: "DELETE" });
|
|
3984
|
+
else clearCoverageDirectory(directory);
|
|
3985
|
+
process.stdout.write(values.url ? `Cleared coverage at ${values.url}.
|
|
3986
|
+
` : `Deleted ${resolve4(directory)}.
|
|
3987
|
+
`);
|
|
3988
|
+
return;
|
|
3989
|
+
}
|
|
3990
|
+
let report;
|
|
3991
|
+
let source;
|
|
3992
|
+
if (values.url) {
|
|
3993
|
+
report = (await request(values.url, "/testkit/coverage")).report;
|
|
3994
|
+
source = values.url;
|
|
3995
|
+
} else {
|
|
3996
|
+
const read = readCoverageDirectory(directory);
|
|
3997
|
+
if (read.files === 0) {
|
|
3998
|
+
throw new TestkitError("INVALID_REQUEST", `No coverage recorded in ${resolve4(directory)}.`, [
|
|
3999
|
+
"Turn it on with useKindeTestkit({ coverage: true }), startKindeTestkit({ coverage: true }) or kinde-testkit start --coverage.",
|
|
4000
|
+
"Or read a running issuer with --url."
|
|
4001
|
+
]);
|
|
4002
|
+
}
|
|
4003
|
+
report = read.report;
|
|
4004
|
+
source = `${read.files} test run${read.files === 1 ? "" : "s"} in ${resolve4(directory)}`;
|
|
4005
|
+
}
|
|
4006
|
+
if (values.json) process.stdout.write(`${JSON.stringify(report, null, 2)}
|
|
4007
|
+
`);
|
|
4008
|
+
else process.stdout.write(`${formatCoverageReport(report)}
|
|
4009
|
+
|
|
4010
|
+
From ${source}.
|
|
4011
|
+
`);
|
|
4012
|
+
const min = values.min === void 0 ? void 0 : Number(values.min);
|
|
4013
|
+
if (min !== void 0 && report.covered < min) {
|
|
4014
|
+
process.stderr.write(`
|
|
4015
|
+
Coverage ${report.covered}/${report.total} is below the minimum of ${min}.
|
|
4016
|
+
`);
|
|
4017
|
+
process.exitCode = 1;
|
|
4018
|
+
}
|
|
2153
4019
|
}
|
|
2154
4020
|
async function readStdin() {
|
|
2155
4021
|
const chunks = [];
|
|
@@ -2234,6 +4100,22 @@ ${types.billing.map((t) => ` ${t}`).join("\n")}
|
|
|
2234
4100
|
`);
|
|
2235
4101
|
if (deliveries.some((d) => !d.delivered)) process.exitCode = 1;
|
|
2236
4102
|
}
|
|
4103
|
+
async function cert(args) {
|
|
4104
|
+
const { values } = parseArgs({ args, options: { dir: { type: "string" }, json: { type: "boolean" } } });
|
|
4105
|
+
const certificate = ensureLocalCertificate(values.dir);
|
|
4106
|
+
if (values.json) {
|
|
4107
|
+
process.stdout.write(`${JSON.stringify({ certPath: certificate.certPath, created: certificate.created })}
|
|
4108
|
+
`);
|
|
4109
|
+
return;
|
|
4110
|
+
}
|
|
4111
|
+
process.stdout.write(
|
|
4112
|
+
`${certificate.created ? "Created" : "Using"} ${certificate.certPath}
|
|
4113
|
+
|
|
4114
|
+
Trust it in Node processes that call the testkit over HTTPS:
|
|
4115
|
+
NODE_EXTRA_CA_CERTS=${certificate.certPath}
|
|
4116
|
+
`
|
|
4117
|
+
);
|
|
4118
|
+
}
|
|
2237
4119
|
function describeDelivery(delivery) {
|
|
2238
4120
|
const attempts = delivery.attempts ?? [];
|
|
2239
4121
|
const outcome = attempts.map((a) => a.status === null ? "no answer" : String(a.status)).join(", ");
|
|
@@ -2299,19 +4181,30 @@ ${details.map((d) => ` - ${d}
|
|
|
2299
4181
|
}
|
|
2300
4182
|
return body;
|
|
2301
4183
|
}
|
|
2302
|
-
function readSeed(path) {
|
|
2303
|
-
try {
|
|
2304
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
2305
|
-
} catch (error) {
|
|
2306
|
-
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${resolve(path)}.`, [
|
|
2307
|
-
error instanceof Error ? error.message : String(error)
|
|
2308
|
-
]);
|
|
2309
|
-
}
|
|
2310
|
-
}
|
|
2311
4184
|
function csv(value) {
|
|
2312
4185
|
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
2313
4186
|
}
|
|
2314
|
-
|
|
4187
|
+
function relaunchTrustingLocalCertificate(argv) {
|
|
4188
|
+
if (process.env.KINDE_TESTKIT_TRUSTED || argv[0] === "start" || argv[0] === "cert") return false;
|
|
4189
|
+
const urlArg = argv.find((arg, i) => arg.startsWith("--url=") || argv[i - 1] === "--url");
|
|
4190
|
+
const target = urlArg?.replace(/^--url=/, "") ?? process.env.KINDE_TESTKIT_URL ?? "";
|
|
4191
|
+
const certPath = resolve4(".kinde-testkit", "localhost-cert.pem");
|
|
4192
|
+
if (!target.startsWith("https://") || !existsSync3(certPath)) return false;
|
|
4193
|
+
let trusted = certPath;
|
|
4194
|
+
const existing = process.env.NODE_EXTRA_CA_CERTS;
|
|
4195
|
+
if (existing && resolve4(existing) !== certPath) {
|
|
4196
|
+
trusted = resolve4(".kinde-testkit", "ca-bundle.pem");
|
|
4197
|
+
const current = existsSync3(existing) ? readFileSync4(existing, "utf8") : "";
|
|
4198
|
+
writeFileSync3(trusted, `${current.trimEnd()}
|
|
4199
|
+
${readFileSync4(certPath, "utf8")}`);
|
|
4200
|
+
}
|
|
4201
|
+
const result = spawnSync(process.execPath, [process.argv[1], ...argv], {
|
|
4202
|
+
stdio: "inherit",
|
|
4203
|
+
env: { ...process.env, NODE_EXTRA_CA_CERTS: trusted, KINDE_TESTKIT_TRUSTED: "1" }
|
|
4204
|
+
});
|
|
4205
|
+
process.exit(result.status ?? 1);
|
|
4206
|
+
}
|
|
4207
|
+
if (!relaunchTrustingLocalCertificate(process.argv.slice(2))) main(process.argv.slice(2)).catch((error) => {
|
|
2315
4208
|
if (error instanceof TestkitError) {
|
|
2316
4209
|
process.stderr.write(`${error.toString()}
|
|
2317
4210
|
`);
|