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/index.js
CHANGED
|
@@ -189,6 +189,20 @@ var INVALID_TOKEN_KINDS = [
|
|
|
189
189
|
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
190
190
|
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
191
191
|
var KindeTestkit = class _KindeTestkit {
|
|
192
|
+
observers = [];
|
|
193
|
+
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
194
|
+
observe(observer) {
|
|
195
|
+
this.observers.push(observer);
|
|
196
|
+
return () => {
|
|
197
|
+
this.observers = this.observers.filter((o) => o !== observer);
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
async signAccess(payload, invalid2, now) {
|
|
201
|
+
const final = applyInvalidClaims(payload, invalid2, now);
|
|
202
|
+
const token = await this.sign(final, invalid2);
|
|
203
|
+
for (const observer of this.observers) observer.accessToken?.(final, invalid2, token);
|
|
204
|
+
return token;
|
|
205
|
+
}
|
|
192
206
|
issuer;
|
|
193
207
|
audience;
|
|
194
208
|
clientId;
|
|
@@ -248,7 +262,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
248
262
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
249
263
|
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
250
264
|
Object.assign(payload, options.claims ?? {});
|
|
251
|
-
return this.
|
|
265
|
+
return this.signAccess(payload, options.invalid, now);
|
|
252
266
|
}
|
|
253
267
|
async m2mToken(options = {}) {
|
|
254
268
|
const now = this.clock();
|
|
@@ -269,10 +283,13 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
269
283
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
270
284
|
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
271
285
|
Object.assign(payload, options.claims ?? {});
|
|
272
|
-
return this.
|
|
286
|
+
return this.signAccess(payload, options.invalid, now);
|
|
273
287
|
}
|
|
274
288
|
async tokenFor(scenario2, overrides = {}) {
|
|
275
|
-
if (scenario2.kind === "unauthenticated")
|
|
289
|
+
if (scenario2.kind === "unauthenticated") {
|
|
290
|
+
for (const observer of this.observers) observer.anonymous?.();
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
276
293
|
return this.token({
|
|
277
294
|
subject: scenario2.user.id,
|
|
278
295
|
organizationCode: scenario2.organization?.code ?? null,
|
|
@@ -314,7 +331,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
314
331
|
for (const key of Object.keys(payload)) {
|
|
315
332
|
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
316
333
|
}
|
|
317
|
-
|
|
334
|
+
const token = await this.sign(payload);
|
|
335
|
+
for (const observer of this.observers) observer.idToken?.(payload, token);
|
|
336
|
+
return token;
|
|
318
337
|
}
|
|
319
338
|
async headersFor(scenario2, overrides = {}) {
|
|
320
339
|
const token = await this.tokenFor(scenario2, overrides);
|
|
@@ -440,8 +459,230 @@ async function createKindeToken(options = {}) {
|
|
|
440
459
|
|
|
441
460
|
// src/server.ts
|
|
442
461
|
import { createServer } from "http";
|
|
462
|
+
import { createServer as createHttpsServer } from "https";
|
|
463
|
+
|
|
464
|
+
// src/certificate.ts
|
|
465
|
+
import { createHash as createHash2, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
|
|
466
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
467
|
+
import { join, resolve } from "path";
|
|
468
|
+
var CERT_FILE = "localhost-cert.pem";
|
|
469
|
+
var KEY_FILE = "localhost-key.pem";
|
|
470
|
+
var VALID_DAYS = 825;
|
|
471
|
+
function ensureLocalCertificate(directory = ".kinde-testkit") {
|
|
472
|
+
const dir = resolve(directory);
|
|
473
|
+
const certPath = join(dir, CERT_FILE);
|
|
474
|
+
const keyPath = join(dir, KEY_FILE);
|
|
475
|
+
if (existsSync(certPath) && existsSync(keyPath)) {
|
|
476
|
+
const cert2 = readFileSync(certPath, "utf8");
|
|
477
|
+
const key2 = readFileSync(keyPath, "utf8");
|
|
478
|
+
try {
|
|
479
|
+
if (new Date(new X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
|
|
480
|
+
return { cert: cert2, key: key2, certPath, keyPath, created: false };
|
|
481
|
+
}
|
|
482
|
+
} catch {
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
const { cert, key } = createLocalCertificate();
|
|
486
|
+
mkdirSync(dir, { recursive: true });
|
|
487
|
+
writeFileSync(certPath, cert);
|
|
488
|
+
writeFileSync(keyPath, key, { mode: 384 });
|
|
489
|
+
writeFileSync(join(dir, ".gitignore"), "*\n");
|
|
490
|
+
return { cert, key, certPath, keyPath, created: true };
|
|
491
|
+
}
|
|
492
|
+
function createLocalCertificate() {
|
|
493
|
+
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
494
|
+
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
495
|
+
const keyId = createHash2("sha1").update(subjectPublicKeyBits(spki)).digest();
|
|
496
|
+
const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
|
|
497
|
+
const now = Date.now();
|
|
498
|
+
const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
|
|
499
|
+
const serial = randomBytes(16);
|
|
500
|
+
serial[0] &= 127;
|
|
501
|
+
const extensions = seq(
|
|
502
|
+
seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
|
|
503
|
+
seq(oid("2.5.29.14"), octets(octets(keyId))),
|
|
504
|
+
seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
|
|
505
|
+
seq(
|
|
506
|
+
oid("2.5.29.17"),
|
|
507
|
+
octets(
|
|
508
|
+
seq(
|
|
509
|
+
tlv(130, Buffer.from("localhost")),
|
|
510
|
+
tlv(135, Buffer.from([127, 0, 0, 1])),
|
|
511
|
+
tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
|
|
512
|
+
)
|
|
513
|
+
)
|
|
514
|
+
)
|
|
515
|
+
);
|
|
516
|
+
const tbs = seq(
|
|
517
|
+
tlv(160, integer(Buffer.from([2]))),
|
|
518
|
+
integer(serial),
|
|
519
|
+
algorithm,
|
|
520
|
+
name,
|
|
521
|
+
seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
|
|
522
|
+
name,
|
|
523
|
+
spki,
|
|
524
|
+
tlv(163, extensions)
|
|
525
|
+
);
|
|
526
|
+
const signature = sign("sha256", tbs, privateKey);
|
|
527
|
+
const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
|
|
528
|
+
return {
|
|
529
|
+
cert: pem("CERTIFICATE", der),
|
|
530
|
+
key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
function subjectPublicKeyBits(spki) {
|
|
534
|
+
const outer = readTlv(spki, 0);
|
|
535
|
+
const algorithm = readTlv(spki, outer.start);
|
|
536
|
+
const bits = readTlv(spki, algorithm.end);
|
|
537
|
+
return spki.subarray(bits.start + 1, bits.end);
|
|
538
|
+
}
|
|
539
|
+
function readTlv(buf, offset) {
|
|
540
|
+
let len = buf[offset + 1];
|
|
541
|
+
let header = 2;
|
|
542
|
+
if (len & 128) {
|
|
543
|
+
const n = len & 127;
|
|
544
|
+
len = 0;
|
|
545
|
+
for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
|
|
546
|
+
header += n;
|
|
547
|
+
}
|
|
548
|
+
return { start: offset + header, end: offset + header + len };
|
|
549
|
+
}
|
|
550
|
+
function tlv(tag, content) {
|
|
551
|
+
return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
|
|
552
|
+
}
|
|
553
|
+
function length(n) {
|
|
554
|
+
if (n < 128) return Buffer.from([n]);
|
|
555
|
+
const bytes = [];
|
|
556
|
+
while (n > 0) {
|
|
557
|
+
bytes.unshift(n & 255);
|
|
558
|
+
n >>= 8;
|
|
559
|
+
}
|
|
560
|
+
return Buffer.from([128 | bytes.length, ...bytes]);
|
|
561
|
+
}
|
|
562
|
+
function seq(...items) {
|
|
563
|
+
return tlv(48, Buffer.concat(items));
|
|
564
|
+
}
|
|
565
|
+
function set(...items) {
|
|
566
|
+
return tlv(49, Buffer.concat(items));
|
|
567
|
+
}
|
|
568
|
+
function octets(content) {
|
|
569
|
+
return tlv(4, content);
|
|
570
|
+
}
|
|
571
|
+
function integer(bytes) {
|
|
572
|
+
return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
|
|
573
|
+
}
|
|
574
|
+
function oid(dotted) {
|
|
575
|
+
const parts = dotted.split(".").map(Number);
|
|
576
|
+
const bytes = [parts[0] * 40 + parts[1]];
|
|
577
|
+
for (const part of parts.slice(2)) {
|
|
578
|
+
const chunk = [part & 127];
|
|
579
|
+
let value = part >> 7;
|
|
580
|
+
while (value > 0) {
|
|
581
|
+
chunk.unshift(value & 127 | 128);
|
|
582
|
+
value >>= 7;
|
|
583
|
+
}
|
|
584
|
+
bytes.push(...chunk);
|
|
585
|
+
}
|
|
586
|
+
return tlv(6, Buffer.from(bytes));
|
|
587
|
+
}
|
|
588
|
+
function utcTime(date) {
|
|
589
|
+
const iso = date.toISOString();
|
|
590
|
+
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`;
|
|
591
|
+
return tlv(23, Buffer.from(value));
|
|
592
|
+
}
|
|
593
|
+
function pem(label, der) {
|
|
594
|
+
const body = der.toString("base64").match(/.{1,64}/g).join("\n");
|
|
595
|
+
return `-----BEGIN ${label}-----
|
|
596
|
+
${body}
|
|
597
|
+
-----END ${label}-----
|
|
598
|
+
`;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// src/login-page.ts
|
|
602
|
+
var STYLE = `
|
|
603
|
+
: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}
|
|
604
|
+
@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}}
|
|
605
|
+
*{box-sizing:border-box}
|
|
606
|
+
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}
|
|
607
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
608
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
609
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
610
|
+
p{margin:0;color:var(--muted)}
|
|
611
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
612
|
+
form{margin:0}
|
|
613
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
614
|
+
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}
|
|
615
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
616
|
+
.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}
|
|
617
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
618
|
+
.list{display:grid;gap:8px}
|
|
619
|
+
.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}
|
|
620
|
+
.option:hover{border-color:var(--muted)}
|
|
621
|
+
.option strong{display:block;font-weight:500}
|
|
622
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
623
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
624
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
625
|
+
`;
|
|
626
|
+
function escapeHtml(value) {
|
|
627
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
628
|
+
}
|
|
629
|
+
function layout(title, body) {
|
|
630
|
+
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>`;
|
|
631
|
+
}
|
|
632
|
+
function displayName(user) {
|
|
633
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
634
|
+
}
|
|
635
|
+
function renderSignIn(options) {
|
|
636
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
637
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
638
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
639
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
640
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
641
|
+
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>`;
|
|
642
|
+
}).join("");
|
|
643
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
644
|
+
return layout(
|
|
645
|
+
"Sign in",
|
|
646
|
+
`<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>`
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
function renderOrganizationPicker(options) {
|
|
650
|
+
const choices = options.organizations.map(
|
|
651
|
+
(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>`
|
|
652
|
+
).join("");
|
|
653
|
+
return layout(
|
|
654
|
+
"Choose an organization",
|
|
655
|
+
`<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>`
|
|
656
|
+
);
|
|
657
|
+
}
|
|
658
|
+
function renderMessage(title, message) {
|
|
659
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
660
|
+
}
|
|
443
661
|
|
|
444
662
|
// src/seed.ts
|
|
663
|
+
function roleRecord(key, extra = {}) {
|
|
664
|
+
return {
|
|
665
|
+
id: stableId("role", key),
|
|
666
|
+
key,
|
|
667
|
+
name: extra.name ?? titleCase(key),
|
|
668
|
+
description: extra.description ?? null,
|
|
669
|
+
isDefault: extra.isDefault ?? false,
|
|
670
|
+
permissions: [...extra.permissions ?? []]
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
function permissionRecord(key, extra = {}) {
|
|
674
|
+
return {
|
|
675
|
+
id: stableId("perm", key),
|
|
676
|
+
key,
|
|
677
|
+
name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
|
|
678
|
+
description: extra.description ?? null
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
function effectivePermissions(seed, membership) {
|
|
682
|
+
if (!membership) return [];
|
|
683
|
+
const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
|
|
684
|
+
return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
|
|
685
|
+
}
|
|
445
686
|
function resolveSeed(input) {
|
|
446
687
|
const problems = [];
|
|
447
688
|
if (!isRecord(input)) {
|
|
@@ -452,6 +693,10 @@ function resolveSeed(input) {
|
|
|
452
693
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
453
694
|
const rawApplications = listOf(input.applications, "applications", problems);
|
|
454
695
|
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
696
|
+
const rawRoles = listOf(input.roles, "roles", problems);
|
|
697
|
+
const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
|
|
698
|
+
const rawPlans = listOf(input.plans, "plans", problems);
|
|
699
|
+
const rawPermissions = listOf(input.permissions, "permissions", problems);
|
|
455
700
|
const webhooks = [];
|
|
456
701
|
rawWebhooks.forEach((raw, index) => {
|
|
457
702
|
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
@@ -555,7 +800,107 @@ function resolveSeed(input) {
|
|
|
555
800
|
if (problems.length > 0) {
|
|
556
801
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
557
802
|
}
|
|
558
|
-
|
|
803
|
+
const permissions = [];
|
|
804
|
+
rawPermissions.forEach((raw, index) => {
|
|
805
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
806
|
+
problems.push(`permissions[${index}] needs a string "key".`);
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
if (permissions.some((p) => p.key === raw.key)) {
|
|
810
|
+
problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
permissions.push(
|
|
814
|
+
permissionRecord(raw.key, {
|
|
815
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
816
|
+
description: typeof raw.description === "string" ? raw.description : void 0
|
|
817
|
+
})
|
|
818
|
+
);
|
|
819
|
+
});
|
|
820
|
+
const roles = [];
|
|
821
|
+
rawRoles.forEach((raw, index) => {
|
|
822
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
823
|
+
problems.push(`roles[${index}] needs a string "key".`);
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
if (roles.some((r) => r.key === raw.key)) {
|
|
827
|
+
problems.push(`roles[${index}] repeats the key "${raw.key}".`);
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
|
|
831
|
+
problems.push(`roles[${index}].permissions must be a list of permission keys.`);
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
roles.push(
|
|
835
|
+
roleRecord(raw.key, {
|
|
836
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
837
|
+
description: typeof raw.description === "string" ? raw.description : void 0,
|
|
838
|
+
isDefault: raw.isDefault === true,
|
|
839
|
+
permissions: raw.permissions ?? []
|
|
840
|
+
})
|
|
841
|
+
);
|
|
842
|
+
});
|
|
843
|
+
if (problems.length > 0) {
|
|
844
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
845
|
+
}
|
|
846
|
+
const featureFlags = [];
|
|
847
|
+
rawFlags.forEach((raw, index) => {
|
|
848
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
|
|
849
|
+
problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
|
|
853
|
+
featureFlags.push({
|
|
854
|
+
id: stableId("flag", raw.key),
|
|
855
|
+
key: raw.key,
|
|
856
|
+
name: typeof raw.name === "string" ? raw.name : raw.key,
|
|
857
|
+
type,
|
|
858
|
+
value: raw.value,
|
|
859
|
+
organizations: isRecord(raw.organizations) ? raw.organizations : {}
|
|
860
|
+
});
|
|
861
|
+
});
|
|
862
|
+
const plans = [];
|
|
863
|
+
rawPlans.forEach((raw, index) => {
|
|
864
|
+
if (!isRecord(raw) || typeof raw.key !== "string") {
|
|
865
|
+
problems.push(`plans[${index}] needs a string "key".`);
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
|
|
869
|
+
plans.push({
|
|
870
|
+
key: raw.key,
|
|
871
|
+
name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
|
|
872
|
+
subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
|
|
873
|
+
subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
874
|
+
entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
|
|
875
|
+
id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
|
|
876
|
+
featureKey: e.featureKey,
|
|
877
|
+
featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
|
|
878
|
+
priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
|
|
879
|
+
fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
|
|
880
|
+
unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
|
|
881
|
+
limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
|
|
882
|
+
limitMin: typeof e.limitMin === "number" ? e.limitMin : null
|
|
883
|
+
}))
|
|
884
|
+
});
|
|
885
|
+
});
|
|
886
|
+
const userProperties = {};
|
|
887
|
+
rawUsers.forEach((raw) => {
|
|
888
|
+
if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
|
|
889
|
+
userProperties[raw.id] = raw.properties;
|
|
890
|
+
}
|
|
891
|
+
});
|
|
892
|
+
if (problems.length > 0) {
|
|
893
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
894
|
+
}
|
|
895
|
+
const usedRoles = new Set(memberships.flatMap((m) => m.roles));
|
|
896
|
+
for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
|
|
897
|
+
const usedPermissions = /* @__PURE__ */ new Set([
|
|
898
|
+
...memberships.flatMap((m) => m.permissions),
|
|
899
|
+
...roles.flatMap((r) => r.permissions),
|
|
900
|
+
...applications.flatMap((a) => a.permissions ?? [])
|
|
901
|
+
]);
|
|
902
|
+
for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
|
|
903
|
+
return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
|
|
559
904
|
}
|
|
560
905
|
function findUser(users, ref) {
|
|
561
906
|
const needle = ref.toLowerCase();
|
|
@@ -600,7 +945,7 @@ function seedScenario(seed, ref) {
|
|
|
600
945
|
user,
|
|
601
946
|
organization,
|
|
602
947
|
roles: [...membership?.roles ?? []],
|
|
603
|
-
permissions:
|
|
948
|
+
permissions: effectivePermissions(seed, membership),
|
|
604
949
|
claims: {}
|
|
605
950
|
};
|
|
606
951
|
}
|
|
@@ -615,72 +960,18 @@ function listOf(value, field, problems) {
|
|
|
615
960
|
function isRecord(value) {
|
|
616
961
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
617
962
|
}
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
*{box-sizing:border-box}
|
|
627
|
-
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}
|
|
628
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
629
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
630
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
631
|
-
p{margin:0;color:var(--muted)}
|
|
632
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
633
|
-
form{margin:0}
|
|
634
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
635
|
-
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}
|
|
636
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
637
|
-
.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}
|
|
638
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
639
|
-
.list{display:grid;gap:8px}
|
|
640
|
-
.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}
|
|
641
|
-
.option:hover{border-color:var(--muted)}
|
|
642
|
-
.option strong{display:block;font-weight:500}
|
|
643
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
644
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
645
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
646
|
-
`;
|
|
647
|
-
function escapeHtml(value) {
|
|
648
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
649
|
-
}
|
|
650
|
-
function layout(title, body) {
|
|
651
|
-
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>`;
|
|
652
|
-
}
|
|
653
|
-
function displayName(user) {
|
|
654
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
655
|
-
}
|
|
656
|
-
function renderSignIn(options) {
|
|
657
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
658
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
659
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
660
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
661
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
662
|
-
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>`;
|
|
663
|
-
}).join("");
|
|
664
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
665
|
-
return layout(
|
|
666
|
-
"Sign in",
|
|
667
|
-
`<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>`
|
|
668
|
-
);
|
|
669
|
-
}
|
|
670
|
-
function renderOrganizationPicker(options) {
|
|
671
|
-
const choices = options.organizations.map(
|
|
672
|
-
(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>`
|
|
673
|
-
).join("");
|
|
674
|
-
return layout(
|
|
675
|
-
"Choose an organization",
|
|
676
|
-
`<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>`
|
|
677
|
-
);
|
|
678
|
-
}
|
|
679
|
-
function renderMessage(title, message) {
|
|
680
|
-
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
963
|
+
function featureFlagsFor(seed, organizationCode) {
|
|
964
|
+
if (seed.featureFlags.length === 0) return void 0;
|
|
965
|
+
const claim = {};
|
|
966
|
+
for (const flag of seed.featureFlags) {
|
|
967
|
+
const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
|
|
968
|
+
claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
|
|
969
|
+
}
|
|
970
|
+
return claim;
|
|
681
971
|
}
|
|
682
972
|
|
|
683
973
|
// src/oauth.ts
|
|
974
|
+
import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
684
975
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
685
976
|
var OAuthError = class extends Error {
|
|
686
977
|
constructor(status, error, description) {
|
|
@@ -692,14 +983,18 @@ var OAuthError = class extends Error {
|
|
|
692
983
|
error;
|
|
693
984
|
};
|
|
694
985
|
var AuthorizationServer = class {
|
|
695
|
-
constructor(testkit, seed, emit = () => void 0) {
|
|
986
|
+
constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
|
|
696
987
|
this.testkit = testkit;
|
|
697
988
|
this.seed = seed;
|
|
698
989
|
this.emit = emit;
|
|
990
|
+
this.directory = directory;
|
|
991
|
+
this.observe = observe;
|
|
699
992
|
}
|
|
700
993
|
testkit;
|
|
701
994
|
seed;
|
|
702
995
|
emit;
|
|
996
|
+
directory;
|
|
997
|
+
observe;
|
|
703
998
|
codes = /* @__PURE__ */ new Map();
|
|
704
999
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
705
1000
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -736,6 +1031,7 @@ var AuthorizationServer = class {
|
|
|
736
1031
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
737
1032
|
}
|
|
738
1033
|
if (params.get("prompt") === "none") {
|
|
1034
|
+
this.observe("session.silent");
|
|
739
1035
|
return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
740
1036
|
}
|
|
741
1037
|
sendHtml(
|
|
@@ -749,15 +1045,15 @@ var AuthorizationServer = class {
|
|
|
749
1045
|
})
|
|
750
1046
|
);
|
|
751
1047
|
}
|
|
752
|
-
login(res,
|
|
1048
|
+
login(res, form2) {
|
|
753
1049
|
let request;
|
|
754
1050
|
try {
|
|
755
|
-
request = decodeRequest(
|
|
1051
|
+
request = decodeRequest(form2.request ?? "");
|
|
756
1052
|
} catch {
|
|
757
1053
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
758
1054
|
}
|
|
759
1055
|
const encoded = encodeRequest(request);
|
|
760
|
-
const ref = (
|
|
1056
|
+
const ref = (form2.user || form2.email || "").trim();
|
|
761
1057
|
if (!ref) {
|
|
762
1058
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
|
|
763
1059
|
}
|
|
@@ -765,11 +1061,25 @@ var AuthorizationServer = class {
|
|
|
765
1061
|
if (!user) {
|
|
766
1062
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
767
1063
|
}
|
|
1064
|
+
if (this.directory?.isSuspended(user.id)) {
|
|
1065
|
+
this.observe("identity.suspended");
|
|
1066
|
+
return sendHtml(
|
|
1067
|
+
res,
|
|
1068
|
+
403,
|
|
1069
|
+
renderSignIn({
|
|
1070
|
+
request: encoded,
|
|
1071
|
+
users: this.loginPageUsers(),
|
|
1072
|
+
requiredOrganization: request.orgCode ?? void 0,
|
|
1073
|
+
error: `${user.email ?? user.id} is suspended and cannot sign in.`
|
|
1074
|
+
})
|
|
1075
|
+
);
|
|
1076
|
+
}
|
|
768
1077
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
769
|
-
const wanted = request.orgCode ??
|
|
1078
|
+
const wanted = request.orgCode ?? form2.org ?? null;
|
|
770
1079
|
let organizationCode = null;
|
|
771
1080
|
if (wanted) {
|
|
772
1081
|
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
1082
|
+
this.observe("organization.non-member");
|
|
773
1083
|
return sendHtml(
|
|
774
1084
|
res,
|
|
775
1085
|
403,
|
|
@@ -801,7 +1111,7 @@ var AuthorizationServer = class {
|
|
|
801
1111
|
user,
|
|
802
1112
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
803
1113
|
roles: [...membership?.roles ?? []],
|
|
804
|
-
permissions:
|
|
1114
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
805
1115
|
claims: {}
|
|
806
1116
|
};
|
|
807
1117
|
const code = randomToken();
|
|
@@ -817,24 +1127,27 @@ var AuthorizationServer = class {
|
|
|
817
1127
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
818
1128
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
819
1129
|
});
|
|
1130
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
820
1131
|
this.emit("user.authenticated", user);
|
|
821
1132
|
const target = new URL(request.redirectUri);
|
|
822
1133
|
target.searchParams.set("code", code);
|
|
823
1134
|
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
824
1135
|
redirect(res, target.toString());
|
|
825
1136
|
}
|
|
826
|
-
async token(req, res,
|
|
1137
|
+
async token(req, res, form2) {
|
|
827
1138
|
try {
|
|
828
|
-
const clientId = clientIdFrom(req,
|
|
829
|
-
const grantType =
|
|
1139
|
+
const clientId = clientIdFrom(req, form2);
|
|
1140
|
+
const grantType = form2.grant_type;
|
|
830
1141
|
if (grantType === "client_credentials") {
|
|
831
|
-
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req,
|
|
1142
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
|
|
832
1143
|
}
|
|
833
1144
|
let grant;
|
|
834
1145
|
if (grantType === "authorization_code") {
|
|
835
|
-
grant = this.redeemCode(
|
|
1146
|
+
grant = this.redeemCode(form2, clientId);
|
|
1147
|
+
this.observe("session.sign-in");
|
|
836
1148
|
} else if (grantType === "refresh_token") {
|
|
837
|
-
grant = this.redeemRefreshToken(
|
|
1149
|
+
grant = this.redeemRefreshToken(form2, clientId);
|
|
1150
|
+
this.observe("session.refresh");
|
|
838
1151
|
} else {
|
|
839
1152
|
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
840
1153
|
}
|
|
@@ -846,14 +1159,14 @@ var AuthorizationServer = class {
|
|
|
846
1159
|
throw error;
|
|
847
1160
|
}
|
|
848
1161
|
}
|
|
849
|
-
async clientCredentials(clientId, clientSecret,
|
|
1162
|
+
async clientCredentials(clientId, clientSecret, form2) {
|
|
850
1163
|
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
851
1164
|
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
852
1165
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
853
1166
|
}
|
|
854
|
-
const requested = (
|
|
855
|
-
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
856
|
-
const audience = (
|
|
1167
|
+
const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
|
|
1168
|
+
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1169
|
+
const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
|
|
857
1170
|
return {
|
|
858
1171
|
access_token: await this.testkit.m2mToken({
|
|
859
1172
|
clientId,
|
|
@@ -873,8 +1186,8 @@ var AuthorizationServer = class {
|
|
|
873
1186
|
this.refreshTokens.clear();
|
|
874
1187
|
this.signedUpUsers.clear();
|
|
875
1188
|
}
|
|
876
|
-
redeemCode(
|
|
877
|
-
const code =
|
|
1189
|
+
redeemCode(form2, clientId) {
|
|
1190
|
+
const code = form2.code ?? "";
|
|
878
1191
|
const pending = this.codes.get(code);
|
|
879
1192
|
this.codes.delete(code);
|
|
880
1193
|
if (!pending || pending.expiresAt < Date.now()) {
|
|
@@ -883,20 +1196,20 @@ var AuthorizationServer = class {
|
|
|
883
1196
|
if (pending.clientId !== clientId) {
|
|
884
1197
|
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
885
1198
|
}
|
|
886
|
-
if (
|
|
1199
|
+
if (form2.redirect_uri !== pending.redirectUri) {
|
|
887
1200
|
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
888
1201
|
}
|
|
889
1202
|
if (pending.codeChallenge) {
|
|
890
|
-
const verifier =
|
|
891
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1203
|
+
const verifier = form2.code_verifier ?? "";
|
|
1204
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
892
1205
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
893
1206
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
894
1207
|
}
|
|
895
1208
|
}
|
|
896
1209
|
return pending;
|
|
897
1210
|
}
|
|
898
|
-
redeemRefreshToken(
|
|
899
|
-
const token =
|
|
1211
|
+
redeemRefreshToken(form2, clientId) {
|
|
1212
|
+
const token = form2.refresh_token ?? "";
|
|
900
1213
|
const grant = this.refreshTokens.get(token);
|
|
901
1214
|
this.refreshTokens.delete(token);
|
|
902
1215
|
if (!grant) {
|
|
@@ -918,7 +1231,8 @@ var AuthorizationServer = class {
|
|
|
918
1231
|
scopes: grant.scope,
|
|
919
1232
|
clientId: grant.clientId,
|
|
920
1233
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
921
|
-
authTime: grant.authTime
|
|
1234
|
+
authTime: grant.authTime,
|
|
1235
|
+
featureFlags: featureFlagsFor(this.seed, scenario2.organization?.code ?? null)
|
|
922
1236
|
}),
|
|
923
1237
|
expires_in: this.testkit.accessTokenLifetime,
|
|
924
1238
|
scope: grant.scope.join(" "),
|
|
@@ -969,11 +1283,13 @@ var AuthorizationServer = class {
|
|
|
969
1283
|
phone: null
|
|
970
1284
|
});
|
|
971
1285
|
}
|
|
972
|
-
revoke(res,
|
|
973
|
-
if (
|
|
1286
|
+
revoke(res, form2) {
|
|
1287
|
+
if (form2.token) this.refreshTokens.delete(form2.token);
|
|
1288
|
+
this.observe("session.revoke");
|
|
974
1289
|
sendJson(res, 200, {});
|
|
975
1290
|
}
|
|
976
1291
|
logout(res, params) {
|
|
1292
|
+
this.observe("session.sign-out");
|
|
977
1293
|
const target = params.get("redirect");
|
|
978
1294
|
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
979
1295
|
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
@@ -985,6 +1301,8 @@ var AuthorizationServer = class {
|
|
|
985
1301
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
986
1302
|
if (!this.signedUpUsers.has(user.id)) {
|
|
987
1303
|
this.signedUpUsers.set(user.id, user);
|
|
1304
|
+
this.observe("identity.unseeded");
|
|
1305
|
+
if (this.directory) this.seed.users.push(user);
|
|
988
1306
|
this.emit("user.created", user);
|
|
989
1307
|
}
|
|
990
1308
|
return this.signedUpUsers.get(user.id);
|
|
@@ -1037,24 +1355,24 @@ function decodeRequest(value) {
|
|
|
1037
1355
|
}
|
|
1038
1356
|
return request;
|
|
1039
1357
|
}
|
|
1040
|
-
function clientIdFrom(req,
|
|
1358
|
+
function clientIdFrom(req, form2) {
|
|
1041
1359
|
const header = req.headers.authorization ?? "";
|
|
1042
1360
|
if (header.startsWith("Basic ")) {
|
|
1043
1361
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1044
1362
|
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
1045
1363
|
if (id) return id;
|
|
1046
1364
|
}
|
|
1047
|
-
if (
|
|
1365
|
+
if (form2.client_id) return form2.client_id;
|
|
1048
1366
|
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
1049
1367
|
}
|
|
1050
|
-
function clientSecretFrom(req,
|
|
1368
|
+
function clientSecretFrom(req, form2) {
|
|
1051
1369
|
const header = req.headers.authorization ?? "";
|
|
1052
1370
|
if (header.startsWith("Basic ")) {
|
|
1053
1371
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1054
1372
|
const index = decoded.indexOf(":");
|
|
1055
1373
|
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1056
1374
|
}
|
|
1057
|
-
return
|
|
1375
|
+
return form2.client_secret ?? null;
|
|
1058
1376
|
}
|
|
1059
1377
|
function redirectWithError(res, request, error, description) {
|
|
1060
1378
|
const target = new URL(request.redirectUri);
|
|
@@ -1072,7 +1390,7 @@ function isHttpUrl(value) {
|
|
|
1072
1390
|
}
|
|
1073
1391
|
}
|
|
1074
1392
|
function randomToken() {
|
|
1075
|
-
return
|
|
1393
|
+
return randomBytes2(32).toString("base64url");
|
|
1076
1394
|
}
|
|
1077
1395
|
function safeEqual(a, b) {
|
|
1078
1396
|
const left = Buffer.from(a);
|
|
@@ -1096,6 +1414,703 @@ function sendJson(res, status, body) {
|
|
|
1096
1414
|
res.end(JSON.stringify(body));
|
|
1097
1415
|
}
|
|
1098
1416
|
|
|
1417
|
+
// src/account.ts
|
|
1418
|
+
var DEFAULT_PAGE_SIZE = 10;
|
|
1419
|
+
var AccountApi = class {
|
|
1420
|
+
constructor(testkit, directory) {
|
|
1421
|
+
this.testkit = testkit;
|
|
1422
|
+
this.directory = directory;
|
|
1423
|
+
}
|
|
1424
|
+
testkit;
|
|
1425
|
+
directory;
|
|
1426
|
+
async handle(req, res, url) {
|
|
1427
|
+
if (!url.pathname.startsWith("/account_api/v1/")) return false;
|
|
1428
|
+
if ((req.method ?? "GET") !== "GET") {
|
|
1429
|
+
sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
|
|
1430
|
+
return true;
|
|
1431
|
+
}
|
|
1432
|
+
const header = req.headers.authorization ?? "";
|
|
1433
|
+
let token;
|
|
1434
|
+
try {
|
|
1435
|
+
if (!header.startsWith("Bearer ")) throw new Error("missing");
|
|
1436
|
+
token = await this.testkit.verify(header.slice(7));
|
|
1437
|
+
} catch {
|
|
1438
|
+
sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
|
|
1439
|
+
return true;
|
|
1440
|
+
}
|
|
1441
|
+
if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
|
|
1442
|
+
sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
|
|
1443
|
+
return true;
|
|
1444
|
+
}
|
|
1445
|
+
const userId = token.sub;
|
|
1446
|
+
const orgCode = typeof token.org_code === "string" ? token.org_code : null;
|
|
1447
|
+
const path = url.pathname.slice("/account_api/v1/".length);
|
|
1448
|
+
const d = this.directory;
|
|
1449
|
+
const membership = orgCode ? d.membership(userId, orgCode) : void 0;
|
|
1450
|
+
if (path === "permissions") {
|
|
1451
|
+
const items = effectivePermissions(d.seed, membership).map((key) => {
|
|
1452
|
+
const p = d.ensurePermission(key);
|
|
1453
|
+
return { id: p.id, name: p.name, key: p.key };
|
|
1454
|
+
});
|
|
1455
|
+
sendPage(res, url, "permissions", items, { org_code: orgCode });
|
|
1456
|
+
return true;
|
|
1457
|
+
}
|
|
1458
|
+
if (path.startsWith("permission/")) {
|
|
1459
|
+
const key = decodeURIComponent(path.slice("permission/".length));
|
|
1460
|
+
sendJson2(res, 200, {
|
|
1461
|
+
data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
|
|
1462
|
+
});
|
|
1463
|
+
return true;
|
|
1464
|
+
}
|
|
1465
|
+
if (path === "roles") {
|
|
1466
|
+
const items = (membership?.roles ?? []).map((key) => {
|
|
1467
|
+
const r = d.ensureRole(key);
|
|
1468
|
+
return { id: r.id, name: r.name, key: r.key };
|
|
1469
|
+
});
|
|
1470
|
+
sendPage(res, url, "roles", items, { org_code: orgCode });
|
|
1471
|
+
return true;
|
|
1472
|
+
}
|
|
1473
|
+
if (path === "feature_flags") {
|
|
1474
|
+
const items = d.seed.featureFlags.map((flag) => ({
|
|
1475
|
+
id: flag.id,
|
|
1476
|
+
name: flag.name,
|
|
1477
|
+
key: flag.key,
|
|
1478
|
+
type: flag.type,
|
|
1479
|
+
value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
|
|
1480
|
+
}));
|
|
1481
|
+
sendPage(res, url, "feature_flags", items, {});
|
|
1482
|
+
return true;
|
|
1483
|
+
}
|
|
1484
|
+
if (path === "properties") {
|
|
1485
|
+
const values = d.seed.userProperties[userId] ?? {};
|
|
1486
|
+
const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
|
|
1487
|
+
sendPage(res, url, "properties", items, {});
|
|
1488
|
+
return true;
|
|
1489
|
+
}
|
|
1490
|
+
if (path === "entitlements" || path.startsWith("entitlement")) {
|
|
1491
|
+
const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
|
|
1492
|
+
const entitlements = (plan?.entitlements ?? []).map((e) => ({
|
|
1493
|
+
id: e.id,
|
|
1494
|
+
fixed_charge: e.fixedCharge,
|
|
1495
|
+
price_name: e.priceName,
|
|
1496
|
+
unit_amount: e.unitAmount,
|
|
1497
|
+
feature_key: e.featureKey,
|
|
1498
|
+
feature_name: e.featureName,
|
|
1499
|
+
entitlement_limit_max: e.limitMax,
|
|
1500
|
+
entitlement_limit_min: e.limitMin
|
|
1501
|
+
}));
|
|
1502
|
+
if (path === "entitlements") {
|
|
1503
|
+
const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
|
|
1504
|
+
sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
|
|
1505
|
+
return true;
|
|
1506
|
+
}
|
|
1507
|
+
const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
|
|
1508
|
+
const entitlement = entitlements.find((e) => e.feature_key === key);
|
|
1509
|
+
if (!entitlement) {
|
|
1510
|
+
sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
|
|
1511
|
+
} else {
|
|
1512
|
+
sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
|
|
1513
|
+
}
|
|
1514
|
+
return true;
|
|
1515
|
+
}
|
|
1516
|
+
if (path === "portal_link") {
|
|
1517
|
+
sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
|
|
1518
|
+
return true;
|
|
1519
|
+
}
|
|
1520
|
+
sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
|
|
1521
|
+
return true;
|
|
1522
|
+
}
|
|
1523
|
+
};
|
|
1524
|
+
function sendPage(res, url, field, items, extra) {
|
|
1525
|
+
const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
|
|
1526
|
+
const after = url.searchParams.get("starting_after");
|
|
1527
|
+
const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
|
|
1528
|
+
const page = items.slice(start, start + size);
|
|
1529
|
+
const hasMore = start + size < items.length;
|
|
1530
|
+
sendJson2(res, 200, {
|
|
1531
|
+
data: { ...extra, [field]: page },
|
|
1532
|
+
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
1533
|
+
});
|
|
1534
|
+
}
|
|
1535
|
+
function errors(code, message) {
|
|
1536
|
+
return { errors: [{ code, message }] };
|
|
1537
|
+
}
|
|
1538
|
+
function sendJson2(res, status, body) {
|
|
1539
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1540
|
+
res.end(JSON.stringify(body));
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
// src/directory.ts
|
|
1544
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1545
|
+
var Directory = class {
|
|
1546
|
+
constructor(seed) {
|
|
1547
|
+
this.seed = seed;
|
|
1548
|
+
this.snapshot = JSON.stringify(seed);
|
|
1549
|
+
}
|
|
1550
|
+
seed;
|
|
1551
|
+
userMeta = /* @__PURE__ */ new Map();
|
|
1552
|
+
orgMeta = /* @__PURE__ */ new Map();
|
|
1553
|
+
snapshot;
|
|
1554
|
+
restore() {
|
|
1555
|
+
const original = JSON.parse(this.snapshot);
|
|
1556
|
+
for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
|
|
1557
|
+
this.seed[key].splice(0, this.seed[key].length, ...original[key]);
|
|
1558
|
+
}
|
|
1559
|
+
this.userMeta.clear();
|
|
1560
|
+
this.orgMeta.clear();
|
|
1561
|
+
}
|
|
1562
|
+
/** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
|
|
1563
|
+
load(next) {
|
|
1564
|
+
for (const key of Object.keys(next)) {
|
|
1565
|
+
const current = this.seed[key];
|
|
1566
|
+
if (Array.isArray(current)) {
|
|
1567
|
+
current.splice(0, current.length, ...next[key]);
|
|
1568
|
+
} else {
|
|
1569
|
+
const record = current;
|
|
1570
|
+
for (const name of Object.keys(record)) delete record[name];
|
|
1571
|
+
Object.assign(record, next[key]);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
this.snapshot = JSON.stringify(this.seed);
|
|
1575
|
+
this.userMeta.clear();
|
|
1576
|
+
this.orgMeta.clear();
|
|
1577
|
+
}
|
|
1578
|
+
user(id) {
|
|
1579
|
+
return this.seed.users.find((user) => user.id === id);
|
|
1580
|
+
}
|
|
1581
|
+
meta(user) {
|
|
1582
|
+
let meta = this.userMeta.get(user.id);
|
|
1583
|
+
if (!meta) {
|
|
1584
|
+
meta = {
|
|
1585
|
+
providedId: null,
|
|
1586
|
+
isSuspended: false,
|
|
1587
|
+
isPasswordResetRequested: false,
|
|
1588
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1589
|
+
totalSignIns: 0,
|
|
1590
|
+
lastSignedIn: null
|
|
1591
|
+
};
|
|
1592
|
+
this.userMeta.set(user.id, meta);
|
|
1593
|
+
}
|
|
1594
|
+
return meta;
|
|
1595
|
+
}
|
|
1596
|
+
isSuspended(userId) {
|
|
1597
|
+
return this.userMeta.get(userId)?.isSuspended ?? false;
|
|
1598
|
+
}
|
|
1599
|
+
recordSignIn(user, organizationCode) {
|
|
1600
|
+
const meta = this.meta(user);
|
|
1601
|
+
meta.totalSignIns += 1;
|
|
1602
|
+
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
1603
|
+
void organizationCode;
|
|
1604
|
+
}
|
|
1605
|
+
createUser(input) {
|
|
1606
|
+
const user = createKindeUser({
|
|
1607
|
+
id: `kp_${randomBytes3(16).toString("hex")}`,
|
|
1608
|
+
email: input.email ?? null,
|
|
1609
|
+
givenName: input.givenName ?? null,
|
|
1610
|
+
familyName: input.familyName ?? null,
|
|
1611
|
+
picture: input.picture ?? null
|
|
1612
|
+
});
|
|
1613
|
+
this.seed.users.push(user);
|
|
1614
|
+
this.meta(user).providedId = input.providedId ?? null;
|
|
1615
|
+
return user;
|
|
1616
|
+
}
|
|
1617
|
+
deleteUser(id) {
|
|
1618
|
+
const index = this.seed.users.findIndex((user) => user.id === id);
|
|
1619
|
+
if (index < 0) return false;
|
|
1620
|
+
this.seed.users.splice(index, 1);
|
|
1621
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1622
|
+
if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
|
|
1623
|
+
}
|
|
1624
|
+
this.userMeta.delete(id);
|
|
1625
|
+
return true;
|
|
1626
|
+
}
|
|
1627
|
+
organization(code) {
|
|
1628
|
+
return this.seed.organizations.find((org) => org.code === code);
|
|
1629
|
+
}
|
|
1630
|
+
orgInfo(org) {
|
|
1631
|
+
let meta = this.orgMeta.get(org.code);
|
|
1632
|
+
if (!meta) {
|
|
1633
|
+
meta = {
|
|
1634
|
+
externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
|
|
1635
|
+
handle: slug(org.name),
|
|
1636
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1637
|
+
isAllowRegistrations: false
|
|
1638
|
+
};
|
|
1639
|
+
this.orgMeta.set(org.code, meta);
|
|
1640
|
+
}
|
|
1641
|
+
return meta;
|
|
1642
|
+
}
|
|
1643
|
+
createOrganization(input) {
|
|
1644
|
+
const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
|
|
1645
|
+
this.seed.organizations.push(org);
|
|
1646
|
+
const meta = this.orgInfo(org);
|
|
1647
|
+
meta.externalId = input.externalId ?? null;
|
|
1648
|
+
if (input.handle) meta.handle = input.handle;
|
|
1649
|
+
return org;
|
|
1650
|
+
}
|
|
1651
|
+
deleteOrganization(code) {
|
|
1652
|
+
const index = this.seed.organizations.findIndex((org) => org.code === code);
|
|
1653
|
+
if (index < 0) return false;
|
|
1654
|
+
this.seed.organizations.splice(index, 1);
|
|
1655
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1656
|
+
if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
|
|
1657
|
+
}
|
|
1658
|
+
this.orgMeta.delete(code);
|
|
1659
|
+
return true;
|
|
1660
|
+
}
|
|
1661
|
+
membership(userId, organizationCode) {
|
|
1662
|
+
return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1663
|
+
}
|
|
1664
|
+
addMembership(userId, organizationCode, roles = [], permissions = []) {
|
|
1665
|
+
const existing = this.membership(userId, organizationCode);
|
|
1666
|
+
if (existing) return existing;
|
|
1667
|
+
const membership = createMembership({ userId, organizationCode, roles, permissions });
|
|
1668
|
+
this.seed.memberships.push(membership);
|
|
1669
|
+
for (const key of roles) this.ensureRole(key);
|
|
1670
|
+
for (const key of permissions) this.ensurePermission(key);
|
|
1671
|
+
return membership;
|
|
1672
|
+
}
|
|
1673
|
+
removeMembership(userId, organizationCode) {
|
|
1674
|
+
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1675
|
+
if (index < 0) return false;
|
|
1676
|
+
this.seed.memberships.splice(index, 1);
|
|
1677
|
+
return true;
|
|
1678
|
+
}
|
|
1679
|
+
role(idOrKey) {
|
|
1680
|
+
return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
|
|
1681
|
+
}
|
|
1682
|
+
permission(idOrKey) {
|
|
1683
|
+
return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
|
|
1684
|
+
}
|
|
1685
|
+
ensureRole(key, extra = {}) {
|
|
1686
|
+
const existing = this.role(key);
|
|
1687
|
+
if (existing) return existing;
|
|
1688
|
+
const role = roleRecord(key, extra);
|
|
1689
|
+
this.seed.roles.push(role);
|
|
1690
|
+
return role;
|
|
1691
|
+
}
|
|
1692
|
+
ensurePermission(key, extra = {}) {
|
|
1693
|
+
const existing = this.permission(key);
|
|
1694
|
+
if (existing) return existing;
|
|
1695
|
+
const permission = permissionRecord(key, extra);
|
|
1696
|
+
this.seed.permissions.push(permission);
|
|
1697
|
+
return permission;
|
|
1698
|
+
}
|
|
1699
|
+
deleteRole(id) {
|
|
1700
|
+
const role = this.role(id);
|
|
1701
|
+
if (!role) return void 0;
|
|
1702
|
+
this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
|
|
1703
|
+
for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
|
|
1704
|
+
return role;
|
|
1705
|
+
}
|
|
1706
|
+
deletePermission(id) {
|
|
1707
|
+
const permission = this.permission(id);
|
|
1708
|
+
if (!permission) return void 0;
|
|
1709
|
+
this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
|
|
1710
|
+
for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
|
|
1711
|
+
for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
|
|
1712
|
+
return permission;
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
|
|
1716
|
+
// src/management.ts
|
|
1717
|
+
var OK = { code: "OK", message: "Success" };
|
|
1718
|
+
var DEFAULT_PAGE_SIZE2 = 10;
|
|
1719
|
+
var MAX_PAGE_SIZE = 500;
|
|
1720
|
+
var ManagementApi = class {
|
|
1721
|
+
constructor(testkit, directory, webhooks) {
|
|
1722
|
+
this.testkit = testkit;
|
|
1723
|
+
this.directory = directory;
|
|
1724
|
+
this.webhooks = webhooks;
|
|
1725
|
+
this.register();
|
|
1726
|
+
}
|
|
1727
|
+
testkit;
|
|
1728
|
+
directory;
|
|
1729
|
+
webhooks;
|
|
1730
|
+
routes = [];
|
|
1731
|
+
async handle(req, res, url, readBody) {
|
|
1732
|
+
if (!url.pathname.startsWith("/api/v1/")) return false;
|
|
1733
|
+
const method = req.method ?? "GET";
|
|
1734
|
+
const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
1735
|
+
if (!route) {
|
|
1736
|
+
sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
|
|
1737
|
+
return true;
|
|
1738
|
+
}
|
|
1739
|
+
const token = await this.authenticate(req.headers.authorization);
|
|
1740
|
+
if ("error" in token) {
|
|
1741
|
+
sendJson3(res, 403, errors2(token.code, token.error));
|
|
1742
|
+
return true;
|
|
1743
|
+
}
|
|
1744
|
+
const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
|
|
1745
|
+
if (granted.length > 0 && !granted.includes(route.scope)) {
|
|
1746
|
+
sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
|
|
1747
|
+
return true;
|
|
1748
|
+
}
|
|
1749
|
+
const match = route.pattern.exec(url.pathname);
|
|
1750
|
+
const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
|
|
1751
|
+
const body = method === "GET" || method === "DELETE" ? {} : await readBody();
|
|
1752
|
+
const [status, payload] = await route.handler({ params, query: url.searchParams, body });
|
|
1753
|
+
sendJson3(res, status, payload);
|
|
1754
|
+
return true;
|
|
1755
|
+
}
|
|
1756
|
+
async authenticate(header) {
|
|
1757
|
+
if (!header?.startsWith("Bearer ")) {
|
|
1758
|
+
return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
|
|
1759
|
+
}
|
|
1760
|
+
let payload;
|
|
1761
|
+
try {
|
|
1762
|
+
payload = await this.testkit.verify(header.slice(7));
|
|
1763
|
+
} catch {
|
|
1764
|
+
return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
|
|
1765
|
+
}
|
|
1766
|
+
const audience = `${this.testkit.issuer}/api`;
|
|
1767
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
1768
|
+
if (!aud.includes(audience)) {
|
|
1769
|
+
return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
|
|
1770
|
+
}
|
|
1771
|
+
if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
|
|
1772
|
+
return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
|
|
1773
|
+
}
|
|
1774
|
+
return { payload };
|
|
1775
|
+
}
|
|
1776
|
+
route(method, path, scope, handler) {
|
|
1777
|
+
const keys = [];
|
|
1778
|
+
const pattern = new RegExp(
|
|
1779
|
+
`^${path.replace(/\{(\w+)\}/g, (_, key) => {
|
|
1780
|
+
keys.push(key);
|
|
1781
|
+
return "([^/]+)";
|
|
1782
|
+
})}$`
|
|
1783
|
+
);
|
|
1784
|
+
this.routes.push({ method, pattern, keys, scope, handler });
|
|
1785
|
+
}
|
|
1786
|
+
register() {
|
|
1787
|
+
const d = this.directory;
|
|
1788
|
+
this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
|
|
1789
|
+
let users = [...d.seed.users];
|
|
1790
|
+
const userId = query.get("user_id");
|
|
1791
|
+
const email = query.get("email")?.toLowerCase();
|
|
1792
|
+
if (userId) users = users.filter((u) => u.id === userId);
|
|
1793
|
+
if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
|
|
1794
|
+
const page = paginate(users, query);
|
|
1795
|
+
return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
|
|
1796
|
+
});
|
|
1797
|
+
this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
|
|
1798
|
+
const user = d.user(query.get("id") ?? "");
|
|
1799
|
+
return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
|
|
1800
|
+
});
|
|
1801
|
+
this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
|
|
1802
|
+
const profile = body.profile ?? {};
|
|
1803
|
+
const identities = Array.isArray(body.identities) ? body.identities : [];
|
|
1804
|
+
const emailIdentity = identities.find((i) => i.type === "email");
|
|
1805
|
+
const email = (emailIdentity?.details ?? {}).email;
|
|
1806
|
+
if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
|
|
1807
|
+
return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
|
|
1808
|
+
}
|
|
1809
|
+
const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
|
|
1810
|
+
if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
|
|
1811
|
+
const user = d.createUser({
|
|
1812
|
+
email: typeof email === "string" ? email : null,
|
|
1813
|
+
givenName: str(profile.given_name),
|
|
1814
|
+
familyName: str(profile.family_name),
|
|
1815
|
+
picture: str(profile.picture),
|
|
1816
|
+
providedId: str(body.provided_id)
|
|
1817
|
+
});
|
|
1818
|
+
if (orgCode) d.addMembership(user.id, orgCode);
|
|
1819
|
+
this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
|
|
1820
|
+
return [
|
|
1821
|
+
200,
|
|
1822
|
+
{ id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
|
|
1823
|
+
];
|
|
1824
|
+
});
|
|
1825
|
+
this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
|
|
1826
|
+
const user = d.user(query.get("id") ?? "");
|
|
1827
|
+
if (!user) return notFound("USER_INVALID", "No user has that id.");
|
|
1828
|
+
if (typeof body.given_name === "string") user.givenName = body.given_name;
|
|
1829
|
+
if (typeof body.family_name === "string") user.familyName = body.family_name;
|
|
1830
|
+
if (typeof body.picture === "string") user.picture = body.picture;
|
|
1831
|
+
const meta = d.meta(user);
|
|
1832
|
+
if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
|
|
1833
|
+
if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
|
|
1834
|
+
if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
|
|
1835
|
+
this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
|
|
1836
|
+
return [
|
|
1837
|
+
200,
|
|
1838
|
+
{
|
|
1839
|
+
id: user.id,
|
|
1840
|
+
given_name: user.givenName,
|
|
1841
|
+
family_name: user.familyName,
|
|
1842
|
+
email: user.email,
|
|
1843
|
+
is_suspended: meta.isSuspended,
|
|
1844
|
+
is_password_reset_requested: meta.isPasswordResetRequested,
|
|
1845
|
+
picture: user.picture
|
|
1846
|
+
}
|
|
1847
|
+
];
|
|
1848
|
+
});
|
|
1849
|
+
this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
|
|
1850
|
+
const id = query.get("id") ?? "";
|
|
1851
|
+
if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
|
|
1852
|
+
this.webhooks.emit("user.deleted", { user: { id } });
|
|
1853
|
+
return [200, OK];
|
|
1854
|
+
});
|
|
1855
|
+
this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
|
|
1856
|
+
const page = paginate(d.seed.organizations, query);
|
|
1857
|
+
return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
|
|
1858
|
+
});
|
|
1859
|
+
this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
|
|
1860
|
+
const org = d.organization(query.get("code") ?? "");
|
|
1861
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1862
|
+
const meta = d.orgInfo(org);
|
|
1863
|
+
return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
|
|
1864
|
+
});
|
|
1865
|
+
this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
|
|
1866
|
+
if (typeof body.name !== "string" || body.name.trim() === "") {
|
|
1867
|
+
return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
|
|
1868
|
+
}
|
|
1869
|
+
const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
|
|
1870
|
+
if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
|
|
1871
|
+
this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
|
|
1872
|
+
return [200, { ...OK, organization: { code: org.code } }];
|
|
1873
|
+
});
|
|
1874
|
+
this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
|
|
1875
|
+
const org = d.organization(params.org_code);
|
|
1876
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1877
|
+
const meta = d.orgInfo(org);
|
|
1878
|
+
if (typeof body.name === "string") org.name = body.name;
|
|
1879
|
+
if (typeof body.external_id === "string") meta.externalId = body.external_id;
|
|
1880
|
+
if (typeof body.handle === "string") meta.handle = body.handle;
|
|
1881
|
+
if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
|
|
1882
|
+
this.webhooks.emit("organization.updated", {
|
|
1883
|
+
organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
|
|
1884
|
+
});
|
|
1885
|
+
return [200, OK];
|
|
1886
|
+
});
|
|
1887
|
+
this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
|
|
1888
|
+
if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1889
|
+
this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
|
|
1890
|
+
return [200, OK];
|
|
1891
|
+
});
|
|
1892
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
|
|
1893
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1894
|
+
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);
|
|
1895
|
+
const page = paginate(members, query);
|
|
1896
|
+
return [
|
|
1897
|
+
200,
|
|
1898
|
+
{
|
|
1899
|
+
...OK,
|
|
1900
|
+
organization_users: page.items.map(({ membership, user }) => ({
|
|
1901
|
+
id: user.id,
|
|
1902
|
+
email: user.email,
|
|
1903
|
+
full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
|
|
1904
|
+
last_name: user.familyName,
|
|
1905
|
+
first_name: user.givenName,
|
|
1906
|
+
picture: user.picture,
|
|
1907
|
+
joined_on: d.meta(user).createdOn,
|
|
1908
|
+
last_accessed_on: d.meta(user).lastSignedIn,
|
|
1909
|
+
is_suspended: d.meta(user).isSuspended,
|
|
1910
|
+
roles: [...membership.roles]
|
|
1911
|
+
})),
|
|
1912
|
+
next_token: page.nextToken
|
|
1913
|
+
}
|
|
1914
|
+
];
|
|
1915
|
+
});
|
|
1916
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
|
|
1917
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1918
|
+
const users = Array.isArray(body.users) ? body.users : [];
|
|
1919
|
+
const added = [];
|
|
1920
|
+
const blocked = [];
|
|
1921
|
+
for (const entry of users) {
|
|
1922
|
+
const id = typeof entry.id === "string" ? entry.id : "";
|
|
1923
|
+
if (!d.user(id)) {
|
|
1924
|
+
blocked.push(id);
|
|
1925
|
+
continue;
|
|
1926
|
+
}
|
|
1927
|
+
d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
|
|
1928
|
+
added.push(id);
|
|
1929
|
+
}
|
|
1930
|
+
return [200, { ...OK, users_added: added, users_blocked: blocked }];
|
|
1931
|
+
});
|
|
1932
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
|
|
1933
|
+
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}.`);
|
|
1934
|
+
});
|
|
1935
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
|
|
1936
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1937
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1938
|
+
const roles = membership.roles.map((key) => d.ensureRole(key));
|
|
1939
|
+
return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
|
|
1940
|
+
});
|
|
1941
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
|
|
1942
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1943
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1944
|
+
const role = d.role(str(body.role_id) ?? "");
|
|
1945
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1946
|
+
if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
|
|
1947
|
+
return [200, OK];
|
|
1948
|
+
});
|
|
1949
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
|
|
1950
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1951
|
+
const role = d.role(params.role_id);
|
|
1952
|
+
if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
|
|
1953
|
+
membership.roles = membership.roles.filter((key) => key !== role.key);
|
|
1954
|
+
return [200, OK];
|
|
1955
|
+
});
|
|
1956
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
|
|
1957
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1958
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1959
|
+
const permissions = effectivePermissions(d.seed, membership).map((key) => {
|
|
1960
|
+
const permission = d.ensurePermission(key);
|
|
1961
|
+
const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
|
|
1962
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
|
|
1963
|
+
});
|
|
1964
|
+
return [200, { ...OK, permissions }];
|
|
1965
|
+
});
|
|
1966
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
|
|
1967
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1968
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1969
|
+
const permission = d.permission(str(body.permission_id) ?? "");
|
|
1970
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1971
|
+
if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
|
|
1972
|
+
return [200, OK];
|
|
1973
|
+
});
|
|
1974
|
+
this.route(
|
|
1975
|
+
"DELETE",
|
|
1976
|
+
"/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
|
|
1977
|
+
"delete:organization_user_permissions",
|
|
1978
|
+
({ params }) => {
|
|
1979
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1980
|
+
const permission = d.permission(params.permission_id);
|
|
1981
|
+
if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
|
|
1982
|
+
membership.permissions = membership.permissions.filter((key) => key !== permission.key);
|
|
1983
|
+
return [200, OK];
|
|
1984
|
+
}
|
|
1985
|
+
);
|
|
1986
|
+
this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
|
|
1987
|
+
const page = paginate(d.seed.roles, query);
|
|
1988
|
+
return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
|
|
1989
|
+
});
|
|
1990
|
+
this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
|
|
1991
|
+
const key = str(body.key);
|
|
1992
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
|
|
1993
|
+
if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
|
|
1994
|
+
const role = d.ensureRole(key, {
|
|
1995
|
+
name: str(body.name) ?? void 0,
|
|
1996
|
+
description: str(body.description) ?? void 0,
|
|
1997
|
+
isDefault: body.is_default_role === true
|
|
1998
|
+
});
|
|
1999
|
+
this.webhooks.emit("role.created", {
|
|
2000
|
+
role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
|
|
2001
|
+
});
|
|
2002
|
+
return [201, { ...OK, role: { id: role.id } }];
|
|
2003
|
+
});
|
|
2004
|
+
this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
|
|
2005
|
+
const role = d.role(params.role_id);
|
|
2006
|
+
return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
|
|
2007
|
+
});
|
|
2008
|
+
this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
|
|
2009
|
+
const role = d.deleteRole(params.role_id);
|
|
2010
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
2011
|
+
this.webhooks.emit("role.deleted", { role: { id: role.id } });
|
|
2012
|
+
return [200, OK];
|
|
2013
|
+
});
|
|
2014
|
+
this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
|
|
2015
|
+
const role = d.role(params.role_id);
|
|
2016
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
2017
|
+
return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
|
|
2018
|
+
});
|
|
2019
|
+
this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
|
|
2020
|
+
const page = paginate(d.seed.permissions, query);
|
|
2021
|
+
return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
|
|
2022
|
+
});
|
|
2023
|
+
this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
|
|
2024
|
+
const key = str(body.key);
|
|
2025
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
|
|
2026
|
+
if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
|
|
2027
|
+
const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
|
|
2028
|
+
this.webhooks.emit("permission.created", {
|
|
2029
|
+
permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
|
|
2030
|
+
});
|
|
2031
|
+
return [201, OK];
|
|
2032
|
+
});
|
|
2033
|
+
this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
|
|
2034
|
+
const permission = d.deletePermission(params.permission_id);
|
|
2035
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
2036
|
+
this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
|
|
2037
|
+
return [200, OK];
|
|
2038
|
+
});
|
|
2039
|
+
}
|
|
2040
|
+
userListItem(user) {
|
|
2041
|
+
const meta = this.directory.meta(user);
|
|
2042
|
+
return {
|
|
2043
|
+
id: user.id,
|
|
2044
|
+
provided_id: meta.providedId,
|
|
2045
|
+
email: user.email,
|
|
2046
|
+
phone: null,
|
|
2047
|
+
username: null,
|
|
2048
|
+
last_name: user.familyName,
|
|
2049
|
+
first_name: user.givenName,
|
|
2050
|
+
is_suspended: meta.isSuspended,
|
|
2051
|
+
picture: user.picture,
|
|
2052
|
+
total_sign_ins: meta.totalSignIns,
|
|
2053
|
+
failed_sign_ins: 0,
|
|
2054
|
+
last_signed_in: meta.lastSignedIn,
|
|
2055
|
+
created_on: meta.createdOn,
|
|
2056
|
+
organizations: this.organizationsOf(user),
|
|
2057
|
+
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
2058
|
+
};
|
|
2059
|
+
}
|
|
2060
|
+
userDetail(user) {
|
|
2061
|
+
const { email, ...rest } = this.userListItem(user);
|
|
2062
|
+
return { ...rest, preferred_email: email };
|
|
2063
|
+
}
|
|
2064
|
+
organizationsOf(user) {
|
|
2065
|
+
return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
|
|
2066
|
+
}
|
|
2067
|
+
organizationItem(org) {
|
|
2068
|
+
const meta = this.directory.orgInfo(org);
|
|
2069
|
+
return {
|
|
2070
|
+
code: org.code,
|
|
2071
|
+
name: org.name,
|
|
2072
|
+
handle: meta.handle,
|
|
2073
|
+
is_default: false,
|
|
2074
|
+
external_id: meta.externalId,
|
|
2075
|
+
is_auto_membership_enabled: false
|
|
2076
|
+
};
|
|
2077
|
+
}
|
|
2078
|
+
organizationEvent(org) {
|
|
2079
|
+
const meta = this.directory.orgInfo(org);
|
|
2080
|
+
return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
|
|
2081
|
+
}
|
|
2082
|
+
roleItem(role) {
|
|
2083
|
+
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
2084
|
+
}
|
|
2085
|
+
permissionItem(permission) {
|
|
2086
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
2087
|
+
}
|
|
2088
|
+
};
|
|
2089
|
+
function paginate(items, query) {
|
|
2090
|
+
const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
|
|
2091
|
+
const token = query.get("next_token");
|
|
2092
|
+
const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
|
|
2093
|
+
const page = items.slice(offset, offset + size);
|
|
2094
|
+
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
2095
|
+
return { items: page, nextToken: next };
|
|
2096
|
+
}
|
|
2097
|
+
function errors2(code, message) {
|
|
2098
|
+
return { errors: [{ code, message }] };
|
|
2099
|
+
}
|
|
2100
|
+
function notFound(code, message) {
|
|
2101
|
+
return [404, errors2(code, message)];
|
|
2102
|
+
}
|
|
2103
|
+
function str(value) {
|
|
2104
|
+
return typeof value === "string" ? value : null;
|
|
2105
|
+
}
|
|
2106
|
+
function strings(value) {
|
|
2107
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
2108
|
+
}
|
|
2109
|
+
function sendJson3(res, status, body) {
|
|
2110
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
2111
|
+
res.end(JSON.stringify(body));
|
|
2112
|
+
}
|
|
2113
|
+
|
|
1099
2114
|
// src/failures.ts
|
|
1100
2115
|
var MAX_DELAY_MS = 6e4;
|
|
1101
2116
|
var FailureInjector = class {
|
|
@@ -1177,7 +2192,7 @@ function validate(rule) {
|
|
|
1177
2192
|
}
|
|
1178
2193
|
|
|
1179
2194
|
// src/webhooks.ts
|
|
1180
|
-
import { randomBytes as
|
|
2195
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
1181
2196
|
var WEBHOOK_EVENT_TYPES = [
|
|
1182
2197
|
"user.created",
|
|
1183
2198
|
"user.updated",
|
|
@@ -1226,6 +2241,8 @@ var WebhookDispatcher = class {
|
|
|
1226
2241
|
nextEndpoint = 1;
|
|
1227
2242
|
retryDelaysMs;
|
|
1228
2243
|
timeoutMs;
|
|
2244
|
+
/** Set by the server to record coverage. */
|
|
2245
|
+
observe = () => void 0;
|
|
1229
2246
|
addEndpoint(input) {
|
|
1230
2247
|
if (!isHttpUrl2(input.url)) {
|
|
1231
2248
|
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
@@ -1237,6 +2254,14 @@ var WebhookDispatcher = class {
|
|
|
1237
2254
|
this.endpoints.push(endpoint);
|
|
1238
2255
|
return { ...endpoint };
|
|
1239
2256
|
}
|
|
2257
|
+
/** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
|
|
2258
|
+
replaceSeededEndpoints(endpoints) {
|
|
2259
|
+
const seeded = new Set(this.seededEndpoints.map((e) => e.id));
|
|
2260
|
+
this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
|
|
2261
|
+
const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
|
|
2262
|
+
const ids = new Set(added.map((e) => e.id));
|
|
2263
|
+
this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
|
|
2264
|
+
}
|
|
1240
2265
|
removeEndpoint(id) {
|
|
1241
2266
|
const before = this.endpoints.length;
|
|
1242
2267
|
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
@@ -1260,7 +2285,7 @@ var WebhookDispatcher = class {
|
|
|
1260
2285
|
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1261
2286
|
const event = {
|
|
1262
2287
|
data: options.data ?? this.buildData(options),
|
|
1263
|
-
event_id: `event_${
|
|
2288
|
+
event_id: `event_${randomBytes4(16).toString("hex")}`,
|
|
1264
2289
|
event_timestamp: timestamp,
|
|
1265
2290
|
source: options.source ?? "admin",
|
|
1266
2291
|
timestamp,
|
|
@@ -1287,16 +2312,23 @@ var WebhookDispatcher = class {
|
|
|
1287
2312
|
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
1288
2313
|
);
|
|
1289
2314
|
}
|
|
2315
|
+
if (copies > 1) this.observe("webhook.duplicate");
|
|
2316
|
+
if (options.invalid === "stale") this.observe("webhook.stale");
|
|
2317
|
+
else if (options.invalid) this.observe("webhook.forged");
|
|
1290
2318
|
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
1291
2319
|
const signed = await this.testkit.signPayload(
|
|
1292
2320
|
event,
|
|
1293
2321
|
options.invalid === "stale" ? void 0 : options.invalid
|
|
1294
2322
|
);
|
|
1295
2323
|
const jobs = targets.flatMap((target) => {
|
|
1296
|
-
const webhookId = `wh_${
|
|
2324
|
+
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
1297
2325
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1298
2326
|
});
|
|
1299
|
-
|
|
2327
|
+
const deliveries = await Promise.all(jobs);
|
|
2328
|
+
if (!options.invalid) {
|
|
2329
|
+
for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
|
|
2330
|
+
}
|
|
2331
|
+
return deliveries;
|
|
1300
2332
|
}
|
|
1301
2333
|
async deliver(url, webhookId, body, event, copy) {
|
|
1302
2334
|
const delivery = {
|
|
@@ -1374,6 +2406,13 @@ var WebhookDispatcher = class {
|
|
|
1374
2406
|
);
|
|
1375
2407
|
}
|
|
1376
2408
|
}
|
|
2409
|
+
emit(type, data, source = "api") {
|
|
2410
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2411
|
+
void this.send({ type, data, source }).catch(() => void 0);
|
|
2412
|
+
}
|
|
2413
|
+
userEventData(user) {
|
|
2414
|
+
return this.userPayload(user);
|
|
2415
|
+
}
|
|
1377
2416
|
emitForUser(type, user) {
|
|
1378
2417
|
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1379
2418
|
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
@@ -1438,7 +2477,511 @@ function isHttpUrl2(value) {
|
|
|
1438
2477
|
}
|
|
1439
2478
|
}
|
|
1440
2479
|
function sleep(ms) {
|
|
1441
|
-
return new Promise((
|
|
2480
|
+
return new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
2481
|
+
}
|
|
2482
|
+
|
|
2483
|
+
// src/activity.ts
|
|
2484
|
+
var LIMIT = 200;
|
|
2485
|
+
var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
|
|
2486
|
+
var ActivityLog = class {
|
|
2487
|
+
requestLog = [];
|
|
2488
|
+
tokenLog = [];
|
|
2489
|
+
request(entry) {
|
|
2490
|
+
const query = new URLSearchParams(entry.query);
|
|
2491
|
+
for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
|
|
2492
|
+
const search = query.toString();
|
|
2493
|
+
push(this.requestLog, {
|
|
2494
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2495
|
+
method: entry.method,
|
|
2496
|
+
path: search ? `${entry.path}?${search}` : entry.path,
|
|
2497
|
+
status: entry.status,
|
|
2498
|
+
durationMs: entry.durationMs,
|
|
2499
|
+
injected: entry.injected
|
|
2500
|
+
});
|
|
2501
|
+
}
|
|
2502
|
+
token(kind, claims, invalid2, token) {
|
|
2503
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
2504
|
+
push(this.tokenLog, {
|
|
2505
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2506
|
+
kind,
|
|
2507
|
+
subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
|
|
2508
|
+
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
2509
|
+
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
2510
|
+
roles,
|
|
2511
|
+
invalid: invalid2 ?? null,
|
|
2512
|
+
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
2513
|
+
claims,
|
|
2514
|
+
token
|
|
2515
|
+
});
|
|
2516
|
+
}
|
|
2517
|
+
requests() {
|
|
2518
|
+
return [...this.requestLog];
|
|
2519
|
+
}
|
|
2520
|
+
tokens() {
|
|
2521
|
+
return [...this.tokenLog];
|
|
2522
|
+
}
|
|
2523
|
+
reset() {
|
|
2524
|
+
this.requestLog = [];
|
|
2525
|
+
this.tokenLog = [];
|
|
2526
|
+
}
|
|
2527
|
+
};
|
|
2528
|
+
function push(list, entry) {
|
|
2529
|
+
list.push(entry);
|
|
2530
|
+
if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
|
|
2531
|
+
}
|
|
2532
|
+
|
|
2533
|
+
// src/coverage.ts
|
|
2534
|
+
import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
2535
|
+
import { join as join2, resolve as resolve2 } from "path";
|
|
2536
|
+
var COVERAGE_GROUPS = [
|
|
2537
|
+
{
|
|
2538
|
+
name: "Identity",
|
|
2539
|
+
items: [
|
|
2540
|
+
{ id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
|
|
2541
|
+
{ id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
|
|
2542
|
+
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
2543
|
+
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
2544
|
+
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
2545
|
+
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
|
|
2546
|
+
]
|
|
2547
|
+
},
|
|
2548
|
+
{
|
|
2549
|
+
name: "Organizations",
|
|
2550
|
+
items: [
|
|
2551
|
+
{ id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
|
|
2552
|
+
{ id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
|
|
2553
|
+
{ id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
|
|
2554
|
+
{ 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." },
|
|
2555
|
+
{ id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
|
|
2556
|
+
]
|
|
2557
|
+
},
|
|
2558
|
+
{
|
|
2559
|
+
name: "Permissions",
|
|
2560
|
+
items: [
|
|
2561
|
+
{ id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
|
|
2562
|
+
{ 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." },
|
|
2563
|
+
{ id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
|
|
2564
|
+
{ id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
|
|
2565
|
+
{ id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
|
|
2566
|
+
]
|
|
2567
|
+
},
|
|
2568
|
+
{
|
|
2569
|
+
name: "Token validation",
|
|
2570
|
+
items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
|
|
2571
|
+
(kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
|
|
2572
|
+
)
|
|
2573
|
+
},
|
|
2574
|
+
{
|
|
2575
|
+
name: "Sessions",
|
|
2576
|
+
items: [
|
|
2577
|
+
{ id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
|
|
2578
|
+
{ id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
|
|
2579
|
+
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
2580
|
+
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
2581
|
+
{ id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
|
|
2582
|
+
]
|
|
2583
|
+
},
|
|
2584
|
+
{
|
|
2585
|
+
name: "Machine-to-machine",
|
|
2586
|
+
items: [
|
|
2587
|
+
{ id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
|
|
2588
|
+
{ id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
|
|
2589
|
+
{ id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
|
|
2590
|
+
{ id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
|
|
2591
|
+
]
|
|
2592
|
+
},
|
|
2593
|
+
{
|
|
2594
|
+
name: "Kinde APIs",
|
|
2595
|
+
items: [
|
|
2596
|
+
{ id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
|
|
2597
|
+
{ id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
|
|
2598
|
+
{ id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
|
|
2599
|
+
{ id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
|
|
2600
|
+
]
|
|
2601
|
+
},
|
|
2602
|
+
{
|
|
2603
|
+
name: "Webhooks",
|
|
2604
|
+
items: [
|
|
2605
|
+
{ id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
|
|
2606
|
+
{ id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
|
|
2607
|
+
{ id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
|
|
2608
|
+
{ id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
|
|
2609
|
+
{ id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
|
|
2610
|
+
]
|
|
2611
|
+
},
|
|
2612
|
+
{
|
|
2613
|
+
name: "Outages",
|
|
2614
|
+
items: [
|
|
2615
|
+
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
2616
|
+
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
2617
|
+
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
2618
|
+
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
|
|
2619
|
+
]
|
|
2620
|
+
}
|
|
2621
|
+
];
|
|
2622
|
+
var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
|
|
2623
|
+
function tokenLabel(kind) {
|
|
2624
|
+
return {
|
|
2625
|
+
expired: "Expired token",
|
|
2626
|
+
"future-iat": "Token issued in the future",
|
|
2627
|
+
"wrong-issuer": "Wrong issuer",
|
|
2628
|
+
"wrong-audience": "Wrong audience",
|
|
2629
|
+
"bad-signature": "Tampered signature",
|
|
2630
|
+
"unknown-key": "Unknown signing key",
|
|
2631
|
+
unsigned: "Unsigned token",
|
|
2632
|
+
"missing-subject": "No subject"
|
|
2633
|
+
}[kind];
|
|
2634
|
+
}
|
|
2635
|
+
var CoverageRecorder = class {
|
|
2636
|
+
hits = /* @__PURE__ */ new Map();
|
|
2637
|
+
userOrganizations = /* @__PURE__ */ new Map();
|
|
2638
|
+
organizationUsers = /* @__PURE__ */ new Map();
|
|
2639
|
+
organizationPermissionSets = /* @__PURE__ */ new Map();
|
|
2640
|
+
hit(id) {
|
|
2641
|
+
if (!ALL_IDS.has(id)) return;
|
|
2642
|
+
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
2643
|
+
}
|
|
2644
|
+
/** Called for every access token the testkit signs. */
|
|
2645
|
+
observeAccessToken(payload, invalid2) {
|
|
2646
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
2647
|
+
this.hit("m2m.token");
|
|
2648
|
+
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
2649
|
+
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
2650
|
+
if (invalid2) this.hit("m2m.invalid");
|
|
2651
|
+
return;
|
|
2652
|
+
}
|
|
2653
|
+
if (invalid2 === "missing-organization") return this.hit("organization.missing");
|
|
2654
|
+
if (invalid2 === "missing-permissions") return this.hit("permission.none");
|
|
2655
|
+
if (invalid2) return this.hit(`token.${invalid2}`);
|
|
2656
|
+
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
2657
|
+
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
2658
|
+
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
2659
|
+
if (subject) this.hit("identity.user");
|
|
2660
|
+
if (!organization) this.hit("identity.no-organization");
|
|
2661
|
+
if (permissions.length > 0) this.hit("permission.granted");
|
|
2662
|
+
else this.hit("permission.none");
|
|
2663
|
+
if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
|
|
2664
|
+
if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
|
|
2665
|
+
if (!organization) return;
|
|
2666
|
+
this.hit("organization.token");
|
|
2667
|
+
if (subject) {
|
|
2668
|
+
const organizations = add(this.userOrganizations, subject, organization);
|
|
2669
|
+
if (organizations.size > 1) this.hit("organization.two-for-one-user");
|
|
2670
|
+
add(this.organizationUsers, organization, subject);
|
|
2671
|
+
const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
|
|
2672
|
+
const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
|
|
2673
|
+
if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
|
|
2674
|
+
}
|
|
2675
|
+
const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
|
|
2676
|
+
if (sets.size > 1) this.hit("permission.different-sets");
|
|
2677
|
+
}
|
|
2678
|
+
report() {
|
|
2679
|
+
return buildReport(Object.fromEntries(this.hits));
|
|
2680
|
+
}
|
|
2681
|
+
snapshot() {
|
|
2682
|
+
return { version: 1, hits: Object.fromEntries(this.hits) };
|
|
2683
|
+
}
|
|
2684
|
+
reset() {
|
|
2685
|
+
this.hits.clear();
|
|
2686
|
+
this.userOrganizations.clear();
|
|
2687
|
+
this.organizationUsers.clear();
|
|
2688
|
+
this.organizationPermissionSets.clear();
|
|
2689
|
+
}
|
|
2690
|
+
/** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
|
|
2691
|
+
write(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2692
|
+
const folder = resolve2(directory);
|
|
2693
|
+
mkdirSync2(folder, { recursive: true });
|
|
2694
|
+
const file = join2(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
|
|
2695
|
+
writeFileSync2(file, `${JSON.stringify(this.snapshot())}
|
|
2696
|
+
`);
|
|
2697
|
+
return file;
|
|
2698
|
+
}
|
|
2699
|
+
};
|
|
2700
|
+
var DEFAULT_COVERAGE_DIRECTORY = join2(".kinde-testkit", "coverage");
|
|
2701
|
+
function add(map, key, value) {
|
|
2702
|
+
let set2 = map.get(key);
|
|
2703
|
+
if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
|
|
2704
|
+
set2.add(value);
|
|
2705
|
+
return set2;
|
|
2706
|
+
}
|
|
2707
|
+
function buildReport(hits) {
|
|
2708
|
+
const groups = COVERAGE_GROUPS.map((group) => {
|
|
2709
|
+
const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
|
|
2710
|
+
return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
|
|
2711
|
+
});
|
|
2712
|
+
return {
|
|
2713
|
+
covered: groups.reduce((sum, g) => sum + g.covered, 0),
|
|
2714
|
+
total: groups.reduce((sum, g) => sum + g.total, 0),
|
|
2715
|
+
groups
|
|
2716
|
+
};
|
|
2717
|
+
}
|
|
2718
|
+
function mergeSnapshots(snapshots) {
|
|
2719
|
+
const hits = {};
|
|
2720
|
+
for (const snapshot of snapshots) {
|
|
2721
|
+
for (const [id, count] of Object.entries(snapshot.hits ?? {})) hits[id] = (hits[id] ?? 0) + count;
|
|
2722
|
+
}
|
|
2723
|
+
return hits;
|
|
2724
|
+
}
|
|
2725
|
+
function readCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2726
|
+
const folder = resolve2(directory);
|
|
2727
|
+
let names = [];
|
|
2728
|
+
try {
|
|
2729
|
+
names = readdirSync(folder).filter((name) => name.endsWith(".json"));
|
|
2730
|
+
} catch {
|
|
2731
|
+
}
|
|
2732
|
+
const snapshots = names.map((name) => JSON.parse(readFileSync2(join2(folder, name), "utf8")));
|
|
2733
|
+
return { files: names.length, report: buildReport(mergeSnapshots(snapshots)) };
|
|
2734
|
+
}
|
|
2735
|
+
function clearCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2736
|
+
rmSync(resolve2(directory), { recursive: true, force: true });
|
|
2737
|
+
}
|
|
2738
|
+
function formatCoverageReport(report, options = {}) {
|
|
2739
|
+
const width = Math.max(...report.groups.map((g) => g.name.length)) + 3;
|
|
2740
|
+
const lines = ["Kinde authentication coverage", ""];
|
|
2741
|
+
for (const group of report.groups) {
|
|
2742
|
+
lines.push(`${group.name.padEnd(width)}${String(group.covered).padStart(2)}/${group.total}`);
|
|
2743
|
+
}
|
|
2744
|
+
lines.push("", `Overall: ${report.covered}/${report.total}`);
|
|
2745
|
+
if (options.missing !== false) {
|
|
2746
|
+
const missing = report.groups.flatMap((g) => g.items.filter((i) => !i.covered).map((i) => ({ group: g.name, ...i })));
|
|
2747
|
+
if (missing.length > 0) {
|
|
2748
|
+
lines.push("", "Not covered:");
|
|
2749
|
+
for (const item of missing) lines.push(` ${item.group}: ${item.label}. ${item.hint}`);
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
return lines.join("\n");
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
// src/dashboard.ts
|
|
2756
|
+
var STYLE2 = `
|
|
2757
|
+
: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}
|
|
2758
|
+
@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}}
|
|
2759
|
+
*{box-sizing:border-box}
|
|
2760
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
2761
|
+
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)}
|
|
2762
|
+
header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
|
|
2763
|
+
header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2764
|
+
nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
|
|
2765
|
+
nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
|
|
2766
|
+
main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
|
|
2767
|
+
section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
|
|
2768
|
+
h2{margin:0 0 4px;font-size:16px;font-weight:600}
|
|
2769
|
+
.sub{margin:0 0 14px;color:var(--muted);font-size:13px}
|
|
2770
|
+
table{width:100%;border-collapse:collapse;font-size:13px}
|
|
2771
|
+
th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
|
|
2772
|
+
td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
|
|
2773
|
+
tr:last-child td{border-bottom:0}
|
|
2774
|
+
code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2775
|
+
.chips{display:flex;flex-wrap:wrap;gap:4px}
|
|
2776
|
+
.chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
|
|
2777
|
+
.ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
|
|
2778
|
+
.empty{color:var(--muted);font-size:13px;margin:0}
|
|
2779
|
+
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
|
|
2780
|
+
label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
|
|
2781
|
+
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}
|
|
2782
|
+
input[type=checkbox]{height:auto}
|
|
2783
|
+
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}
|
|
2784
|
+
button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
|
|
2785
|
+
button:hover{border-color:var(--muted)}
|
|
2786
|
+
details summary{cursor:pointer;color:var(--muted)}
|
|
2787
|
+
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}
|
|
2788
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
|
|
2789
|
+
.group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
|
|
2790
|
+
.group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
|
|
2791
|
+
.notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
|
|
2792
|
+
.split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
|
|
2793
|
+
`;
|
|
2794
|
+
function renderDashboard(data) {
|
|
2795
|
+
const e = escapeHtml;
|
|
2796
|
+
const { seed } = data;
|
|
2797
|
+
const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
|
|
2798
|
+
const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
|
|
2799
|
+
const users = seed.users.length ? table(
|
|
2800
|
+
["User", "ID", "Organizations", "Sign-ins", "Status"],
|
|
2801
|
+
seed.users.map((user) => [
|
|
2802
|
+
e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
|
|
2803
|
+
`<code>${e(user.id)}</code>`,
|
|
2804
|
+
chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
|
|
2805
|
+
String(data.signIns(user.id)),
|
|
2806
|
+
data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
|
|
2807
|
+
])
|
|
2808
|
+
) : empty("No users yet. Seed some, or sign in with any email.");
|
|
2809
|
+
const organizations = seed.organizations.length ? table(
|
|
2810
|
+
["Organization", "Code", "Members"],
|
|
2811
|
+
seed.organizations.map((org) => [
|
|
2812
|
+
e(org.name),
|
|
2813
|
+
`<code>${e(org.code)}</code>`,
|
|
2814
|
+
String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
|
|
2815
|
+
])
|
|
2816
|
+
) : empty("No organizations.");
|
|
2817
|
+
const memberships = seed.memberships.length ? table(
|
|
2818
|
+
["User", "Organization", "Roles", "Permissions in the token"],
|
|
2819
|
+
seed.memberships.map((m) => [
|
|
2820
|
+
e(userLabel(m.userId)),
|
|
2821
|
+
e(orgName(m.organizationCode)),
|
|
2822
|
+
chips(m.roles),
|
|
2823
|
+
chips(effectivePermissions(seed, m))
|
|
2824
|
+
])
|
|
2825
|
+
) : empty("No memberships.");
|
|
2826
|
+
const applications = seed.applications.length ? table(
|
|
2827
|
+
["Client ID", "Organization", "Scopes"],
|
|
2828
|
+
seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
|
|
2829
|
+
) : "";
|
|
2830
|
+
const tokens = data.tokens.length ? table(
|
|
2831
|
+
["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
|
|
2832
|
+
[...data.tokens].reverse().slice(0, 50).map((t) => [
|
|
2833
|
+
time(t.at),
|
|
2834
|
+
t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
|
|
2835
|
+
`<code>${e(t.subject ?? "none")}</code>`,
|
|
2836
|
+
e(t.organization ?? "none"),
|
|
2837
|
+
chips(t.permissions),
|
|
2838
|
+
`<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
|
|
2839
|
+
])
|
|
2840
|
+
) : empty("No tokens issued yet.");
|
|
2841
|
+
const requests = data.requests.length ? table(
|
|
2842
|
+
["Time", "Request", "Status", "Time taken"],
|
|
2843
|
+
[...data.requests].reverse().slice(0, 100).map((r) => [
|
|
2844
|
+
time(r.at),
|
|
2845
|
+
`<code>${e(r.method)} ${e(r.path)}</code>`,
|
|
2846
|
+
`<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
|
|
2847
|
+
`${r.durationMs} ms`
|
|
2848
|
+
])
|
|
2849
|
+
) : empty("No requests yet.");
|
|
2850
|
+
const deliveries = data.deliveries.length ? table(
|
|
2851
|
+
["Event", "Endpoint", "Copy", "Result"],
|
|
2852
|
+
[...data.deliveries].reverse().slice(0, 50).map((d) => [
|
|
2853
|
+
`<code>${e(d.type)}</code>`,
|
|
2854
|
+
`<code>${e(d.url)}</code>`,
|
|
2855
|
+
String(d.copy),
|
|
2856
|
+
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>`
|
|
2857
|
+
])
|
|
2858
|
+
) : empty("No webhooks sent yet.");
|
|
2859
|
+
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>`;
|
|
2860
|
+
const webhookForm = data.endpoints.length ? form(
|
|
2861
|
+
"/dashboard/webhooks",
|
|
2862
|
+
`<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
|
|
2863
|
+
<label>User<select name="user"><option value="">First seeded user</option>${seed.users.map((u) => `<option value="${e(u.id)}">${e(u.email ?? u.id)}</option>`).join("")}</select></label>
|
|
2864
|
+
<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>
|
|
2865
|
+
<label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
|
|
2866
|
+
<button class="primary">Send</button>`
|
|
2867
|
+
) : "";
|
|
2868
|
+
const failures = data.failures.length ? table(
|
|
2869
|
+
["Path", "Method", "Effect", "Remaining", "Hits", ""],
|
|
2870
|
+
data.failures.map((f) => [
|
|
2871
|
+
`<code>${e(f.path)}</code>`,
|
|
2872
|
+
e(f.method ?? "any"),
|
|
2873
|
+
e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
|
|
2874
|
+
f.remaining === null ? "Until removed" : String(f.remaining),
|
|
2875
|
+
String(f.hits),
|
|
2876
|
+
form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
|
|
2877
|
+
])
|
|
2878
|
+
) : empty("No failure rules.");
|
|
2879
|
+
const coverage = `<div class="grid">${data.coverage.groups.map(
|
|
2880
|
+
(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>`
|
|
2881
|
+
).join("")}</div>`;
|
|
2882
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2883
|
+
${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
|
|
2884
|
+
<title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
|
|
2885
|
+
<header>
|
|
2886
|
+
<div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
|
|
2887
|
+
<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>
|
|
2888
|
+
<div class="row">
|
|
2889
|
+
<a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
|
|
2890
|
+
${form("/dashboard/reset", `<button>Reset state</button>`)}
|
|
2891
|
+
</div>
|
|
2892
|
+
</header>
|
|
2893
|
+
<main>
|
|
2894
|
+
${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
|
|
2895
|
+
<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>
|
|
2896
|
+
<div class="split">
|
|
2897
|
+
<section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
|
|
2898
|
+
<section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
|
|
2899
|
+
</div>
|
|
2900
|
+
${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
|
|
2901
|
+
<section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
|
|
2902
|
+
<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>
|
|
2903
|
+
<section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
|
|
2904
|
+
<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>
|
|
2905
|
+
${form(
|
|
2906
|
+
"/dashboard/failures",
|
|
2907
|
+
`<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
|
|
2908
|
+
<label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
|
|
2909
|
+
<label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
|
|
2910
|
+
<label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
|
|
2911
|
+
<label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
|
|
2912
|
+
<label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
|
|
2913
|
+
<button class="primary">Add rule</button>`
|
|
2914
|
+
)}
|
|
2915
|
+
<div style="margin-top:14px">${failures}</div>
|
|
2916
|
+
${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
|
|
2917
|
+
</section>
|
|
2918
|
+
<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>${coverage}
|
|
2919
|
+
<div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
|
|
2920
|
+
</main></body></html>`;
|
|
2921
|
+
}
|
|
2922
|
+
function table(headers, rows) {
|
|
2923
|
+
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>`;
|
|
2924
|
+
}
|
|
2925
|
+
function chips(values) {
|
|
2926
|
+
if (values.length === 0) return `<span class="muted">none</span>`;
|
|
2927
|
+
return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
|
|
2928
|
+
}
|
|
2929
|
+
function empty(text) {
|
|
2930
|
+
return `<p class="empty">${escapeHtml(text)}</p>`;
|
|
2931
|
+
}
|
|
2932
|
+
function time(iso) {
|
|
2933
|
+
return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
|
|
2934
|
+
}
|
|
2935
|
+
function form(action, body) {
|
|
2936
|
+
return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
|
|
2937
|
+
}
|
|
2938
|
+
|
|
2939
|
+
// src/seed-file.ts
|
|
2940
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
2941
|
+
import { extname, resolve as resolve3 } from "path";
|
|
2942
|
+
import { pathToFileURL } from "url";
|
|
2943
|
+
import { parse as parseYaml } from "yaml";
|
|
2944
|
+
var DEFAULT_SEED_FILES = [
|
|
2945
|
+
"kinde-testkit.json",
|
|
2946
|
+
"kinde-testkit.yaml",
|
|
2947
|
+
"kinde-testkit.yml",
|
|
2948
|
+
"kinde-testkit.ts",
|
|
2949
|
+
"kinde-testkit.mts",
|
|
2950
|
+
"kinde-testkit.js",
|
|
2951
|
+
"kinde-testkit.mjs"
|
|
2952
|
+
];
|
|
2953
|
+
function findSeedFile(directory = ".") {
|
|
2954
|
+
return DEFAULT_SEED_FILES.map((name) => resolve3(directory, name)).find((path) => existsSync2(path));
|
|
2955
|
+
}
|
|
2956
|
+
async function loadSeedFile(path) {
|
|
2957
|
+
const file = resolve3(path);
|
|
2958
|
+
const extension = extname(file).toLowerCase();
|
|
2959
|
+
let value;
|
|
2960
|
+
try {
|
|
2961
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
2962
|
+
value = parseYaml(readFileSync3(file, "utf8"));
|
|
2963
|
+
} else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
|
|
2964
|
+
const module = await import(pathToFileURL(file).href);
|
|
2965
|
+
value = module.seed ?? module.default;
|
|
2966
|
+
if (value && typeof value === "object" && "default" in value && !("users" in value)) {
|
|
2967
|
+
value = value.default;
|
|
2968
|
+
}
|
|
2969
|
+
} else {
|
|
2970
|
+
value = JSON.parse(readFileSync3(file, "utf8"));
|
|
2971
|
+
}
|
|
2972
|
+
} catch (error) {
|
|
2973
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2974
|
+
const details = [message];
|
|
2975
|
+
if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message)) {
|
|
2976
|
+
details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
|
|
2977
|
+
}
|
|
2978
|
+
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
|
|
2979
|
+
}
|
|
2980
|
+
if (value === null || value === void 0) value = {};
|
|
2981
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
2982
|
+
throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
|
|
2983
|
+
}
|
|
2984
|
+
return value;
|
|
1442
2985
|
}
|
|
1443
2986
|
|
|
1444
2987
|
// src/server.ts
|
|
@@ -1453,33 +2996,74 @@ async function startKindeTestkit(options = {}) {
|
|
|
1453
2996
|
`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).`
|
|
1454
2997
|
);
|
|
1455
2998
|
}
|
|
1456
|
-
const
|
|
2999
|
+
const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
|
|
3000
|
+
const seed = resolveSeed(seedInput);
|
|
1457
3001
|
const failures = new FailureInjector();
|
|
1458
3002
|
let ready;
|
|
1459
|
-
const testkitReady = new Promise((
|
|
1460
|
-
const
|
|
3003
|
+
const testkitReady = new Promise((resolve4) => ready = resolve4);
|
|
3004
|
+
const listener = (req, res) => {
|
|
1461
3005
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1462
|
-
}
|
|
1463
|
-
|
|
3006
|
+
};
|
|
3007
|
+
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
3008
|
+
const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
|
|
3009
|
+
await new Promise((resolve4, reject) => {
|
|
1464
3010
|
server.once("error", reject);
|
|
1465
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
3011
|
+
server.listen(options.port ?? 4400, host, () => resolve4());
|
|
1466
3012
|
});
|
|
1467
3013
|
const { port } = server.address();
|
|
1468
|
-
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1469
|
-
const url =
|
|
3014
|
+
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
3015
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1470
3016
|
const testkit = await KindeTestkit.create({
|
|
1471
|
-
issuer: options.issuer ??
|
|
1472
|
-
audience: options.audience ??
|
|
1473
|
-
clientId: options.clientId ??
|
|
3017
|
+
issuer: options.issuer ?? seedInput.issuer ?? url,
|
|
3018
|
+
audience: options.audience ?? seedInput.audience,
|
|
3019
|
+
clientId: options.clientId ?? seedInput.clientId
|
|
3020
|
+
});
|
|
3021
|
+
const coverage = new CoverageRecorder();
|
|
3022
|
+
const activity = new ActivityLog();
|
|
3023
|
+
testkit.observe({
|
|
3024
|
+
accessToken(payload, invalid2, token) {
|
|
3025
|
+
coverage.observeAccessToken(payload, invalid2);
|
|
3026
|
+
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
3027
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid2, token);
|
|
3028
|
+
},
|
|
3029
|
+
idToken(payload, token) {
|
|
3030
|
+
coverage.hit("identity.id-token");
|
|
3031
|
+
activity.token("id", payload, void 0, token);
|
|
3032
|
+
},
|
|
3033
|
+
anonymous() {
|
|
3034
|
+
coverage.hit("identity.anonymous");
|
|
3035
|
+
}
|
|
1474
3036
|
});
|
|
3037
|
+
const observe = (id) => coverage.hit(id);
|
|
3038
|
+
const directory = new Directory(seed);
|
|
1475
3039
|
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
1476
|
-
|
|
3040
|
+
webhooks.observe = observe;
|
|
3041
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
|
|
3042
|
+
const management = new ManagementApi(testkit, directory, webhooks);
|
|
3043
|
+
const account = new AccountApi(testkit, directory);
|
|
1477
3044
|
const reset = () => {
|
|
1478
3045
|
auth.reset();
|
|
1479
3046
|
failures.clear();
|
|
1480
3047
|
webhooks.reset();
|
|
3048
|
+
directory.restore();
|
|
1481
3049
|
};
|
|
1482
|
-
|
|
3050
|
+
const loadSeed = (input) => {
|
|
3051
|
+
const next = resolveSeed(input);
|
|
3052
|
+
directory.load(next);
|
|
3053
|
+
webhooks.replaceSeededEndpoints(next.webhooks);
|
|
3054
|
+
reset();
|
|
3055
|
+
};
|
|
3056
|
+
let closed = false;
|
|
3057
|
+
const close = () => new Promise((resolve4, reject) => {
|
|
3058
|
+
if (closed) return resolve4();
|
|
3059
|
+
closed = true;
|
|
3060
|
+
if (options.coverage) {
|
|
3061
|
+
coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
|
|
3062
|
+
}
|
|
3063
|
+
server.closeAllConnections();
|
|
3064
|
+
server.close((error) => error ? reject(error) : resolve4());
|
|
3065
|
+
});
|
|
3066
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
|
|
1483
3067
|
return {
|
|
1484
3068
|
url,
|
|
1485
3069
|
issuer: testkit.issuer,
|
|
@@ -1489,84 +3073,224 @@ async function startKindeTestkit(options = {}) {
|
|
|
1489
3073
|
seed,
|
|
1490
3074
|
failures,
|
|
1491
3075
|
webhooks,
|
|
3076
|
+
directory,
|
|
3077
|
+
certificatePath: certificate?.certPath ?? null,
|
|
3078
|
+
coverage,
|
|
3079
|
+
activity,
|
|
3080
|
+
loadSeed,
|
|
1492
3081
|
reset,
|
|
1493
|
-
close
|
|
1494
|
-
server.closeAllConnections();
|
|
1495
|
-
server.close((error) => error ? reject(error) : resolve());
|
|
1496
|
-
})
|
|
3082
|
+
close
|
|
1497
3083
|
};
|
|
1498
3084
|
}
|
|
1499
3085
|
async function handle(req, res, context) {
|
|
1500
|
-
const { testkit, auth, seed, failures, webhooks } = context;
|
|
3086
|
+
const { testkit, auth, seed, failures, webhooks, coverage } = context;
|
|
1501
3087
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1502
3088
|
const { pathname } = url;
|
|
1503
3089
|
const method = req.method ?? "GET";
|
|
1504
|
-
|
|
3090
|
+
const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
|
|
3091
|
+
let injected = false;
|
|
3092
|
+
if (!internal && pathname !== "/favicon.ico") {
|
|
3093
|
+
const started = Date.now();
|
|
3094
|
+
res.once("close", () => {
|
|
3095
|
+
context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
|
|
3096
|
+
});
|
|
3097
|
+
}
|
|
3098
|
+
if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
|
|
3099
|
+
if (!internal) {
|
|
1505
3100
|
const failure = failures.take(method, pathname);
|
|
1506
3101
|
if (failure) {
|
|
3102
|
+
injected = true;
|
|
3103
|
+
if (failure.hang) coverage.hit("outage.timeout");
|
|
3104
|
+
else if (failure.status === 429) coverage.hit("outage.rate-limit");
|
|
3105
|
+
else if (failure.status !== null) coverage.hit("outage.error");
|
|
3106
|
+
if (failure.delayMs > 0) coverage.hit("outage.slow");
|
|
1507
3107
|
if (failure.hang) return;
|
|
1508
|
-
if (failure.delayMs > 0) await new Promise((
|
|
3108
|
+
if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
|
|
1509
3109
|
if (failure.status !== null) {
|
|
1510
3110
|
const headers = {};
|
|
1511
3111
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1512
|
-
return
|
|
3112
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1513
3113
|
}
|
|
1514
3114
|
}
|
|
1515
3115
|
}
|
|
1516
3116
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
3117
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) {
|
|
3118
|
+
if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
|
|
3119
|
+
else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
|
|
3120
|
+
return;
|
|
3121
|
+
}
|
|
3122
|
+
if (await context.account.handle(req, res, url)) {
|
|
3123
|
+
if (res.statusCode < 400) coverage.hit("api.account");
|
|
3124
|
+
return;
|
|
3125
|
+
}
|
|
3126
|
+
if (method === "GET" && pathname === "/testkit/portal") {
|
|
3127
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
3128
|
+
res.end(
|
|
3129
|
+
`<!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>`
|
|
3130
|
+
);
|
|
3131
|
+
return;
|
|
3132
|
+
}
|
|
1517
3133
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1518
|
-
return
|
|
3134
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1519
3135
|
}
|
|
1520
3136
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1521
|
-
return
|
|
3137
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1522
3138
|
}
|
|
1523
3139
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1524
|
-
return
|
|
3140
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1525
3141
|
}
|
|
1526
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
3142
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
1527
3143
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1528
|
-
return
|
|
3144
|
+
return sendJson4(res, 200, seed.organizations);
|
|
1529
3145
|
}
|
|
1530
3146
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1531
|
-
return
|
|
3147
|
+
return sendJson4(res, 200, seed.memberships);
|
|
1532
3148
|
}
|
|
1533
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
3149
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1534
3150
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1535
|
-
return
|
|
3151
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1536
3152
|
}
|
|
1537
3153
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1538
3154
|
failures.clear();
|
|
1539
|
-
return
|
|
3155
|
+
return sendJson4(res, 200, { ok: true });
|
|
1540
3156
|
}
|
|
1541
3157
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1542
3158
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1543
|
-
return
|
|
3159
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1544
3160
|
}
|
|
1545
3161
|
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1546
|
-
return
|
|
3162
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
1547
3163
|
}
|
|
1548
3164
|
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1549
|
-
return
|
|
3165
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1550
3166
|
}
|
|
1551
|
-
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return
|
|
1552
|
-
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return
|
|
3167
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
|
|
3168
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
|
|
1553
3169
|
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1554
|
-
return
|
|
3170
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1555
3171
|
}
|
|
1556
3172
|
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1557
3173
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1558
|
-
return
|
|
3174
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1559
3175
|
}
|
|
1560
3176
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1561
3177
|
context.reset();
|
|
1562
|
-
return
|
|
3178
|
+
return sendJson4(res, 200, { ok: true });
|
|
1563
3179
|
}
|
|
1564
3180
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1565
3181
|
const body = await readJson(req);
|
|
1566
|
-
|
|
1567
|
-
|
|
3182
|
+
let accessToken;
|
|
3183
|
+
try {
|
|
3184
|
+
accessToken = await issueToken(testkit, seed, body);
|
|
3185
|
+
} catch (error) {
|
|
3186
|
+
if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
|
|
3187
|
+
throw error;
|
|
3188
|
+
}
|
|
3189
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
3190
|
+
}
|
|
3191
|
+
if (method === "GET" && pathname === "/testkit/coverage") {
|
|
3192
|
+
return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
|
|
3193
|
+
}
|
|
3194
|
+
if (method === "DELETE" && pathname === "/testkit/coverage") {
|
|
3195
|
+
coverage.reset();
|
|
3196
|
+
return sendJson4(res, 200, { ok: true });
|
|
3197
|
+
}
|
|
3198
|
+
if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
|
|
3199
|
+
if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
|
|
3200
|
+
if (method === "POST" && pathname === "/testkit/seed") {
|
|
3201
|
+
const body = await readJson(req);
|
|
3202
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
3203
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
3204
|
+
}
|
|
3205
|
+
context.loadSeed(body);
|
|
3206
|
+
return sendJson4(res, 200, {
|
|
3207
|
+
ok: true,
|
|
3208
|
+
users: seed.users.length,
|
|
3209
|
+
organizations: seed.organizations.length,
|
|
3210
|
+
memberships: seed.memberships.length
|
|
3211
|
+
});
|
|
3212
|
+
}
|
|
3213
|
+
if (method === "POST" && pathname === "/testkit/stop") {
|
|
3214
|
+
sendJson4(res, 200, { ok: true });
|
|
3215
|
+
res.once("finish", () => void context.close().catch(() => void 0));
|
|
3216
|
+
return;
|
|
3217
|
+
}
|
|
3218
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3219
|
+
}
|
|
3220
|
+
async function dashboard(req, res, url, context) {
|
|
3221
|
+
const method = req.method ?? "GET";
|
|
3222
|
+
const { pathname } = url;
|
|
3223
|
+
if (method === "GET" && pathname === "/dashboard") {
|
|
3224
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
3225
|
+
res.end(
|
|
3226
|
+
renderDashboard({
|
|
3227
|
+
issuer: context.testkit.issuer,
|
|
3228
|
+
seed: context.seed,
|
|
3229
|
+
suspended: (id) => context.directory.isSuspended(id),
|
|
3230
|
+
signIns: (id) => {
|
|
3231
|
+
const user = context.directory.user(id);
|
|
3232
|
+
return user ? context.directory.meta(user).totalSignIns : 0;
|
|
3233
|
+
},
|
|
3234
|
+
tokens: context.activity.tokens(),
|
|
3235
|
+
requests: context.activity.requests(),
|
|
3236
|
+
deliveries: context.webhooks.deliveries(),
|
|
3237
|
+
endpoints: context.webhooks.listEndpoints(),
|
|
3238
|
+
failures: context.failures.list(),
|
|
3239
|
+
coverage: context.coverage.report(),
|
|
3240
|
+
webhookTypes: WEBHOOK_EVENT_TYPES,
|
|
3241
|
+
live: url.searchParams.has("live"),
|
|
3242
|
+
notice: url.searchParams.get("notice")
|
|
3243
|
+
})
|
|
3244
|
+
);
|
|
3245
|
+
return;
|
|
3246
|
+
}
|
|
3247
|
+
if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3248
|
+
const origin = req.headers.origin;
|
|
3249
|
+
if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
|
|
3250
|
+
return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
|
|
3251
|
+
}
|
|
3252
|
+
const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
|
|
3253
|
+
let notice = "Done.";
|
|
3254
|
+
try {
|
|
3255
|
+
if (pathname === "/dashboard/reset") {
|
|
3256
|
+
context.reset();
|
|
3257
|
+
notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
|
|
3258
|
+
} else if (pathname === "/dashboard/coverage/reset") {
|
|
3259
|
+
context.coverage.reset();
|
|
3260
|
+
notice = "Cleared coverage.";
|
|
3261
|
+
} else if (pathname === "/dashboard/failures/clear") {
|
|
3262
|
+
context.failures.clear();
|
|
3263
|
+
notice = "Removed every failure rule.";
|
|
3264
|
+
} else if (pathname === "/dashboard/failures") {
|
|
3265
|
+
const rule = { path: form2.path ?? "" };
|
|
3266
|
+
if (form2.method) rule.method = form2.method;
|
|
3267
|
+
if (form2.status) rule.status = Number(form2.status);
|
|
3268
|
+
if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
|
|
3269
|
+
if (form2.times) rule.times = Number(form2.times);
|
|
3270
|
+
if (form2.hang) rule.hang = true;
|
|
3271
|
+
const added = context.failures.add(rule);
|
|
3272
|
+
notice = `Added ${added.id} for ${added.path}.`;
|
|
3273
|
+
} else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
|
|
3274
|
+
const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
|
|
3275
|
+
notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
|
|
3276
|
+
} else if (pathname === "/dashboard/webhooks") {
|
|
3277
|
+
const deliveries = await context.webhooks.send({
|
|
3278
|
+
type: form2.type ?? "",
|
|
3279
|
+
user: form2.user || void 0,
|
|
3280
|
+
invalid: form2.invalid || void 0,
|
|
3281
|
+
duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
|
|
3282
|
+
});
|
|
3283
|
+
const delivered = deliveries.filter((d) => d.delivered).length;
|
|
3284
|
+
notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
|
|
3285
|
+
} else {
|
|
3286
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
|
|
3287
|
+
}
|
|
3288
|
+
} catch (error) {
|
|
3289
|
+
notice = error.message.replace(/\s+/g, " ").trim();
|
|
1568
3290
|
}
|
|
1569
|
-
|
|
3291
|
+
const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
|
|
3292
|
+
res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
|
|
3293
|
+
res.end();
|
|
1570
3294
|
}
|
|
1571
3295
|
function discovery(testkit) {
|
|
1572
3296
|
const base = testkit.issuer;
|
|
@@ -1625,7 +3349,11 @@ async function issueToken(testkit, seed, body) {
|
|
|
1625
3349
|
});
|
|
1626
3350
|
if (permissions) scenario2.permissions = permissions;
|
|
1627
3351
|
if (roles) scenario2.roles = roles;
|
|
1628
|
-
return await testkit.tokenFor(scenario2, {
|
|
3352
|
+
return await testkit.tokenFor(scenario2, {
|
|
3353
|
+
expiresIn,
|
|
3354
|
+
invalid: invalid2,
|
|
3355
|
+
featureFlags: featureFlagsFor(seed, scenario2.organization?.code ?? null)
|
|
3356
|
+
});
|
|
1629
3357
|
}
|
|
1630
3358
|
const options = {
|
|
1631
3359
|
subject: optionalString(input, "subject"),
|
|
@@ -1690,7 +3418,7 @@ async function readText(req) {
|
|
|
1690
3418
|
}
|
|
1691
3419
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1692
3420
|
}
|
|
1693
|
-
function
|
|
3421
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1694
3422
|
res.writeHead(status, {
|
|
1695
3423
|
"content-type": "application/json; charset=utf-8",
|
|
1696
3424
|
"cache-control": "no-store",
|
|
@@ -1704,10 +3432,10 @@ function sendError(res, error) {
|
|
|
1704
3432
|
return;
|
|
1705
3433
|
}
|
|
1706
3434
|
if (error instanceof TestkitError) {
|
|
1707
|
-
|
|
3435
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1708
3436
|
return;
|
|
1709
3437
|
}
|
|
1710
|
-
|
|
3438
|
+
sendJson4(res, 500, {
|
|
1711
3439
|
error: "server_error",
|
|
1712
3440
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1713
3441
|
});
|
|
@@ -1854,6 +3582,15 @@ async function runDoctor(options) {
|
|
|
1854
3582
|
} else {
|
|
1855
3583
|
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1856
3584
|
}
|
|
3585
|
+
if (issuer?.startsWith("https://")) {
|
|
3586
|
+
checks.push(
|
|
3587
|
+
env.NODE_EXTRA_CA_CERTS ? { name: "NODE_EXTRA_CA_CERTS", status: "pass", detail: `${env.NODE_EXTRA_CA_CERTS}.` } : {
|
|
3588
|
+
name: "NODE_EXTRA_CA_CERTS",
|
|
3589
|
+
status: "warn",
|
|
3590
|
+
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."
|
|
3591
|
+
}
|
|
3592
|
+
);
|
|
3593
|
+
}
|
|
1857
3594
|
const site = env.KINDE_SITE_URL;
|
|
1858
3595
|
if (!site) {
|
|
1859
3596
|
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
@@ -1879,13 +3616,65 @@ function parseEnvFile(text) {
|
|
|
1879
3616
|
}
|
|
1880
3617
|
return values;
|
|
1881
3618
|
}
|
|
3619
|
+
|
|
3620
|
+
// src/handle.ts
|
|
3621
|
+
async function kindeTest(options) {
|
|
3622
|
+
const testkit = options.testkit ?? await getDefaultTestkit();
|
|
3623
|
+
const token = await testkit.tokenFor(options.scenario, options.token);
|
|
3624
|
+
const headers = token ? { authorization: `Bearer ${token}` } : {};
|
|
3625
|
+
return {
|
|
3626
|
+
token,
|
|
3627
|
+
headers,
|
|
3628
|
+
principal: testkit.principalFor(options.scenario),
|
|
3629
|
+
request: { headers }
|
|
3630
|
+
};
|
|
3631
|
+
}
|
|
3632
|
+
|
|
3633
|
+
// src/sign-in-flow.ts
|
|
3634
|
+
function appLoginUrl(loginPath, options) {
|
|
3635
|
+
const params = new URLSearchParams({ login_hint: options.user });
|
|
3636
|
+
if (options.org) params.set("org_code", options.org);
|
|
3637
|
+
return `${loginPath}${loginPath.includes("?") ? "&" : "?"}${params}`;
|
|
3638
|
+
}
|
|
3639
|
+
function readSignInRequest(html) {
|
|
3640
|
+
const match = /name="request" value="([^"]+)"/.exec(html);
|
|
3641
|
+
if (!match) {
|
|
3642
|
+
throw new Error("The page is not the kinde-testkit sign-in page. Check that the app's KINDE_ISSUER_URL points at the testkit.");
|
|
3643
|
+
}
|
|
3644
|
+
return decodeEntities(match[1]);
|
|
3645
|
+
}
|
|
3646
|
+
function signInForm(request, options) {
|
|
3647
|
+
const form2 = { request, email: options.user };
|
|
3648
|
+
if (options.org) form2.org = options.org;
|
|
3649
|
+
return form2;
|
|
3650
|
+
}
|
|
3651
|
+
function signInFailure(status, html, options) {
|
|
3652
|
+
if (status === 200 && html.includes("Choose an organization")) {
|
|
3653
|
+
return new Error(`${options.user} belongs to more than one organization. Pass one with { org: "org_..." }.`);
|
|
3654
|
+
}
|
|
3655
|
+
const alert = /role="alert"[^>]*>([\s\S]*?)<\//.exec(html)?.[1];
|
|
3656
|
+
const text = alert ? decodeEntities(alert.replace(/<[^>]+>/g, "")).trim() : `the sign-in page answered ${status}`;
|
|
3657
|
+
return new Error(`kinde-testkit refused the sign-in: ${text}`);
|
|
3658
|
+
}
|
|
3659
|
+
function resolveLocation(location, from) {
|
|
3660
|
+
return new URL(location, from).toString();
|
|
3661
|
+
}
|
|
3662
|
+
function decodeEntities(value) {
|
|
3663
|
+
return value.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
3664
|
+
}
|
|
1882
3665
|
export {
|
|
3666
|
+
ActivityLog,
|
|
1883
3667
|
BILLING_EVENT_TYPES,
|
|
3668
|
+
COVERAGE_GROUPS,
|
|
3669
|
+
CoverageRecorder,
|
|
1884
3670
|
DEFAULT_AUTH_METHODS,
|
|
1885
3671
|
DEFAULT_CLIENT_ID,
|
|
3672
|
+
DEFAULT_COVERAGE_DIRECTORY,
|
|
1886
3673
|
DEFAULT_ISSUER,
|
|
1887
3674
|
DEFAULT_M2M_CLIENT_ID,
|
|
1888
3675
|
DEFAULT_SCOPES,
|
|
3676
|
+
DEFAULT_SEED_FILES,
|
|
3677
|
+
Directory,
|
|
1889
3678
|
FailureInjector,
|
|
1890
3679
|
INVALID_TOKEN_KINDS,
|
|
1891
3680
|
KindeTestkit,
|
|
@@ -1893,20 +3682,35 @@ export {
|
|
|
1893
3682
|
TestkitError,
|
|
1894
3683
|
WEBHOOK_EVENT_TYPES,
|
|
1895
3684
|
WebhookDispatcher,
|
|
3685
|
+
appLoginUrl,
|
|
3686
|
+
buildReport,
|
|
3687
|
+
clearCoverageDirectory,
|
|
1896
3688
|
createKindeOrganization,
|
|
1897
3689
|
createKindeToken,
|
|
1898
3690
|
createKindeUser,
|
|
3691
|
+
createLocalCertificate,
|
|
1899
3692
|
createMembership,
|
|
3693
|
+
ensureLocalCertificate,
|
|
3694
|
+
findSeedFile,
|
|
3695
|
+
formatCoverageReport,
|
|
1900
3696
|
getDefaultTestkit,
|
|
1901
3697
|
inspectToken,
|
|
1902
3698
|
isAuthenticated,
|
|
3699
|
+
kindeTest,
|
|
3700
|
+
loadSeedFile,
|
|
3701
|
+
mergeSnapshots,
|
|
1903
3702
|
parseEnvFile,
|
|
1904
3703
|
principalFromClaims,
|
|
3704
|
+
readCoverageDirectory,
|
|
3705
|
+
readSignInRequest,
|
|
1905
3706
|
resetFactories,
|
|
3707
|
+
resolveLocation,
|
|
1906
3708
|
resolveSeed,
|
|
1907
3709
|
runDoctor,
|
|
1908
3710
|
scenario,
|
|
1909
3711
|
seedScenario,
|
|
3712
|
+
signInFailure,
|
|
3713
|
+
signInForm,
|
|
1910
3714
|
startKindeTestkit,
|
|
1911
3715
|
toKindeRole
|
|
1912
3716
|
};
|