kinde-testkit 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +48 -2
- package/dist/cli.js +1177 -124
- package/dist/index.cjs +1124 -111
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +150 -1
- package/dist/index.d.ts +150 -1
- package/dist/index.js +1120 -110
- package/dist/index.js.map +1 -1
- package/dist/vitest.d.ts +82 -0
- package/dist/vitest.js +1108 -110
- package/dist/vitest.js.map +1 -1
- package/package.json +3 -1
package/dist/vitest.js
CHANGED
|
@@ -361,8 +361,230 @@ function getDefaultTestkit() {
|
|
|
361
361
|
|
|
362
362
|
// src/server.ts
|
|
363
363
|
import { createServer } from "http";
|
|
364
|
+
import { createServer as createHttpsServer } from "https";
|
|
365
|
+
|
|
366
|
+
// src/certificate.ts
|
|
367
|
+
import { createHash as createHash2, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
|
|
368
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
369
|
+
import { join, resolve } from "path";
|
|
370
|
+
var CERT_FILE = "localhost-cert.pem";
|
|
371
|
+
var KEY_FILE = "localhost-key.pem";
|
|
372
|
+
var VALID_DAYS = 825;
|
|
373
|
+
function ensureLocalCertificate(directory = ".kinde-testkit") {
|
|
374
|
+
const dir = resolve(directory);
|
|
375
|
+
const certPath = join(dir, CERT_FILE);
|
|
376
|
+
const keyPath = join(dir, KEY_FILE);
|
|
377
|
+
if (existsSync(certPath) && existsSync(keyPath)) {
|
|
378
|
+
const cert2 = readFileSync(certPath, "utf8");
|
|
379
|
+
const key2 = readFileSync(keyPath, "utf8");
|
|
380
|
+
try {
|
|
381
|
+
if (new Date(new X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
|
|
382
|
+
return { cert: cert2, key: key2, certPath, keyPath, created: false };
|
|
383
|
+
}
|
|
384
|
+
} catch {
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const { cert, key } = createLocalCertificate();
|
|
388
|
+
mkdirSync(dir, { recursive: true });
|
|
389
|
+
writeFileSync(certPath, cert);
|
|
390
|
+
writeFileSync(keyPath, key, { mode: 384 });
|
|
391
|
+
writeFileSync(join(dir, ".gitignore"), "*\n");
|
|
392
|
+
return { cert, key, certPath, keyPath, created: true };
|
|
393
|
+
}
|
|
394
|
+
function createLocalCertificate() {
|
|
395
|
+
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
396
|
+
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
397
|
+
const keyId = createHash2("sha1").update(subjectPublicKeyBits(spki)).digest();
|
|
398
|
+
const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
|
|
399
|
+
const now = Date.now();
|
|
400
|
+
const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
|
|
401
|
+
const serial = randomBytes(16);
|
|
402
|
+
serial[0] &= 127;
|
|
403
|
+
const extensions = seq(
|
|
404
|
+
seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
|
|
405
|
+
seq(oid("2.5.29.14"), octets(octets(keyId))),
|
|
406
|
+
seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
|
|
407
|
+
seq(
|
|
408
|
+
oid("2.5.29.17"),
|
|
409
|
+
octets(
|
|
410
|
+
seq(
|
|
411
|
+
tlv(130, Buffer.from("localhost")),
|
|
412
|
+
tlv(135, Buffer.from([127, 0, 0, 1])),
|
|
413
|
+
tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
|
|
414
|
+
)
|
|
415
|
+
)
|
|
416
|
+
)
|
|
417
|
+
);
|
|
418
|
+
const tbs = seq(
|
|
419
|
+
tlv(160, integer(Buffer.from([2]))),
|
|
420
|
+
integer(serial),
|
|
421
|
+
algorithm,
|
|
422
|
+
name,
|
|
423
|
+
seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
|
|
424
|
+
name,
|
|
425
|
+
spki,
|
|
426
|
+
tlv(163, extensions)
|
|
427
|
+
);
|
|
428
|
+
const signature = sign("sha256", tbs, privateKey);
|
|
429
|
+
const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
|
|
430
|
+
return {
|
|
431
|
+
cert: pem("CERTIFICATE", der),
|
|
432
|
+
key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
function subjectPublicKeyBits(spki) {
|
|
436
|
+
const outer = readTlv(spki, 0);
|
|
437
|
+
const algorithm = readTlv(spki, outer.start);
|
|
438
|
+
const bits = readTlv(spki, algorithm.end);
|
|
439
|
+
return spki.subarray(bits.start + 1, bits.end);
|
|
440
|
+
}
|
|
441
|
+
function readTlv(buf, offset) {
|
|
442
|
+
let len = buf[offset + 1];
|
|
443
|
+
let header = 2;
|
|
444
|
+
if (len & 128) {
|
|
445
|
+
const n = len & 127;
|
|
446
|
+
len = 0;
|
|
447
|
+
for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
|
|
448
|
+
header += n;
|
|
449
|
+
}
|
|
450
|
+
return { start: offset + header, end: offset + header + len };
|
|
451
|
+
}
|
|
452
|
+
function tlv(tag, content) {
|
|
453
|
+
return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
|
|
454
|
+
}
|
|
455
|
+
function length(n) {
|
|
456
|
+
if (n < 128) return Buffer.from([n]);
|
|
457
|
+
const bytes = [];
|
|
458
|
+
while (n > 0) {
|
|
459
|
+
bytes.unshift(n & 255);
|
|
460
|
+
n >>= 8;
|
|
461
|
+
}
|
|
462
|
+
return Buffer.from([128 | bytes.length, ...bytes]);
|
|
463
|
+
}
|
|
464
|
+
function seq(...items) {
|
|
465
|
+
return tlv(48, Buffer.concat(items));
|
|
466
|
+
}
|
|
467
|
+
function set(...items) {
|
|
468
|
+
return tlv(49, Buffer.concat(items));
|
|
469
|
+
}
|
|
470
|
+
function octets(content) {
|
|
471
|
+
return tlv(4, content);
|
|
472
|
+
}
|
|
473
|
+
function integer(bytes) {
|
|
474
|
+
return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
|
|
475
|
+
}
|
|
476
|
+
function oid(dotted) {
|
|
477
|
+
const parts = dotted.split(".").map(Number);
|
|
478
|
+
const bytes = [parts[0] * 40 + parts[1]];
|
|
479
|
+
for (const part of parts.slice(2)) {
|
|
480
|
+
const chunk = [part & 127];
|
|
481
|
+
let value = part >> 7;
|
|
482
|
+
while (value > 0) {
|
|
483
|
+
chunk.unshift(value & 127 | 128);
|
|
484
|
+
value >>= 7;
|
|
485
|
+
}
|
|
486
|
+
bytes.push(...chunk);
|
|
487
|
+
}
|
|
488
|
+
return tlv(6, Buffer.from(bytes));
|
|
489
|
+
}
|
|
490
|
+
function utcTime(date) {
|
|
491
|
+
const iso = date.toISOString();
|
|
492
|
+
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`;
|
|
493
|
+
return tlv(23, Buffer.from(value));
|
|
494
|
+
}
|
|
495
|
+
function pem(label, der) {
|
|
496
|
+
const body = der.toString("base64").match(/.{1,64}/g).join("\n");
|
|
497
|
+
return `-----BEGIN ${label}-----
|
|
498
|
+
${body}
|
|
499
|
+
-----END ${label}-----
|
|
500
|
+
`;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// src/login-page.ts
|
|
504
|
+
var STYLE = `
|
|
505
|
+
: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}
|
|
506
|
+
@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}}
|
|
507
|
+
*{box-sizing:border-box}
|
|
508
|
+
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}
|
|
509
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
510
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
511
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
512
|
+
p{margin:0;color:var(--muted)}
|
|
513
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
514
|
+
form{margin:0}
|
|
515
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
516
|
+
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}
|
|
517
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
518
|
+
.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}
|
|
519
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
520
|
+
.list{display:grid;gap:8px}
|
|
521
|
+
.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}
|
|
522
|
+
.option:hover{border-color:var(--muted)}
|
|
523
|
+
.option strong{display:block;font-weight:500}
|
|
524
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
525
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
526
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
527
|
+
`;
|
|
528
|
+
function escapeHtml(value) {
|
|
529
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
530
|
+
}
|
|
531
|
+
function layout(title, body) {
|
|
532
|
+
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>`;
|
|
533
|
+
}
|
|
534
|
+
function displayName(user) {
|
|
535
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
536
|
+
}
|
|
537
|
+
function renderSignIn(options) {
|
|
538
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
539
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
540
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
541
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
542
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
543
|
+
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>`;
|
|
544
|
+
}).join("");
|
|
545
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
546
|
+
return layout(
|
|
547
|
+
"Sign in",
|
|
548
|
+
`<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>`
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
function renderOrganizationPicker(options) {
|
|
552
|
+
const choices = options.organizations.map(
|
|
553
|
+
(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>`
|
|
554
|
+
).join("");
|
|
555
|
+
return layout(
|
|
556
|
+
"Choose an organization",
|
|
557
|
+
`<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>`
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
function renderMessage(title, message) {
|
|
561
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
562
|
+
}
|
|
364
563
|
|
|
365
564
|
// src/seed.ts
|
|
565
|
+
function roleRecord(key, extra = {}) {
|
|
566
|
+
return {
|
|
567
|
+
id: stableId("role", key),
|
|
568
|
+
key,
|
|
569
|
+
name: extra.name ?? titleCase(key),
|
|
570
|
+
description: extra.description ?? null,
|
|
571
|
+
isDefault: extra.isDefault ?? false,
|
|
572
|
+
permissions: [...extra.permissions ?? []]
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
function permissionRecord(key, extra = {}) {
|
|
576
|
+
return {
|
|
577
|
+
id: stableId("perm", key),
|
|
578
|
+
key,
|
|
579
|
+
name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
|
|
580
|
+
description: extra.description ?? null
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
function effectivePermissions(seed, membership) {
|
|
584
|
+
if (!membership) return [];
|
|
585
|
+
const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
|
|
586
|
+
return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
|
|
587
|
+
}
|
|
366
588
|
function resolveSeed(input) {
|
|
367
589
|
const problems = [];
|
|
368
590
|
if (!isRecord(input)) {
|
|
@@ -373,6 +595,10 @@ function resolveSeed(input) {
|
|
|
373
595
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
374
596
|
const rawApplications = listOf(input.applications, "applications", problems);
|
|
375
597
|
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
598
|
+
const rawRoles = listOf(input.roles, "roles", problems);
|
|
599
|
+
const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
|
|
600
|
+
const rawPlans = listOf(input.plans, "plans", problems);
|
|
601
|
+
const rawPermissions = listOf(input.permissions, "permissions", problems);
|
|
376
602
|
const webhooks = [];
|
|
377
603
|
rawWebhooks.forEach((raw, index) => {
|
|
378
604
|
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
@@ -476,7 +702,107 @@ function resolveSeed(input) {
|
|
|
476
702
|
if (problems.length > 0) {
|
|
477
703
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
478
704
|
}
|
|
479
|
-
|
|
705
|
+
const permissions = [];
|
|
706
|
+
rawPermissions.forEach((raw, index) => {
|
|
707
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
708
|
+
problems.push(`permissions[${index}] needs a string "key".`);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (permissions.some((p) => p.key === raw.key)) {
|
|
712
|
+
problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
permissions.push(
|
|
716
|
+
permissionRecord(raw.key, {
|
|
717
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
718
|
+
description: typeof raw.description === "string" ? raw.description : void 0
|
|
719
|
+
})
|
|
720
|
+
);
|
|
721
|
+
});
|
|
722
|
+
const roles = [];
|
|
723
|
+
rawRoles.forEach((raw, index) => {
|
|
724
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
725
|
+
problems.push(`roles[${index}] needs a string "key".`);
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
if (roles.some((r) => r.key === raw.key)) {
|
|
729
|
+
problems.push(`roles[${index}] repeats the key "${raw.key}".`);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
|
|
733
|
+
problems.push(`roles[${index}].permissions must be a list of permission keys.`);
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
roles.push(
|
|
737
|
+
roleRecord(raw.key, {
|
|
738
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
739
|
+
description: typeof raw.description === "string" ? raw.description : void 0,
|
|
740
|
+
isDefault: raw.isDefault === true,
|
|
741
|
+
permissions: raw.permissions ?? []
|
|
742
|
+
})
|
|
743
|
+
);
|
|
744
|
+
});
|
|
745
|
+
if (problems.length > 0) {
|
|
746
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
747
|
+
}
|
|
748
|
+
const featureFlags = [];
|
|
749
|
+
rawFlags.forEach((raw, index) => {
|
|
750
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
|
|
751
|
+
problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
|
|
755
|
+
featureFlags.push({
|
|
756
|
+
id: stableId("flag", raw.key),
|
|
757
|
+
key: raw.key,
|
|
758
|
+
name: typeof raw.name === "string" ? raw.name : raw.key,
|
|
759
|
+
type,
|
|
760
|
+
value: raw.value,
|
|
761
|
+
organizations: isRecord(raw.organizations) ? raw.organizations : {}
|
|
762
|
+
});
|
|
763
|
+
});
|
|
764
|
+
const plans = [];
|
|
765
|
+
rawPlans.forEach((raw, index) => {
|
|
766
|
+
if (!isRecord(raw) || typeof raw.key !== "string") {
|
|
767
|
+
problems.push(`plans[${index}] needs a string "key".`);
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
|
|
771
|
+
plans.push({
|
|
772
|
+
key: raw.key,
|
|
773
|
+
name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
|
|
774
|
+
subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
|
|
775
|
+
subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
776
|
+
entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
|
|
777
|
+
id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
|
|
778
|
+
featureKey: e.featureKey,
|
|
779
|
+
featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
|
|
780
|
+
priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
|
|
781
|
+
fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
|
|
782
|
+
unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
|
|
783
|
+
limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
|
|
784
|
+
limitMin: typeof e.limitMin === "number" ? e.limitMin : null
|
|
785
|
+
}))
|
|
786
|
+
});
|
|
787
|
+
});
|
|
788
|
+
const userProperties = {};
|
|
789
|
+
rawUsers.forEach((raw) => {
|
|
790
|
+
if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
|
|
791
|
+
userProperties[raw.id] = raw.properties;
|
|
792
|
+
}
|
|
793
|
+
});
|
|
794
|
+
if (problems.length > 0) {
|
|
795
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
796
|
+
}
|
|
797
|
+
const usedRoles = new Set(memberships.flatMap((m) => m.roles));
|
|
798
|
+
for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
|
|
799
|
+
const usedPermissions = /* @__PURE__ */ new Set([
|
|
800
|
+
...memberships.flatMap((m) => m.permissions),
|
|
801
|
+
...roles.flatMap((r) => r.permissions),
|
|
802
|
+
...applications.flatMap((a) => a.permissions ?? [])
|
|
803
|
+
]);
|
|
804
|
+
for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
|
|
805
|
+
return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
|
|
480
806
|
}
|
|
481
807
|
function findUser(users, ref) {
|
|
482
808
|
const needle = ref.toLowerCase();
|
|
@@ -521,7 +847,7 @@ function seedScenario(seed, ref) {
|
|
|
521
847
|
user,
|
|
522
848
|
organization,
|
|
523
849
|
roles: [...membership?.roles ?? []],
|
|
524
|
-
permissions:
|
|
850
|
+
permissions: effectivePermissions(seed, membership),
|
|
525
851
|
claims: {}
|
|
526
852
|
};
|
|
527
853
|
}
|
|
@@ -536,72 +862,18 @@ function listOf(value, field, problems) {
|
|
|
536
862
|
function isRecord(value) {
|
|
537
863
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
538
864
|
}
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
*{box-sizing:border-box}
|
|
548
|
-
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}
|
|
549
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
550
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
551
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
552
|
-
p{margin:0;color:var(--muted)}
|
|
553
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
554
|
-
form{margin:0}
|
|
555
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
556
|
-
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}
|
|
557
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
558
|
-
.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}
|
|
559
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
560
|
-
.list{display:grid;gap:8px}
|
|
561
|
-
.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}
|
|
562
|
-
.option:hover{border-color:var(--muted)}
|
|
563
|
-
.option strong{display:block;font-weight:500}
|
|
564
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
565
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
566
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
567
|
-
`;
|
|
568
|
-
function escapeHtml(value) {
|
|
569
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
570
|
-
}
|
|
571
|
-
function layout(title, body) {
|
|
572
|
-
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>`;
|
|
573
|
-
}
|
|
574
|
-
function displayName(user) {
|
|
575
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
576
|
-
}
|
|
577
|
-
function renderSignIn(options) {
|
|
578
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
579
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
580
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
581
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
582
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
583
|
-
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>`;
|
|
584
|
-
}).join("");
|
|
585
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
586
|
-
return layout(
|
|
587
|
-
"Sign in",
|
|
588
|
-
`<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>`
|
|
589
|
-
);
|
|
590
|
-
}
|
|
591
|
-
function renderOrganizationPicker(options) {
|
|
592
|
-
const choices = options.organizations.map(
|
|
593
|
-
(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>`
|
|
594
|
-
).join("");
|
|
595
|
-
return layout(
|
|
596
|
-
"Choose an organization",
|
|
597
|
-
`<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>`
|
|
598
|
-
);
|
|
599
|
-
}
|
|
600
|
-
function renderMessage(title, message) {
|
|
601
|
-
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
865
|
+
function featureFlagsFor(seed, organizationCode) {
|
|
866
|
+
if (seed.featureFlags.length === 0) return void 0;
|
|
867
|
+
const claim = {};
|
|
868
|
+
for (const flag of seed.featureFlags) {
|
|
869
|
+
const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
|
|
870
|
+
claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
|
|
871
|
+
}
|
|
872
|
+
return claim;
|
|
602
873
|
}
|
|
603
874
|
|
|
604
875
|
// src/oauth.ts
|
|
876
|
+
import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
605
877
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
606
878
|
var OAuthError = class extends Error {
|
|
607
879
|
constructor(status, error, description) {
|
|
@@ -613,14 +885,16 @@ var OAuthError = class extends Error {
|
|
|
613
885
|
error;
|
|
614
886
|
};
|
|
615
887
|
var AuthorizationServer = class {
|
|
616
|
-
constructor(testkit, seed, emit = () => void 0) {
|
|
888
|
+
constructor(testkit, seed, emit = () => void 0, directory) {
|
|
617
889
|
this.testkit = testkit;
|
|
618
890
|
this.seed = seed;
|
|
619
891
|
this.emit = emit;
|
|
892
|
+
this.directory = directory;
|
|
620
893
|
}
|
|
621
894
|
testkit;
|
|
622
895
|
seed;
|
|
623
896
|
emit;
|
|
897
|
+
directory;
|
|
624
898
|
codes = /* @__PURE__ */ new Map();
|
|
625
899
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
626
900
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -686,6 +960,18 @@ var AuthorizationServer = class {
|
|
|
686
960
|
if (!user) {
|
|
687
961
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
688
962
|
}
|
|
963
|
+
if (this.directory?.isSuspended(user.id)) {
|
|
964
|
+
return sendHtml(
|
|
965
|
+
res,
|
|
966
|
+
403,
|
|
967
|
+
renderSignIn({
|
|
968
|
+
request: encoded,
|
|
969
|
+
users: this.loginPageUsers(),
|
|
970
|
+
requiredOrganization: request.orgCode ?? void 0,
|
|
971
|
+
error: `${user.email ?? user.id} is suspended and cannot sign in.`
|
|
972
|
+
})
|
|
973
|
+
);
|
|
974
|
+
}
|
|
689
975
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
690
976
|
const wanted = request.orgCode ?? form.org ?? null;
|
|
691
977
|
let organizationCode = null;
|
|
@@ -722,7 +1008,7 @@ var AuthorizationServer = class {
|
|
|
722
1008
|
user,
|
|
723
1009
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
724
1010
|
roles: [...membership?.roles ?? []],
|
|
725
|
-
permissions:
|
|
1011
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
726
1012
|
claims: {}
|
|
727
1013
|
};
|
|
728
1014
|
const code = randomToken();
|
|
@@ -738,6 +1024,7 @@ var AuthorizationServer = class {
|
|
|
738
1024
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
739
1025
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
740
1026
|
});
|
|
1027
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
741
1028
|
this.emit("user.authenticated", user);
|
|
742
1029
|
const target = new URL(request.redirectUri);
|
|
743
1030
|
target.searchParams.set("code", code);
|
|
@@ -773,7 +1060,7 @@ var AuthorizationServer = class {
|
|
|
773
1060
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
774
1061
|
}
|
|
775
1062
|
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
776
|
-
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1063
|
+
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
777
1064
|
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
778
1065
|
return {
|
|
779
1066
|
access_token: await this.testkit.m2mToken({
|
|
@@ -809,7 +1096,7 @@ var AuthorizationServer = class {
|
|
|
809
1096
|
}
|
|
810
1097
|
if (pending.codeChallenge) {
|
|
811
1098
|
const verifier = form.code_verifier ?? "";
|
|
812
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1099
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
813
1100
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
814
1101
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
815
1102
|
}
|
|
@@ -839,7 +1126,8 @@ var AuthorizationServer = class {
|
|
|
839
1126
|
scopes: grant.scope,
|
|
840
1127
|
clientId: grant.clientId,
|
|
841
1128
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
842
|
-
authTime: grant.authTime
|
|
1129
|
+
authTime: grant.authTime,
|
|
1130
|
+
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
843
1131
|
}),
|
|
844
1132
|
expires_in: this.testkit.accessTokenLifetime,
|
|
845
1133
|
scope: grant.scope.join(" "),
|
|
@@ -906,6 +1194,7 @@ var AuthorizationServer = class {
|
|
|
906
1194
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
907
1195
|
if (!this.signedUpUsers.has(user.id)) {
|
|
908
1196
|
this.signedUpUsers.set(user.id, user);
|
|
1197
|
+
if (this.directory) this.seed.users.push(user);
|
|
909
1198
|
this.emit("user.created", user);
|
|
910
1199
|
}
|
|
911
1200
|
return this.signedUpUsers.get(user.id);
|
|
@@ -993,7 +1282,7 @@ function isHttpUrl(value) {
|
|
|
993
1282
|
}
|
|
994
1283
|
}
|
|
995
1284
|
function randomToken() {
|
|
996
|
-
return
|
|
1285
|
+
return randomBytes2(32).toString("base64url");
|
|
997
1286
|
}
|
|
998
1287
|
function safeEqual(a, b) {
|
|
999
1288
|
const left = Buffer.from(a);
|
|
@@ -1017,6 +1306,687 @@ function sendJson(res, status, body) {
|
|
|
1017
1306
|
res.end(JSON.stringify(body));
|
|
1018
1307
|
}
|
|
1019
1308
|
|
|
1309
|
+
// src/account.ts
|
|
1310
|
+
var DEFAULT_PAGE_SIZE = 10;
|
|
1311
|
+
var AccountApi = class {
|
|
1312
|
+
constructor(testkit, directory) {
|
|
1313
|
+
this.testkit = testkit;
|
|
1314
|
+
this.directory = directory;
|
|
1315
|
+
}
|
|
1316
|
+
testkit;
|
|
1317
|
+
directory;
|
|
1318
|
+
async handle(req, res, url) {
|
|
1319
|
+
if (!url.pathname.startsWith("/account_api/v1/")) return false;
|
|
1320
|
+
if ((req.method ?? "GET") !== "GET") {
|
|
1321
|
+
sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
|
|
1322
|
+
return true;
|
|
1323
|
+
}
|
|
1324
|
+
const header = req.headers.authorization ?? "";
|
|
1325
|
+
let token;
|
|
1326
|
+
try {
|
|
1327
|
+
if (!header.startsWith("Bearer ")) throw new Error("missing");
|
|
1328
|
+
token = await this.testkit.verify(header.slice(7));
|
|
1329
|
+
} catch {
|
|
1330
|
+
sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
|
|
1331
|
+
return true;
|
|
1332
|
+
}
|
|
1333
|
+
if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
|
|
1334
|
+
sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
|
|
1335
|
+
return true;
|
|
1336
|
+
}
|
|
1337
|
+
const userId = token.sub;
|
|
1338
|
+
const orgCode = typeof token.org_code === "string" ? token.org_code : null;
|
|
1339
|
+
const path = url.pathname.slice("/account_api/v1/".length);
|
|
1340
|
+
const d = this.directory;
|
|
1341
|
+
const membership = orgCode ? d.membership(userId, orgCode) : void 0;
|
|
1342
|
+
if (path === "permissions") {
|
|
1343
|
+
const items = effectivePermissions(d.seed, membership).map((key) => {
|
|
1344
|
+
const p = d.ensurePermission(key);
|
|
1345
|
+
return { id: p.id, name: p.name, key: p.key };
|
|
1346
|
+
});
|
|
1347
|
+
sendPage(res, url, "permissions", items, { org_code: orgCode });
|
|
1348
|
+
return true;
|
|
1349
|
+
}
|
|
1350
|
+
if (path.startsWith("permission/")) {
|
|
1351
|
+
const key = decodeURIComponent(path.slice("permission/".length));
|
|
1352
|
+
sendJson2(res, 200, {
|
|
1353
|
+
data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
|
|
1354
|
+
});
|
|
1355
|
+
return true;
|
|
1356
|
+
}
|
|
1357
|
+
if (path === "roles") {
|
|
1358
|
+
const items = (membership?.roles ?? []).map((key) => {
|
|
1359
|
+
const r = d.ensureRole(key);
|
|
1360
|
+
return { id: r.id, name: r.name, key: r.key };
|
|
1361
|
+
});
|
|
1362
|
+
sendPage(res, url, "roles", items, { org_code: orgCode });
|
|
1363
|
+
return true;
|
|
1364
|
+
}
|
|
1365
|
+
if (path === "feature_flags") {
|
|
1366
|
+
const items = d.seed.featureFlags.map((flag) => ({
|
|
1367
|
+
id: flag.id,
|
|
1368
|
+
name: flag.name,
|
|
1369
|
+
key: flag.key,
|
|
1370
|
+
type: flag.type,
|
|
1371
|
+
value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
|
|
1372
|
+
}));
|
|
1373
|
+
sendPage(res, url, "feature_flags", items, {});
|
|
1374
|
+
return true;
|
|
1375
|
+
}
|
|
1376
|
+
if (path === "properties") {
|
|
1377
|
+
const values = d.seed.userProperties[userId] ?? {};
|
|
1378
|
+
const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
|
|
1379
|
+
sendPage(res, url, "properties", items, {});
|
|
1380
|
+
return true;
|
|
1381
|
+
}
|
|
1382
|
+
if (path === "entitlements" || path.startsWith("entitlement")) {
|
|
1383
|
+
const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
|
|
1384
|
+
const entitlements = (plan?.entitlements ?? []).map((e) => ({
|
|
1385
|
+
id: e.id,
|
|
1386
|
+
fixed_charge: e.fixedCharge,
|
|
1387
|
+
price_name: e.priceName,
|
|
1388
|
+
unit_amount: e.unitAmount,
|
|
1389
|
+
feature_key: e.featureKey,
|
|
1390
|
+
feature_name: e.featureName,
|
|
1391
|
+
entitlement_limit_max: e.limitMax,
|
|
1392
|
+
entitlement_limit_min: e.limitMin
|
|
1393
|
+
}));
|
|
1394
|
+
if (path === "entitlements") {
|
|
1395
|
+
const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
|
|
1396
|
+
sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
|
|
1397
|
+
return true;
|
|
1398
|
+
}
|
|
1399
|
+
const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
|
|
1400
|
+
const entitlement = entitlements.find((e) => e.feature_key === key);
|
|
1401
|
+
if (!entitlement) {
|
|
1402
|
+
sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
|
|
1403
|
+
} else {
|
|
1404
|
+
sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
|
|
1405
|
+
}
|
|
1406
|
+
return true;
|
|
1407
|
+
}
|
|
1408
|
+
if (path === "portal_link") {
|
|
1409
|
+
sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
|
|
1410
|
+
return true;
|
|
1411
|
+
}
|
|
1412
|
+
sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
|
|
1413
|
+
return true;
|
|
1414
|
+
}
|
|
1415
|
+
};
|
|
1416
|
+
function sendPage(res, url, field, items, extra) {
|
|
1417
|
+
const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
|
|
1418
|
+
const after = url.searchParams.get("starting_after");
|
|
1419
|
+
const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
|
|
1420
|
+
const page = items.slice(start, start + size);
|
|
1421
|
+
const hasMore = start + size < items.length;
|
|
1422
|
+
sendJson2(res, 200, {
|
|
1423
|
+
data: { ...extra, [field]: page },
|
|
1424
|
+
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
1425
|
+
});
|
|
1426
|
+
}
|
|
1427
|
+
function errors(code, message) {
|
|
1428
|
+
return { errors: [{ code, message }] };
|
|
1429
|
+
}
|
|
1430
|
+
function sendJson2(res, status, body) {
|
|
1431
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1432
|
+
res.end(JSON.stringify(body));
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
// src/directory.ts
|
|
1436
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1437
|
+
var Directory = class {
|
|
1438
|
+
constructor(seed) {
|
|
1439
|
+
this.seed = seed;
|
|
1440
|
+
this.snapshot = JSON.stringify(seed);
|
|
1441
|
+
}
|
|
1442
|
+
seed;
|
|
1443
|
+
userMeta = /* @__PURE__ */ new Map();
|
|
1444
|
+
orgMeta = /* @__PURE__ */ new Map();
|
|
1445
|
+
snapshot;
|
|
1446
|
+
restore() {
|
|
1447
|
+
const original = JSON.parse(this.snapshot);
|
|
1448
|
+
for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
|
|
1449
|
+
this.seed[key].splice(0, this.seed[key].length, ...original[key]);
|
|
1450
|
+
}
|
|
1451
|
+
this.userMeta.clear();
|
|
1452
|
+
this.orgMeta.clear();
|
|
1453
|
+
}
|
|
1454
|
+
user(id) {
|
|
1455
|
+
return this.seed.users.find((user) => user.id === id);
|
|
1456
|
+
}
|
|
1457
|
+
meta(user) {
|
|
1458
|
+
let meta = this.userMeta.get(user.id);
|
|
1459
|
+
if (!meta) {
|
|
1460
|
+
meta = {
|
|
1461
|
+
providedId: null,
|
|
1462
|
+
isSuspended: false,
|
|
1463
|
+
isPasswordResetRequested: false,
|
|
1464
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1465
|
+
totalSignIns: 0,
|
|
1466
|
+
lastSignedIn: null
|
|
1467
|
+
};
|
|
1468
|
+
this.userMeta.set(user.id, meta);
|
|
1469
|
+
}
|
|
1470
|
+
return meta;
|
|
1471
|
+
}
|
|
1472
|
+
isSuspended(userId) {
|
|
1473
|
+
return this.userMeta.get(userId)?.isSuspended ?? false;
|
|
1474
|
+
}
|
|
1475
|
+
recordSignIn(user, organizationCode) {
|
|
1476
|
+
const meta = this.meta(user);
|
|
1477
|
+
meta.totalSignIns += 1;
|
|
1478
|
+
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
1479
|
+
void organizationCode;
|
|
1480
|
+
}
|
|
1481
|
+
createUser(input) {
|
|
1482
|
+
const user = createKindeUser({
|
|
1483
|
+
id: `kp_${randomBytes3(16).toString("hex")}`,
|
|
1484
|
+
email: input.email ?? null,
|
|
1485
|
+
givenName: input.givenName ?? null,
|
|
1486
|
+
familyName: input.familyName ?? null,
|
|
1487
|
+
picture: input.picture ?? null
|
|
1488
|
+
});
|
|
1489
|
+
this.seed.users.push(user);
|
|
1490
|
+
this.meta(user).providedId = input.providedId ?? null;
|
|
1491
|
+
return user;
|
|
1492
|
+
}
|
|
1493
|
+
deleteUser(id) {
|
|
1494
|
+
const index = this.seed.users.findIndex((user) => user.id === id);
|
|
1495
|
+
if (index < 0) return false;
|
|
1496
|
+
this.seed.users.splice(index, 1);
|
|
1497
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1498
|
+
if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
|
|
1499
|
+
}
|
|
1500
|
+
this.userMeta.delete(id);
|
|
1501
|
+
return true;
|
|
1502
|
+
}
|
|
1503
|
+
organization(code) {
|
|
1504
|
+
return this.seed.organizations.find((org) => org.code === code);
|
|
1505
|
+
}
|
|
1506
|
+
orgInfo(org) {
|
|
1507
|
+
let meta = this.orgMeta.get(org.code);
|
|
1508
|
+
if (!meta) {
|
|
1509
|
+
meta = {
|
|
1510
|
+
externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
|
|
1511
|
+
handle: slug(org.name),
|
|
1512
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1513
|
+
isAllowRegistrations: false
|
|
1514
|
+
};
|
|
1515
|
+
this.orgMeta.set(org.code, meta);
|
|
1516
|
+
}
|
|
1517
|
+
return meta;
|
|
1518
|
+
}
|
|
1519
|
+
createOrganization(input) {
|
|
1520
|
+
const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
|
|
1521
|
+
this.seed.organizations.push(org);
|
|
1522
|
+
const meta = this.orgInfo(org);
|
|
1523
|
+
meta.externalId = input.externalId ?? null;
|
|
1524
|
+
if (input.handle) meta.handle = input.handle;
|
|
1525
|
+
return org;
|
|
1526
|
+
}
|
|
1527
|
+
deleteOrganization(code) {
|
|
1528
|
+
const index = this.seed.organizations.findIndex((org) => org.code === code);
|
|
1529
|
+
if (index < 0) return false;
|
|
1530
|
+
this.seed.organizations.splice(index, 1);
|
|
1531
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1532
|
+
if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
|
|
1533
|
+
}
|
|
1534
|
+
this.orgMeta.delete(code);
|
|
1535
|
+
return true;
|
|
1536
|
+
}
|
|
1537
|
+
membership(userId, organizationCode) {
|
|
1538
|
+
return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1539
|
+
}
|
|
1540
|
+
addMembership(userId, organizationCode, roles = [], permissions = []) {
|
|
1541
|
+
const existing = this.membership(userId, organizationCode);
|
|
1542
|
+
if (existing) return existing;
|
|
1543
|
+
const membership = createMembership({ userId, organizationCode, roles, permissions });
|
|
1544
|
+
this.seed.memberships.push(membership);
|
|
1545
|
+
for (const key of roles) this.ensureRole(key);
|
|
1546
|
+
for (const key of permissions) this.ensurePermission(key);
|
|
1547
|
+
return membership;
|
|
1548
|
+
}
|
|
1549
|
+
removeMembership(userId, organizationCode) {
|
|
1550
|
+
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1551
|
+
if (index < 0) return false;
|
|
1552
|
+
this.seed.memberships.splice(index, 1);
|
|
1553
|
+
return true;
|
|
1554
|
+
}
|
|
1555
|
+
role(idOrKey) {
|
|
1556
|
+
return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
|
|
1557
|
+
}
|
|
1558
|
+
permission(idOrKey) {
|
|
1559
|
+
return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
|
|
1560
|
+
}
|
|
1561
|
+
ensureRole(key, extra = {}) {
|
|
1562
|
+
const existing = this.role(key);
|
|
1563
|
+
if (existing) return existing;
|
|
1564
|
+
const role = roleRecord(key, extra);
|
|
1565
|
+
this.seed.roles.push(role);
|
|
1566
|
+
return role;
|
|
1567
|
+
}
|
|
1568
|
+
ensurePermission(key, extra = {}) {
|
|
1569
|
+
const existing = this.permission(key);
|
|
1570
|
+
if (existing) return existing;
|
|
1571
|
+
const permission = permissionRecord(key, extra);
|
|
1572
|
+
this.seed.permissions.push(permission);
|
|
1573
|
+
return permission;
|
|
1574
|
+
}
|
|
1575
|
+
deleteRole(id) {
|
|
1576
|
+
const role = this.role(id);
|
|
1577
|
+
if (!role) return void 0;
|
|
1578
|
+
this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
|
|
1579
|
+
for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
|
|
1580
|
+
return role;
|
|
1581
|
+
}
|
|
1582
|
+
deletePermission(id) {
|
|
1583
|
+
const permission = this.permission(id);
|
|
1584
|
+
if (!permission) return void 0;
|
|
1585
|
+
this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
|
|
1586
|
+
for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
|
|
1587
|
+
for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
|
|
1588
|
+
return permission;
|
|
1589
|
+
}
|
|
1590
|
+
};
|
|
1591
|
+
|
|
1592
|
+
// src/management.ts
|
|
1593
|
+
var OK = { code: "OK", message: "Success" };
|
|
1594
|
+
var DEFAULT_PAGE_SIZE2 = 10;
|
|
1595
|
+
var MAX_PAGE_SIZE = 500;
|
|
1596
|
+
var ManagementApi = class {
|
|
1597
|
+
constructor(testkit, directory, webhooks) {
|
|
1598
|
+
this.testkit = testkit;
|
|
1599
|
+
this.directory = directory;
|
|
1600
|
+
this.webhooks = webhooks;
|
|
1601
|
+
this.register();
|
|
1602
|
+
}
|
|
1603
|
+
testkit;
|
|
1604
|
+
directory;
|
|
1605
|
+
webhooks;
|
|
1606
|
+
routes = [];
|
|
1607
|
+
async handle(req, res, url, readBody) {
|
|
1608
|
+
if (!url.pathname.startsWith("/api/v1/")) return false;
|
|
1609
|
+
const method = req.method ?? "GET";
|
|
1610
|
+
const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
1611
|
+
if (!route) {
|
|
1612
|
+
sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
|
|
1613
|
+
return true;
|
|
1614
|
+
}
|
|
1615
|
+
const token = await this.authenticate(req.headers.authorization);
|
|
1616
|
+
if ("error" in token) {
|
|
1617
|
+
sendJson3(res, 403, errors2(token.code, token.error));
|
|
1618
|
+
return true;
|
|
1619
|
+
}
|
|
1620
|
+
const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
|
|
1621
|
+
if (granted.length > 0 && !granted.includes(route.scope)) {
|
|
1622
|
+
sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
|
|
1623
|
+
return true;
|
|
1624
|
+
}
|
|
1625
|
+
const match = route.pattern.exec(url.pathname);
|
|
1626
|
+
const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
|
|
1627
|
+
const body = method === "GET" || method === "DELETE" ? {} : await readBody();
|
|
1628
|
+
const [status, payload] = await route.handler({ params, query: url.searchParams, body });
|
|
1629
|
+
sendJson3(res, status, payload);
|
|
1630
|
+
return true;
|
|
1631
|
+
}
|
|
1632
|
+
async authenticate(header) {
|
|
1633
|
+
if (!header?.startsWith("Bearer ")) {
|
|
1634
|
+
return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
|
|
1635
|
+
}
|
|
1636
|
+
let payload;
|
|
1637
|
+
try {
|
|
1638
|
+
payload = await this.testkit.verify(header.slice(7));
|
|
1639
|
+
} catch {
|
|
1640
|
+
return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
|
|
1641
|
+
}
|
|
1642
|
+
const audience = `${this.testkit.issuer}/api`;
|
|
1643
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
1644
|
+
if (!aud.includes(audience)) {
|
|
1645
|
+
return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
|
|
1646
|
+
}
|
|
1647
|
+
if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
|
|
1648
|
+
return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
|
|
1649
|
+
}
|
|
1650
|
+
return { payload };
|
|
1651
|
+
}
|
|
1652
|
+
route(method, path, scope, handler) {
|
|
1653
|
+
const keys = [];
|
|
1654
|
+
const pattern = new RegExp(
|
|
1655
|
+
`^${path.replace(/\{(\w+)\}/g, (_, key) => {
|
|
1656
|
+
keys.push(key);
|
|
1657
|
+
return "([^/]+)";
|
|
1658
|
+
})}$`
|
|
1659
|
+
);
|
|
1660
|
+
this.routes.push({ method, pattern, keys, scope, handler });
|
|
1661
|
+
}
|
|
1662
|
+
register() {
|
|
1663
|
+
const d = this.directory;
|
|
1664
|
+
this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
|
|
1665
|
+
let users = [...d.seed.users];
|
|
1666
|
+
const userId = query.get("user_id");
|
|
1667
|
+
const email = query.get("email")?.toLowerCase();
|
|
1668
|
+
if (userId) users = users.filter((u) => u.id === userId);
|
|
1669
|
+
if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
|
|
1670
|
+
const page = paginate(users, query);
|
|
1671
|
+
return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
|
|
1672
|
+
});
|
|
1673
|
+
this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
|
|
1674
|
+
const user = d.user(query.get("id") ?? "");
|
|
1675
|
+
return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
|
|
1676
|
+
});
|
|
1677
|
+
this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
|
|
1678
|
+
const profile = body.profile ?? {};
|
|
1679
|
+
const identities = Array.isArray(body.identities) ? body.identities : [];
|
|
1680
|
+
const emailIdentity = identities.find((i) => i.type === "email");
|
|
1681
|
+
const email = (emailIdentity?.details ?? {}).email;
|
|
1682
|
+
if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
|
|
1683
|
+
return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
|
|
1684
|
+
}
|
|
1685
|
+
const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
|
|
1686
|
+
if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
|
|
1687
|
+
const user = d.createUser({
|
|
1688
|
+
email: typeof email === "string" ? email : null,
|
|
1689
|
+
givenName: str(profile.given_name),
|
|
1690
|
+
familyName: str(profile.family_name),
|
|
1691
|
+
picture: str(profile.picture),
|
|
1692
|
+
providedId: str(body.provided_id)
|
|
1693
|
+
});
|
|
1694
|
+
if (orgCode) d.addMembership(user.id, orgCode);
|
|
1695
|
+
this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
|
|
1696
|
+
return [
|
|
1697
|
+
200,
|
|
1698
|
+
{ id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
|
|
1699
|
+
];
|
|
1700
|
+
});
|
|
1701
|
+
this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
|
|
1702
|
+
const user = d.user(query.get("id") ?? "");
|
|
1703
|
+
if (!user) return notFound("USER_INVALID", "No user has that id.");
|
|
1704
|
+
if (typeof body.given_name === "string") user.givenName = body.given_name;
|
|
1705
|
+
if (typeof body.family_name === "string") user.familyName = body.family_name;
|
|
1706
|
+
if (typeof body.picture === "string") user.picture = body.picture;
|
|
1707
|
+
const meta = d.meta(user);
|
|
1708
|
+
if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
|
|
1709
|
+
if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
|
|
1710
|
+
if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
|
|
1711
|
+
this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
|
|
1712
|
+
return [
|
|
1713
|
+
200,
|
|
1714
|
+
{
|
|
1715
|
+
id: user.id,
|
|
1716
|
+
given_name: user.givenName,
|
|
1717
|
+
family_name: user.familyName,
|
|
1718
|
+
email: user.email,
|
|
1719
|
+
is_suspended: meta.isSuspended,
|
|
1720
|
+
is_password_reset_requested: meta.isPasswordResetRequested,
|
|
1721
|
+
picture: user.picture
|
|
1722
|
+
}
|
|
1723
|
+
];
|
|
1724
|
+
});
|
|
1725
|
+
this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
|
|
1726
|
+
const id = query.get("id") ?? "";
|
|
1727
|
+
if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
|
|
1728
|
+
this.webhooks.emit("user.deleted", { user: { id } });
|
|
1729
|
+
return [200, OK];
|
|
1730
|
+
});
|
|
1731
|
+
this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
|
|
1732
|
+
const page = paginate(d.seed.organizations, query);
|
|
1733
|
+
return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
|
|
1734
|
+
});
|
|
1735
|
+
this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
|
|
1736
|
+
const org = d.organization(query.get("code") ?? "");
|
|
1737
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1738
|
+
const meta = d.orgInfo(org);
|
|
1739
|
+
return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
|
|
1740
|
+
});
|
|
1741
|
+
this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
|
|
1742
|
+
if (typeof body.name !== "string" || body.name.trim() === "") {
|
|
1743
|
+
return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
|
|
1744
|
+
}
|
|
1745
|
+
const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
|
|
1746
|
+
if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
|
|
1747
|
+
this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
|
|
1748
|
+
return [200, { ...OK, organization: { code: org.code } }];
|
|
1749
|
+
});
|
|
1750
|
+
this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
|
|
1751
|
+
const org = d.organization(params.org_code);
|
|
1752
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1753
|
+
const meta = d.orgInfo(org);
|
|
1754
|
+
if (typeof body.name === "string") org.name = body.name;
|
|
1755
|
+
if (typeof body.external_id === "string") meta.externalId = body.external_id;
|
|
1756
|
+
if (typeof body.handle === "string") meta.handle = body.handle;
|
|
1757
|
+
if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
|
|
1758
|
+
this.webhooks.emit("organization.updated", {
|
|
1759
|
+
organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
|
|
1760
|
+
});
|
|
1761
|
+
return [200, OK];
|
|
1762
|
+
});
|
|
1763
|
+
this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
|
|
1764
|
+
if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1765
|
+
this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
|
|
1766
|
+
return [200, OK];
|
|
1767
|
+
});
|
|
1768
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
|
|
1769
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1770
|
+
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);
|
|
1771
|
+
const page = paginate(members, query);
|
|
1772
|
+
return [
|
|
1773
|
+
200,
|
|
1774
|
+
{
|
|
1775
|
+
...OK,
|
|
1776
|
+
organization_users: page.items.map(({ membership, user }) => ({
|
|
1777
|
+
id: user.id,
|
|
1778
|
+
email: user.email,
|
|
1779
|
+
full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
|
|
1780
|
+
last_name: user.familyName,
|
|
1781
|
+
first_name: user.givenName,
|
|
1782
|
+
picture: user.picture,
|
|
1783
|
+
joined_on: d.meta(user).createdOn,
|
|
1784
|
+
last_accessed_on: d.meta(user).lastSignedIn,
|
|
1785
|
+
is_suspended: d.meta(user).isSuspended,
|
|
1786
|
+
roles: [...membership.roles]
|
|
1787
|
+
})),
|
|
1788
|
+
next_token: page.nextToken
|
|
1789
|
+
}
|
|
1790
|
+
];
|
|
1791
|
+
});
|
|
1792
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
|
|
1793
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1794
|
+
const users = Array.isArray(body.users) ? body.users : [];
|
|
1795
|
+
const added = [];
|
|
1796
|
+
const blocked = [];
|
|
1797
|
+
for (const entry of users) {
|
|
1798
|
+
const id = typeof entry.id === "string" ? entry.id : "";
|
|
1799
|
+
if (!d.user(id)) {
|
|
1800
|
+
blocked.push(id);
|
|
1801
|
+
continue;
|
|
1802
|
+
}
|
|
1803
|
+
d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
|
|
1804
|
+
added.push(id);
|
|
1805
|
+
}
|
|
1806
|
+
return [200, { ...OK, users_added: added, users_blocked: blocked }];
|
|
1807
|
+
});
|
|
1808
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
|
|
1809
|
+
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}.`);
|
|
1810
|
+
});
|
|
1811
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
|
|
1812
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1813
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1814
|
+
const roles = membership.roles.map((key) => d.ensureRole(key));
|
|
1815
|
+
return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
|
|
1816
|
+
});
|
|
1817
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
|
|
1818
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1819
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1820
|
+
const role = d.role(str(body.role_id) ?? "");
|
|
1821
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1822
|
+
if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
|
|
1823
|
+
return [200, OK];
|
|
1824
|
+
});
|
|
1825
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
|
|
1826
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1827
|
+
const role = d.role(params.role_id);
|
|
1828
|
+
if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
|
|
1829
|
+
membership.roles = membership.roles.filter((key) => key !== role.key);
|
|
1830
|
+
return [200, OK];
|
|
1831
|
+
});
|
|
1832
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
|
|
1833
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1834
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1835
|
+
const permissions = effectivePermissions(d.seed, membership).map((key) => {
|
|
1836
|
+
const permission = d.ensurePermission(key);
|
|
1837
|
+
const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
|
|
1838
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
|
|
1839
|
+
});
|
|
1840
|
+
return [200, { ...OK, permissions }];
|
|
1841
|
+
});
|
|
1842
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
|
|
1843
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1844
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1845
|
+
const permission = d.permission(str(body.permission_id) ?? "");
|
|
1846
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1847
|
+
if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
|
|
1848
|
+
return [200, OK];
|
|
1849
|
+
});
|
|
1850
|
+
this.route(
|
|
1851
|
+
"DELETE",
|
|
1852
|
+
"/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
|
|
1853
|
+
"delete:organization_user_permissions",
|
|
1854
|
+
({ params }) => {
|
|
1855
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1856
|
+
const permission = d.permission(params.permission_id);
|
|
1857
|
+
if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
|
|
1858
|
+
membership.permissions = membership.permissions.filter((key) => key !== permission.key);
|
|
1859
|
+
return [200, OK];
|
|
1860
|
+
}
|
|
1861
|
+
);
|
|
1862
|
+
this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
|
|
1863
|
+
const page = paginate(d.seed.roles, query);
|
|
1864
|
+
return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
|
|
1865
|
+
});
|
|
1866
|
+
this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
|
|
1867
|
+
const key = str(body.key);
|
|
1868
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
|
|
1869
|
+
if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
|
|
1870
|
+
const role = d.ensureRole(key, {
|
|
1871
|
+
name: str(body.name) ?? void 0,
|
|
1872
|
+
description: str(body.description) ?? void 0,
|
|
1873
|
+
isDefault: body.is_default_role === true
|
|
1874
|
+
});
|
|
1875
|
+
this.webhooks.emit("role.created", {
|
|
1876
|
+
role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
|
|
1877
|
+
});
|
|
1878
|
+
return [201, { ...OK, role: { id: role.id } }];
|
|
1879
|
+
});
|
|
1880
|
+
this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
|
|
1881
|
+
const role = d.role(params.role_id);
|
|
1882
|
+
return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
|
|
1883
|
+
});
|
|
1884
|
+
this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
|
|
1885
|
+
const role = d.deleteRole(params.role_id);
|
|
1886
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1887
|
+
this.webhooks.emit("role.deleted", { role: { id: role.id } });
|
|
1888
|
+
return [200, OK];
|
|
1889
|
+
});
|
|
1890
|
+
this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
|
|
1891
|
+
const role = d.role(params.role_id);
|
|
1892
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1893
|
+
return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
|
|
1894
|
+
});
|
|
1895
|
+
this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
|
|
1896
|
+
const page = paginate(d.seed.permissions, query);
|
|
1897
|
+
return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
|
|
1898
|
+
});
|
|
1899
|
+
this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
|
|
1900
|
+
const key = str(body.key);
|
|
1901
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
|
|
1902
|
+
if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
|
|
1903
|
+
const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
|
|
1904
|
+
this.webhooks.emit("permission.created", {
|
|
1905
|
+
permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
|
|
1906
|
+
});
|
|
1907
|
+
return [201, OK];
|
|
1908
|
+
});
|
|
1909
|
+
this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
|
|
1910
|
+
const permission = d.deletePermission(params.permission_id);
|
|
1911
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1912
|
+
this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
|
|
1913
|
+
return [200, OK];
|
|
1914
|
+
});
|
|
1915
|
+
}
|
|
1916
|
+
userListItem(user) {
|
|
1917
|
+
const meta = this.directory.meta(user);
|
|
1918
|
+
return {
|
|
1919
|
+
id: user.id,
|
|
1920
|
+
provided_id: meta.providedId,
|
|
1921
|
+
email: user.email,
|
|
1922
|
+
phone: null,
|
|
1923
|
+
username: null,
|
|
1924
|
+
last_name: user.familyName,
|
|
1925
|
+
first_name: user.givenName,
|
|
1926
|
+
is_suspended: meta.isSuspended,
|
|
1927
|
+
picture: user.picture,
|
|
1928
|
+
total_sign_ins: meta.totalSignIns,
|
|
1929
|
+
failed_sign_ins: 0,
|
|
1930
|
+
last_signed_in: meta.lastSignedIn,
|
|
1931
|
+
created_on: meta.createdOn,
|
|
1932
|
+
organizations: this.organizationsOf(user),
|
|
1933
|
+
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
1934
|
+
};
|
|
1935
|
+
}
|
|
1936
|
+
userDetail(user) {
|
|
1937
|
+
const { email, ...rest } = this.userListItem(user);
|
|
1938
|
+
return { ...rest, preferred_email: email };
|
|
1939
|
+
}
|
|
1940
|
+
organizationsOf(user) {
|
|
1941
|
+
return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
|
|
1942
|
+
}
|
|
1943
|
+
organizationItem(org) {
|
|
1944
|
+
const meta = this.directory.orgInfo(org);
|
|
1945
|
+
return {
|
|
1946
|
+
code: org.code,
|
|
1947
|
+
name: org.name,
|
|
1948
|
+
handle: meta.handle,
|
|
1949
|
+
is_default: false,
|
|
1950
|
+
external_id: meta.externalId,
|
|
1951
|
+
is_auto_membership_enabled: false
|
|
1952
|
+
};
|
|
1953
|
+
}
|
|
1954
|
+
organizationEvent(org) {
|
|
1955
|
+
const meta = this.directory.orgInfo(org);
|
|
1956
|
+
return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
|
|
1957
|
+
}
|
|
1958
|
+
roleItem(role) {
|
|
1959
|
+
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
1960
|
+
}
|
|
1961
|
+
permissionItem(permission) {
|
|
1962
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
1963
|
+
}
|
|
1964
|
+
};
|
|
1965
|
+
function paginate(items, query) {
|
|
1966
|
+
const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
|
|
1967
|
+
const token = query.get("next_token");
|
|
1968
|
+
const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
|
|
1969
|
+
const page = items.slice(offset, offset + size);
|
|
1970
|
+
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
1971
|
+
return { items: page, nextToken: next };
|
|
1972
|
+
}
|
|
1973
|
+
function errors2(code, message) {
|
|
1974
|
+
return { errors: [{ code, message }] };
|
|
1975
|
+
}
|
|
1976
|
+
function notFound(code, message) {
|
|
1977
|
+
return [404, errors2(code, message)];
|
|
1978
|
+
}
|
|
1979
|
+
function str(value) {
|
|
1980
|
+
return typeof value === "string" ? value : null;
|
|
1981
|
+
}
|
|
1982
|
+
function strings(value) {
|
|
1983
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
1984
|
+
}
|
|
1985
|
+
function sendJson3(res, status, body) {
|
|
1986
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1987
|
+
res.end(JSON.stringify(body));
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1020
1990
|
// src/failures.ts
|
|
1021
1991
|
var MAX_DELAY_MS = 6e4;
|
|
1022
1992
|
var FailureInjector = class {
|
|
@@ -1098,7 +2068,7 @@ function validate(rule) {
|
|
|
1098
2068
|
}
|
|
1099
2069
|
|
|
1100
2070
|
// src/webhooks.ts
|
|
1101
|
-
import { randomBytes as
|
|
2071
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
1102
2072
|
var WEBHOOK_EVENT_TYPES = [
|
|
1103
2073
|
"user.created",
|
|
1104
2074
|
"user.updated",
|
|
@@ -1181,7 +2151,7 @@ var WebhookDispatcher = class {
|
|
|
1181
2151
|
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1182
2152
|
const event = {
|
|
1183
2153
|
data: options.data ?? this.buildData(options),
|
|
1184
|
-
event_id: `event_${
|
|
2154
|
+
event_id: `event_${randomBytes4(16).toString("hex")}`,
|
|
1185
2155
|
event_timestamp: timestamp,
|
|
1186
2156
|
source: options.source ?? "admin",
|
|
1187
2157
|
timestamp,
|
|
@@ -1214,7 +2184,7 @@ var WebhookDispatcher = class {
|
|
|
1214
2184
|
options.invalid === "stale" ? void 0 : options.invalid
|
|
1215
2185
|
);
|
|
1216
2186
|
const jobs = targets.flatMap((target) => {
|
|
1217
|
-
const webhookId = `wh_${
|
|
2187
|
+
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
1218
2188
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1219
2189
|
});
|
|
1220
2190
|
return Promise.all(jobs);
|
|
@@ -1295,6 +2265,13 @@ var WebhookDispatcher = class {
|
|
|
1295
2265
|
);
|
|
1296
2266
|
}
|
|
1297
2267
|
}
|
|
2268
|
+
emit(type, data, source = "api") {
|
|
2269
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2270
|
+
void this.send({ type, data, source }).catch(() => void 0);
|
|
2271
|
+
}
|
|
2272
|
+
userEventData(user) {
|
|
2273
|
+
return this.userPayload(user);
|
|
2274
|
+
}
|
|
1298
2275
|
emitForUser(type, user) {
|
|
1299
2276
|
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1300
2277
|
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
@@ -1359,7 +2336,7 @@ function isHttpUrl2(value) {
|
|
|
1359
2336
|
}
|
|
1360
2337
|
}
|
|
1361
2338
|
function sleep(ms) {
|
|
1362
|
-
return new Promise((
|
|
2339
|
+
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1363
2340
|
}
|
|
1364
2341
|
|
|
1365
2342
|
// src/server.ts
|
|
@@ -1377,30 +2354,36 @@ async function startKindeTestkit(options = {}) {
|
|
|
1377
2354
|
const seed = resolveSeed(options.seed ?? {});
|
|
1378
2355
|
const failures = new FailureInjector();
|
|
1379
2356
|
let ready;
|
|
1380
|
-
const testkitReady = new Promise((
|
|
1381
|
-
const
|
|
2357
|
+
const testkitReady = new Promise((resolve2) => ready = resolve2);
|
|
2358
|
+
const listener = (req, res) => {
|
|
1382
2359
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1383
|
-
}
|
|
1384
|
-
|
|
2360
|
+
};
|
|
2361
|
+
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
2362
|
+
const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
|
|
2363
|
+
await new Promise((resolve2, reject) => {
|
|
1385
2364
|
server.once("error", reject);
|
|
1386
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
2365
|
+
server.listen(options.port ?? 4400, host, () => resolve2());
|
|
1387
2366
|
});
|
|
1388
2367
|
const { port } = server.address();
|
|
1389
2368
|
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1390
|
-
const url =
|
|
2369
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1391
2370
|
const testkit = await KindeTestkit.create({
|
|
1392
2371
|
issuer: options.issuer ?? options.seed?.issuer ?? url,
|
|
1393
2372
|
audience: options.audience ?? options.seed?.audience,
|
|
1394
2373
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1395
2374
|
});
|
|
2375
|
+
const directory = new Directory(seed);
|
|
1396
2376
|
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
1397
|
-
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
|
|
2377
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
|
|
2378
|
+
const management = new ManagementApi(testkit, directory, webhooks);
|
|
2379
|
+
const account = new AccountApi(testkit, directory);
|
|
1398
2380
|
const reset = () => {
|
|
1399
2381
|
auth.reset();
|
|
1400
2382
|
failures.clear();
|
|
1401
2383
|
webhooks.reset();
|
|
2384
|
+
directory.restore();
|
|
1402
2385
|
};
|
|
1403
|
-
ready({ testkit, auth, seed, failures, webhooks, reset });
|
|
2386
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
|
|
1404
2387
|
return {
|
|
1405
2388
|
url,
|
|
1406
2389
|
issuer: testkit.issuer,
|
|
@@ -1410,10 +2393,12 @@ async function startKindeTestkit(options = {}) {
|
|
|
1410
2393
|
seed,
|
|
1411
2394
|
failures,
|
|
1412
2395
|
webhooks,
|
|
2396
|
+
directory,
|
|
2397
|
+
certificatePath: certificate?.certPath ?? null,
|
|
1413
2398
|
reset,
|
|
1414
|
-
close: () => new Promise((
|
|
2399
|
+
close: () => new Promise((resolve2, reject) => {
|
|
1415
2400
|
server.closeAllConnections();
|
|
1416
|
-
server.close((error) => error ? reject(error) :
|
|
2401
|
+
server.close((error) => error ? reject(error) : resolve2());
|
|
1417
2402
|
})
|
|
1418
2403
|
};
|
|
1419
2404
|
}
|
|
@@ -1426,68 +2411,77 @@ async function handle(req, res, context) {
|
|
|
1426
2411
|
const failure = failures.take(method, pathname);
|
|
1427
2412
|
if (failure) {
|
|
1428
2413
|
if (failure.hang) return;
|
|
1429
|
-
if (failure.delayMs > 0) await new Promise((
|
|
2414
|
+
if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
|
|
1430
2415
|
if (failure.status !== null) {
|
|
1431
2416
|
const headers = {};
|
|
1432
2417
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1433
|
-
return
|
|
2418
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1434
2419
|
}
|
|
1435
2420
|
}
|
|
1436
2421
|
}
|
|
1437
2422
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
2423
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
|
|
2424
|
+
if (await context.account.handle(req, res, url)) return;
|
|
2425
|
+
if (method === "GET" && pathname === "/testkit/portal") {
|
|
2426
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
2427
|
+
res.end(
|
|
2428
|
+
`<!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>`
|
|
2429
|
+
);
|
|
2430
|
+
return;
|
|
2431
|
+
}
|
|
1438
2432
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1439
|
-
return
|
|
2433
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1440
2434
|
}
|
|
1441
2435
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1442
|
-
return
|
|
2436
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1443
2437
|
}
|
|
1444
2438
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1445
|
-
return
|
|
2439
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1446
2440
|
}
|
|
1447
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
2441
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
1448
2442
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1449
|
-
return
|
|
2443
|
+
return sendJson4(res, 200, seed.organizations);
|
|
1450
2444
|
}
|
|
1451
2445
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1452
|
-
return
|
|
2446
|
+
return sendJson4(res, 200, seed.memberships);
|
|
1453
2447
|
}
|
|
1454
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
2448
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1455
2449
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1456
|
-
return
|
|
2450
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1457
2451
|
}
|
|
1458
2452
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1459
2453
|
failures.clear();
|
|
1460
|
-
return
|
|
2454
|
+
return sendJson4(res, 200, { ok: true });
|
|
1461
2455
|
}
|
|
1462
2456
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1463
2457
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1464
|
-
return
|
|
2458
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1465
2459
|
}
|
|
1466
2460
|
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1467
|
-
return
|
|
2461
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
1468
2462
|
}
|
|
1469
2463
|
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1470
|
-
return
|
|
2464
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1471
2465
|
}
|
|
1472
|
-
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return
|
|
1473
|
-
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return
|
|
2466
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
|
|
2467
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
|
|
1474
2468
|
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1475
|
-
return
|
|
2469
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1476
2470
|
}
|
|
1477
2471
|
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1478
2472
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1479
|
-
return
|
|
2473
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1480
2474
|
}
|
|
1481
2475
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1482
2476
|
context.reset();
|
|
1483
|
-
return
|
|
2477
|
+
return sendJson4(res, 200, { ok: true });
|
|
1484
2478
|
}
|
|
1485
2479
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1486
2480
|
const body = await readJson(req);
|
|
1487
2481
|
const accessToken = await issueToken(testkit, seed, body);
|
|
1488
|
-
return
|
|
2482
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
1489
2483
|
}
|
|
1490
|
-
return
|
|
2484
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
1491
2485
|
}
|
|
1492
2486
|
function discovery(testkit) {
|
|
1493
2487
|
const base = testkit.issuer;
|
|
@@ -1546,7 +2540,11 @@ async function issueToken(testkit, seed, body) {
|
|
|
1546
2540
|
});
|
|
1547
2541
|
if (permissions) scenario.permissions = permissions;
|
|
1548
2542
|
if (roles) scenario.roles = roles;
|
|
1549
|
-
return await testkit.tokenFor(scenario, {
|
|
2543
|
+
return await testkit.tokenFor(scenario, {
|
|
2544
|
+
expiresIn,
|
|
2545
|
+
invalid: invalid2,
|
|
2546
|
+
featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
|
|
2547
|
+
});
|
|
1550
2548
|
}
|
|
1551
2549
|
const options = {
|
|
1552
2550
|
subject: optionalString(input, "subject"),
|
|
@@ -1611,7 +2609,7 @@ async function readText(req) {
|
|
|
1611
2609
|
}
|
|
1612
2610
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1613
2611
|
}
|
|
1614
|
-
function
|
|
2612
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1615
2613
|
res.writeHead(status, {
|
|
1616
2614
|
"content-type": "application/json; charset=utf-8",
|
|
1617
2615
|
"cache-control": "no-store",
|
|
@@ -1625,10 +2623,10 @@ function sendError(res, error) {
|
|
|
1625
2623
|
return;
|
|
1626
2624
|
}
|
|
1627
2625
|
if (error instanceof TestkitError) {
|
|
1628
|
-
|
|
2626
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1629
2627
|
return;
|
|
1630
2628
|
}
|
|
1631
|
-
|
|
2629
|
+
sendJson4(res, 500, {
|
|
1632
2630
|
error: "server_error",
|
|
1633
2631
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1634
2632
|
});
|