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/vitest.js
CHANGED
|
@@ -129,6 +129,20 @@ var INVALID_TOKEN_KINDS = [
|
|
|
129
129
|
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
130
130
|
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
131
131
|
var KindeTestkit = class _KindeTestkit {
|
|
132
|
+
observers = [];
|
|
133
|
+
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
134
|
+
observe(observer) {
|
|
135
|
+
this.observers.push(observer);
|
|
136
|
+
return () => {
|
|
137
|
+
this.observers = this.observers.filter((o) => o !== observer);
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
async signAccess(payload, invalid2, now) {
|
|
141
|
+
const final = applyInvalidClaims(payload, invalid2, now);
|
|
142
|
+
const token = await this.sign(final, invalid2);
|
|
143
|
+
for (const observer of this.observers) observer.accessToken?.(final, invalid2, token);
|
|
144
|
+
return token;
|
|
145
|
+
}
|
|
132
146
|
issuer;
|
|
133
147
|
audience;
|
|
134
148
|
clientId;
|
|
@@ -188,7 +202,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
188
202
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
189
203
|
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
190
204
|
Object.assign(payload, options.claims ?? {});
|
|
191
|
-
return this.
|
|
205
|
+
return this.signAccess(payload, options.invalid, now);
|
|
192
206
|
}
|
|
193
207
|
async m2mToken(options = {}) {
|
|
194
208
|
const now = this.clock();
|
|
@@ -209,10 +223,13 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
209
223
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
210
224
|
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
211
225
|
Object.assign(payload, options.claims ?? {});
|
|
212
|
-
return this.
|
|
226
|
+
return this.signAccess(payload, options.invalid, now);
|
|
213
227
|
}
|
|
214
228
|
async tokenFor(scenario, overrides = {}) {
|
|
215
|
-
if (scenario.kind === "unauthenticated")
|
|
229
|
+
if (scenario.kind === "unauthenticated") {
|
|
230
|
+
for (const observer of this.observers) observer.anonymous?.();
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
216
233
|
return this.token({
|
|
217
234
|
subject: scenario.user.id,
|
|
218
235
|
organizationCode: scenario.organization?.code ?? null,
|
|
@@ -254,7 +271,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
254
271
|
for (const key of Object.keys(payload)) {
|
|
255
272
|
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
256
273
|
}
|
|
257
|
-
|
|
274
|
+
const token = await this.sign(payload);
|
|
275
|
+
for (const observer of this.observers) observer.idToken?.(payload, token);
|
|
276
|
+
return token;
|
|
258
277
|
}
|
|
259
278
|
async headersFor(scenario, overrides = {}) {
|
|
260
279
|
const token = await this.tokenFor(scenario, overrides);
|
|
@@ -361,8 +380,230 @@ function getDefaultTestkit() {
|
|
|
361
380
|
|
|
362
381
|
// src/server.ts
|
|
363
382
|
import { createServer } from "http";
|
|
383
|
+
import { createServer as createHttpsServer } from "https";
|
|
384
|
+
|
|
385
|
+
// src/certificate.ts
|
|
386
|
+
import { createHash as createHash2, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
|
|
387
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
388
|
+
import { join, resolve } from "path";
|
|
389
|
+
var CERT_FILE = "localhost-cert.pem";
|
|
390
|
+
var KEY_FILE = "localhost-key.pem";
|
|
391
|
+
var VALID_DAYS = 825;
|
|
392
|
+
function ensureLocalCertificate(directory = ".kinde-testkit") {
|
|
393
|
+
const dir = resolve(directory);
|
|
394
|
+
const certPath = join(dir, CERT_FILE);
|
|
395
|
+
const keyPath = join(dir, KEY_FILE);
|
|
396
|
+
if (existsSync(certPath) && existsSync(keyPath)) {
|
|
397
|
+
const cert2 = readFileSync(certPath, "utf8");
|
|
398
|
+
const key2 = readFileSync(keyPath, "utf8");
|
|
399
|
+
try {
|
|
400
|
+
if (new Date(new X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
|
|
401
|
+
return { cert: cert2, key: key2, certPath, keyPath, created: false };
|
|
402
|
+
}
|
|
403
|
+
} catch {
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
const { cert, key } = createLocalCertificate();
|
|
407
|
+
mkdirSync(dir, { recursive: true });
|
|
408
|
+
writeFileSync(certPath, cert);
|
|
409
|
+
writeFileSync(keyPath, key, { mode: 384 });
|
|
410
|
+
writeFileSync(join(dir, ".gitignore"), "*\n");
|
|
411
|
+
return { cert, key, certPath, keyPath, created: true };
|
|
412
|
+
}
|
|
413
|
+
function createLocalCertificate() {
|
|
414
|
+
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
415
|
+
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
416
|
+
const keyId = createHash2("sha1").update(subjectPublicKeyBits(spki)).digest();
|
|
417
|
+
const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
|
|
418
|
+
const now = Date.now();
|
|
419
|
+
const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
|
|
420
|
+
const serial = randomBytes(16);
|
|
421
|
+
serial[0] &= 127;
|
|
422
|
+
const extensions = seq(
|
|
423
|
+
seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
|
|
424
|
+
seq(oid("2.5.29.14"), octets(octets(keyId))),
|
|
425
|
+
seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
|
|
426
|
+
seq(
|
|
427
|
+
oid("2.5.29.17"),
|
|
428
|
+
octets(
|
|
429
|
+
seq(
|
|
430
|
+
tlv(130, Buffer.from("localhost")),
|
|
431
|
+
tlv(135, Buffer.from([127, 0, 0, 1])),
|
|
432
|
+
tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
|
|
433
|
+
)
|
|
434
|
+
)
|
|
435
|
+
)
|
|
436
|
+
);
|
|
437
|
+
const tbs = seq(
|
|
438
|
+
tlv(160, integer(Buffer.from([2]))),
|
|
439
|
+
integer(serial),
|
|
440
|
+
algorithm,
|
|
441
|
+
name,
|
|
442
|
+
seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
|
|
443
|
+
name,
|
|
444
|
+
spki,
|
|
445
|
+
tlv(163, extensions)
|
|
446
|
+
);
|
|
447
|
+
const signature = sign("sha256", tbs, privateKey);
|
|
448
|
+
const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
|
|
449
|
+
return {
|
|
450
|
+
cert: pem("CERTIFICATE", der),
|
|
451
|
+
key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function subjectPublicKeyBits(spki) {
|
|
455
|
+
const outer = readTlv(spki, 0);
|
|
456
|
+
const algorithm = readTlv(spki, outer.start);
|
|
457
|
+
const bits = readTlv(spki, algorithm.end);
|
|
458
|
+
return spki.subarray(bits.start + 1, bits.end);
|
|
459
|
+
}
|
|
460
|
+
function readTlv(buf, offset) {
|
|
461
|
+
let len = buf[offset + 1];
|
|
462
|
+
let header = 2;
|
|
463
|
+
if (len & 128) {
|
|
464
|
+
const n = len & 127;
|
|
465
|
+
len = 0;
|
|
466
|
+
for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
|
|
467
|
+
header += n;
|
|
468
|
+
}
|
|
469
|
+
return { start: offset + header, end: offset + header + len };
|
|
470
|
+
}
|
|
471
|
+
function tlv(tag, content) {
|
|
472
|
+
return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
|
|
473
|
+
}
|
|
474
|
+
function length(n) {
|
|
475
|
+
if (n < 128) return Buffer.from([n]);
|
|
476
|
+
const bytes = [];
|
|
477
|
+
while (n > 0) {
|
|
478
|
+
bytes.unshift(n & 255);
|
|
479
|
+
n >>= 8;
|
|
480
|
+
}
|
|
481
|
+
return Buffer.from([128 | bytes.length, ...bytes]);
|
|
482
|
+
}
|
|
483
|
+
function seq(...items) {
|
|
484
|
+
return tlv(48, Buffer.concat(items));
|
|
485
|
+
}
|
|
486
|
+
function set(...items) {
|
|
487
|
+
return tlv(49, Buffer.concat(items));
|
|
488
|
+
}
|
|
489
|
+
function octets(content) {
|
|
490
|
+
return tlv(4, content);
|
|
491
|
+
}
|
|
492
|
+
function integer(bytes) {
|
|
493
|
+
return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
|
|
494
|
+
}
|
|
495
|
+
function oid(dotted) {
|
|
496
|
+
const parts = dotted.split(".").map(Number);
|
|
497
|
+
const bytes = [parts[0] * 40 + parts[1]];
|
|
498
|
+
for (const part of parts.slice(2)) {
|
|
499
|
+
const chunk = [part & 127];
|
|
500
|
+
let value = part >> 7;
|
|
501
|
+
while (value > 0) {
|
|
502
|
+
chunk.unshift(value & 127 | 128);
|
|
503
|
+
value >>= 7;
|
|
504
|
+
}
|
|
505
|
+
bytes.push(...chunk);
|
|
506
|
+
}
|
|
507
|
+
return tlv(6, Buffer.from(bytes));
|
|
508
|
+
}
|
|
509
|
+
function utcTime(date) {
|
|
510
|
+
const iso = date.toISOString();
|
|
511
|
+
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`;
|
|
512
|
+
return tlv(23, Buffer.from(value));
|
|
513
|
+
}
|
|
514
|
+
function pem(label, der) {
|
|
515
|
+
const body = der.toString("base64").match(/.{1,64}/g).join("\n");
|
|
516
|
+
return `-----BEGIN ${label}-----
|
|
517
|
+
${body}
|
|
518
|
+
-----END ${label}-----
|
|
519
|
+
`;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// src/login-page.ts
|
|
523
|
+
var STYLE = `
|
|
524
|
+
: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}
|
|
525
|
+
@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}}
|
|
526
|
+
*{box-sizing:border-box}
|
|
527
|
+
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}
|
|
528
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
529
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
530
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
531
|
+
p{margin:0;color:var(--muted)}
|
|
532
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
533
|
+
form{margin:0}
|
|
534
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
535
|
+
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}
|
|
536
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
537
|
+
.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}
|
|
538
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
539
|
+
.list{display:grid;gap:8px}
|
|
540
|
+
.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}
|
|
541
|
+
.option:hover{border-color:var(--muted)}
|
|
542
|
+
.option strong{display:block;font-weight:500}
|
|
543
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
544
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
545
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
546
|
+
`;
|
|
547
|
+
function escapeHtml(value) {
|
|
548
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
549
|
+
}
|
|
550
|
+
function layout(title, body) {
|
|
551
|
+
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>`;
|
|
552
|
+
}
|
|
553
|
+
function displayName(user) {
|
|
554
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
555
|
+
}
|
|
556
|
+
function renderSignIn(options) {
|
|
557
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
558
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
559
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
560
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
561
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
562
|
+
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>`;
|
|
563
|
+
}).join("");
|
|
564
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
565
|
+
return layout(
|
|
566
|
+
"Sign in",
|
|
567
|
+
`<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>`
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
function renderOrganizationPicker(options) {
|
|
571
|
+
const choices = options.organizations.map(
|
|
572
|
+
(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>`
|
|
573
|
+
).join("");
|
|
574
|
+
return layout(
|
|
575
|
+
"Choose an organization",
|
|
576
|
+
`<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>`
|
|
577
|
+
);
|
|
578
|
+
}
|
|
579
|
+
function renderMessage(title, message) {
|
|
580
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
581
|
+
}
|
|
364
582
|
|
|
365
583
|
// src/seed.ts
|
|
584
|
+
function roleRecord(key, extra = {}) {
|
|
585
|
+
return {
|
|
586
|
+
id: stableId("role", key),
|
|
587
|
+
key,
|
|
588
|
+
name: extra.name ?? titleCase(key),
|
|
589
|
+
description: extra.description ?? null,
|
|
590
|
+
isDefault: extra.isDefault ?? false,
|
|
591
|
+
permissions: [...extra.permissions ?? []]
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
function permissionRecord(key, extra = {}) {
|
|
595
|
+
return {
|
|
596
|
+
id: stableId("perm", key),
|
|
597
|
+
key,
|
|
598
|
+
name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
|
|
599
|
+
description: extra.description ?? null
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
function effectivePermissions(seed, membership) {
|
|
603
|
+
if (!membership) return [];
|
|
604
|
+
const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
|
|
605
|
+
return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
|
|
606
|
+
}
|
|
366
607
|
function resolveSeed(input) {
|
|
367
608
|
const problems = [];
|
|
368
609
|
if (!isRecord(input)) {
|
|
@@ -373,6 +614,10 @@ function resolveSeed(input) {
|
|
|
373
614
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
374
615
|
const rawApplications = listOf(input.applications, "applications", problems);
|
|
375
616
|
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
617
|
+
const rawRoles = listOf(input.roles, "roles", problems);
|
|
618
|
+
const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
|
|
619
|
+
const rawPlans = listOf(input.plans, "plans", problems);
|
|
620
|
+
const rawPermissions = listOf(input.permissions, "permissions", problems);
|
|
376
621
|
const webhooks = [];
|
|
377
622
|
rawWebhooks.forEach((raw, index) => {
|
|
378
623
|
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
@@ -476,7 +721,107 @@ function resolveSeed(input) {
|
|
|
476
721
|
if (problems.length > 0) {
|
|
477
722
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
478
723
|
}
|
|
479
|
-
|
|
724
|
+
const permissions = [];
|
|
725
|
+
rawPermissions.forEach((raw, index) => {
|
|
726
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
727
|
+
problems.push(`permissions[${index}] needs a string "key".`);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
if (permissions.some((p) => p.key === raw.key)) {
|
|
731
|
+
problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
permissions.push(
|
|
735
|
+
permissionRecord(raw.key, {
|
|
736
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
737
|
+
description: typeof raw.description === "string" ? raw.description : void 0
|
|
738
|
+
})
|
|
739
|
+
);
|
|
740
|
+
});
|
|
741
|
+
const roles = [];
|
|
742
|
+
rawRoles.forEach((raw, index) => {
|
|
743
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
744
|
+
problems.push(`roles[${index}] needs a string "key".`);
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
if (roles.some((r) => r.key === raw.key)) {
|
|
748
|
+
problems.push(`roles[${index}] repeats the key "${raw.key}".`);
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
|
|
752
|
+
problems.push(`roles[${index}].permissions must be a list of permission keys.`);
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
roles.push(
|
|
756
|
+
roleRecord(raw.key, {
|
|
757
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
758
|
+
description: typeof raw.description === "string" ? raw.description : void 0,
|
|
759
|
+
isDefault: raw.isDefault === true,
|
|
760
|
+
permissions: raw.permissions ?? []
|
|
761
|
+
})
|
|
762
|
+
);
|
|
763
|
+
});
|
|
764
|
+
if (problems.length > 0) {
|
|
765
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
766
|
+
}
|
|
767
|
+
const featureFlags = [];
|
|
768
|
+
rawFlags.forEach((raw, index) => {
|
|
769
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
|
|
770
|
+
problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
|
|
774
|
+
featureFlags.push({
|
|
775
|
+
id: stableId("flag", raw.key),
|
|
776
|
+
key: raw.key,
|
|
777
|
+
name: typeof raw.name === "string" ? raw.name : raw.key,
|
|
778
|
+
type,
|
|
779
|
+
value: raw.value,
|
|
780
|
+
organizations: isRecord(raw.organizations) ? raw.organizations : {}
|
|
781
|
+
});
|
|
782
|
+
});
|
|
783
|
+
const plans = [];
|
|
784
|
+
rawPlans.forEach((raw, index) => {
|
|
785
|
+
if (!isRecord(raw) || typeof raw.key !== "string") {
|
|
786
|
+
problems.push(`plans[${index}] needs a string "key".`);
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
|
|
790
|
+
plans.push({
|
|
791
|
+
key: raw.key,
|
|
792
|
+
name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
|
|
793
|
+
subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
|
|
794
|
+
subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
795
|
+
entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
|
|
796
|
+
id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
|
|
797
|
+
featureKey: e.featureKey,
|
|
798
|
+
featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
|
|
799
|
+
priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
|
|
800
|
+
fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
|
|
801
|
+
unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
|
|
802
|
+
limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
|
|
803
|
+
limitMin: typeof e.limitMin === "number" ? e.limitMin : null
|
|
804
|
+
}))
|
|
805
|
+
});
|
|
806
|
+
});
|
|
807
|
+
const userProperties = {};
|
|
808
|
+
rawUsers.forEach((raw) => {
|
|
809
|
+
if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
|
|
810
|
+
userProperties[raw.id] = raw.properties;
|
|
811
|
+
}
|
|
812
|
+
});
|
|
813
|
+
if (problems.length > 0) {
|
|
814
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
815
|
+
}
|
|
816
|
+
const usedRoles = new Set(memberships.flatMap((m) => m.roles));
|
|
817
|
+
for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
|
|
818
|
+
const usedPermissions = /* @__PURE__ */ new Set([
|
|
819
|
+
...memberships.flatMap((m) => m.permissions),
|
|
820
|
+
...roles.flatMap((r) => r.permissions),
|
|
821
|
+
...applications.flatMap((a) => a.permissions ?? [])
|
|
822
|
+
]);
|
|
823
|
+
for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
|
|
824
|
+
return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
|
|
480
825
|
}
|
|
481
826
|
function findUser(users, ref) {
|
|
482
827
|
const needle = ref.toLowerCase();
|
|
@@ -521,7 +866,7 @@ function seedScenario(seed, ref) {
|
|
|
521
866
|
user,
|
|
522
867
|
organization,
|
|
523
868
|
roles: [...membership?.roles ?? []],
|
|
524
|
-
permissions:
|
|
869
|
+
permissions: effectivePermissions(seed, membership),
|
|
525
870
|
claims: {}
|
|
526
871
|
};
|
|
527
872
|
}
|
|
@@ -536,72 +881,18 @@ function listOf(value, field, problems) {
|
|
|
536
881
|
function isRecord(value) {
|
|
537
882
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
538
883
|
}
|
|
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>`);
|
|
884
|
+
function featureFlagsFor(seed, organizationCode) {
|
|
885
|
+
if (seed.featureFlags.length === 0) return void 0;
|
|
886
|
+
const claim = {};
|
|
887
|
+
for (const flag of seed.featureFlags) {
|
|
888
|
+
const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
|
|
889
|
+
claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
|
|
890
|
+
}
|
|
891
|
+
return claim;
|
|
602
892
|
}
|
|
603
893
|
|
|
604
894
|
// src/oauth.ts
|
|
895
|
+
import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
605
896
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
606
897
|
var OAuthError = class extends Error {
|
|
607
898
|
constructor(status, error, description) {
|
|
@@ -613,14 +904,18 @@ var OAuthError = class extends Error {
|
|
|
613
904
|
error;
|
|
614
905
|
};
|
|
615
906
|
var AuthorizationServer = class {
|
|
616
|
-
constructor(testkit, seed, emit = () => void 0) {
|
|
907
|
+
constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
|
|
617
908
|
this.testkit = testkit;
|
|
618
909
|
this.seed = seed;
|
|
619
910
|
this.emit = emit;
|
|
911
|
+
this.directory = directory;
|
|
912
|
+
this.observe = observe;
|
|
620
913
|
}
|
|
621
914
|
testkit;
|
|
622
915
|
seed;
|
|
623
916
|
emit;
|
|
917
|
+
directory;
|
|
918
|
+
observe;
|
|
624
919
|
codes = /* @__PURE__ */ new Map();
|
|
625
920
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
626
921
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -657,6 +952,7 @@ var AuthorizationServer = class {
|
|
|
657
952
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
658
953
|
}
|
|
659
954
|
if (params.get("prompt") === "none") {
|
|
955
|
+
this.observe("session.silent");
|
|
660
956
|
return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
661
957
|
}
|
|
662
958
|
sendHtml(
|
|
@@ -670,15 +966,15 @@ var AuthorizationServer = class {
|
|
|
670
966
|
})
|
|
671
967
|
);
|
|
672
968
|
}
|
|
673
|
-
login(res,
|
|
969
|
+
login(res, form2) {
|
|
674
970
|
let request;
|
|
675
971
|
try {
|
|
676
|
-
request = decodeRequest(
|
|
972
|
+
request = decodeRequest(form2.request ?? "");
|
|
677
973
|
} catch {
|
|
678
974
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
679
975
|
}
|
|
680
976
|
const encoded = encodeRequest(request);
|
|
681
|
-
const ref = (
|
|
977
|
+
const ref = (form2.user || form2.email || "").trim();
|
|
682
978
|
if (!ref) {
|
|
683
979
|
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." }));
|
|
684
980
|
}
|
|
@@ -686,11 +982,25 @@ var AuthorizationServer = class {
|
|
|
686
982
|
if (!user) {
|
|
687
983
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
688
984
|
}
|
|
985
|
+
if (this.directory?.isSuspended(user.id)) {
|
|
986
|
+
this.observe("identity.suspended");
|
|
987
|
+
return sendHtml(
|
|
988
|
+
res,
|
|
989
|
+
403,
|
|
990
|
+
renderSignIn({
|
|
991
|
+
request: encoded,
|
|
992
|
+
users: this.loginPageUsers(),
|
|
993
|
+
requiredOrganization: request.orgCode ?? void 0,
|
|
994
|
+
error: `${user.email ?? user.id} is suspended and cannot sign in.`
|
|
995
|
+
})
|
|
996
|
+
);
|
|
997
|
+
}
|
|
689
998
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
690
|
-
const wanted = request.orgCode ??
|
|
999
|
+
const wanted = request.orgCode ?? form2.org ?? null;
|
|
691
1000
|
let organizationCode = null;
|
|
692
1001
|
if (wanted) {
|
|
693
1002
|
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
1003
|
+
this.observe("organization.non-member");
|
|
694
1004
|
return sendHtml(
|
|
695
1005
|
res,
|
|
696
1006
|
403,
|
|
@@ -722,7 +1032,7 @@ var AuthorizationServer = class {
|
|
|
722
1032
|
user,
|
|
723
1033
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
724
1034
|
roles: [...membership?.roles ?? []],
|
|
725
|
-
permissions:
|
|
1035
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
726
1036
|
claims: {}
|
|
727
1037
|
};
|
|
728
1038
|
const code = randomToken();
|
|
@@ -738,24 +1048,27 @@ var AuthorizationServer = class {
|
|
|
738
1048
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
739
1049
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
740
1050
|
});
|
|
1051
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
741
1052
|
this.emit("user.authenticated", user);
|
|
742
1053
|
const target = new URL(request.redirectUri);
|
|
743
1054
|
target.searchParams.set("code", code);
|
|
744
1055
|
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
745
1056
|
redirect(res, target.toString());
|
|
746
1057
|
}
|
|
747
|
-
async token(req, res,
|
|
1058
|
+
async token(req, res, form2) {
|
|
748
1059
|
try {
|
|
749
|
-
const clientId = clientIdFrom(req,
|
|
750
|
-
const grantType =
|
|
1060
|
+
const clientId = clientIdFrom(req, form2);
|
|
1061
|
+
const grantType = form2.grant_type;
|
|
751
1062
|
if (grantType === "client_credentials") {
|
|
752
|
-
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req,
|
|
1063
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
|
|
753
1064
|
}
|
|
754
1065
|
let grant;
|
|
755
1066
|
if (grantType === "authorization_code") {
|
|
756
|
-
grant = this.redeemCode(
|
|
1067
|
+
grant = this.redeemCode(form2, clientId);
|
|
1068
|
+
this.observe("session.sign-in");
|
|
757
1069
|
} else if (grantType === "refresh_token") {
|
|
758
|
-
grant = this.redeemRefreshToken(
|
|
1070
|
+
grant = this.redeemRefreshToken(form2, clientId);
|
|
1071
|
+
this.observe("session.refresh");
|
|
759
1072
|
} else {
|
|
760
1073
|
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
761
1074
|
}
|
|
@@ -767,14 +1080,14 @@ var AuthorizationServer = class {
|
|
|
767
1080
|
throw error;
|
|
768
1081
|
}
|
|
769
1082
|
}
|
|
770
|
-
async clientCredentials(clientId, clientSecret,
|
|
1083
|
+
async clientCredentials(clientId, clientSecret, form2) {
|
|
771
1084
|
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
772
1085
|
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
773
1086
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
774
1087
|
}
|
|
775
|
-
const requested = (
|
|
776
|
-
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
777
|
-
const audience = (
|
|
1088
|
+
const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
|
|
1089
|
+
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1090
|
+
const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
|
|
778
1091
|
return {
|
|
779
1092
|
access_token: await this.testkit.m2mToken({
|
|
780
1093
|
clientId,
|
|
@@ -794,8 +1107,8 @@ var AuthorizationServer = class {
|
|
|
794
1107
|
this.refreshTokens.clear();
|
|
795
1108
|
this.signedUpUsers.clear();
|
|
796
1109
|
}
|
|
797
|
-
redeemCode(
|
|
798
|
-
const code =
|
|
1110
|
+
redeemCode(form2, clientId) {
|
|
1111
|
+
const code = form2.code ?? "";
|
|
799
1112
|
const pending = this.codes.get(code);
|
|
800
1113
|
this.codes.delete(code);
|
|
801
1114
|
if (!pending || pending.expiresAt < Date.now()) {
|
|
@@ -804,20 +1117,20 @@ var AuthorizationServer = class {
|
|
|
804
1117
|
if (pending.clientId !== clientId) {
|
|
805
1118
|
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
806
1119
|
}
|
|
807
|
-
if (
|
|
1120
|
+
if (form2.redirect_uri !== pending.redirectUri) {
|
|
808
1121
|
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
809
1122
|
}
|
|
810
1123
|
if (pending.codeChallenge) {
|
|
811
|
-
const verifier =
|
|
812
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1124
|
+
const verifier = form2.code_verifier ?? "";
|
|
1125
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
813
1126
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
814
1127
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
815
1128
|
}
|
|
816
1129
|
}
|
|
817
1130
|
return pending;
|
|
818
1131
|
}
|
|
819
|
-
redeemRefreshToken(
|
|
820
|
-
const token =
|
|
1132
|
+
redeemRefreshToken(form2, clientId) {
|
|
1133
|
+
const token = form2.refresh_token ?? "";
|
|
821
1134
|
const grant = this.refreshTokens.get(token);
|
|
822
1135
|
this.refreshTokens.delete(token);
|
|
823
1136
|
if (!grant) {
|
|
@@ -839,7 +1152,8 @@ var AuthorizationServer = class {
|
|
|
839
1152
|
scopes: grant.scope,
|
|
840
1153
|
clientId: grant.clientId,
|
|
841
1154
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
842
|
-
authTime: grant.authTime
|
|
1155
|
+
authTime: grant.authTime,
|
|
1156
|
+
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
843
1157
|
}),
|
|
844
1158
|
expires_in: this.testkit.accessTokenLifetime,
|
|
845
1159
|
scope: grant.scope.join(" "),
|
|
@@ -890,11 +1204,13 @@ var AuthorizationServer = class {
|
|
|
890
1204
|
phone: null
|
|
891
1205
|
});
|
|
892
1206
|
}
|
|
893
|
-
revoke(res,
|
|
894
|
-
if (
|
|
1207
|
+
revoke(res, form2) {
|
|
1208
|
+
if (form2.token) this.refreshTokens.delete(form2.token);
|
|
1209
|
+
this.observe("session.revoke");
|
|
895
1210
|
sendJson(res, 200, {});
|
|
896
1211
|
}
|
|
897
1212
|
logout(res, params) {
|
|
1213
|
+
this.observe("session.sign-out");
|
|
898
1214
|
const target = params.get("redirect");
|
|
899
1215
|
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
900
1216
|
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
@@ -906,6 +1222,8 @@ var AuthorizationServer = class {
|
|
|
906
1222
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
907
1223
|
if (!this.signedUpUsers.has(user.id)) {
|
|
908
1224
|
this.signedUpUsers.set(user.id, user);
|
|
1225
|
+
this.observe("identity.unseeded");
|
|
1226
|
+
if (this.directory) this.seed.users.push(user);
|
|
909
1227
|
this.emit("user.created", user);
|
|
910
1228
|
}
|
|
911
1229
|
return this.signedUpUsers.get(user.id);
|
|
@@ -958,24 +1276,24 @@ function decodeRequest(value) {
|
|
|
958
1276
|
}
|
|
959
1277
|
return request;
|
|
960
1278
|
}
|
|
961
|
-
function clientIdFrom(req,
|
|
1279
|
+
function clientIdFrom(req, form2) {
|
|
962
1280
|
const header = req.headers.authorization ?? "";
|
|
963
1281
|
if (header.startsWith("Basic ")) {
|
|
964
1282
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
965
1283
|
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
966
1284
|
if (id) return id;
|
|
967
1285
|
}
|
|
968
|
-
if (
|
|
1286
|
+
if (form2.client_id) return form2.client_id;
|
|
969
1287
|
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
970
1288
|
}
|
|
971
|
-
function clientSecretFrom(req,
|
|
1289
|
+
function clientSecretFrom(req, form2) {
|
|
972
1290
|
const header = req.headers.authorization ?? "";
|
|
973
1291
|
if (header.startsWith("Basic ")) {
|
|
974
1292
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
975
1293
|
const index = decoded.indexOf(":");
|
|
976
1294
|
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
977
1295
|
}
|
|
978
|
-
return
|
|
1296
|
+
return form2.client_secret ?? null;
|
|
979
1297
|
}
|
|
980
1298
|
function redirectWithError(res, request, error, description) {
|
|
981
1299
|
const target = new URL(request.redirectUri);
|
|
@@ -993,7 +1311,7 @@ function isHttpUrl(value) {
|
|
|
993
1311
|
}
|
|
994
1312
|
}
|
|
995
1313
|
function randomToken() {
|
|
996
|
-
return
|
|
1314
|
+
return randomBytes2(32).toString("base64url");
|
|
997
1315
|
}
|
|
998
1316
|
function safeEqual(a, b) {
|
|
999
1317
|
const left = Buffer.from(a);
|
|
@@ -1017,6 +1335,703 @@ function sendJson(res, status, body) {
|
|
|
1017
1335
|
res.end(JSON.stringify(body));
|
|
1018
1336
|
}
|
|
1019
1337
|
|
|
1338
|
+
// src/account.ts
|
|
1339
|
+
var DEFAULT_PAGE_SIZE = 10;
|
|
1340
|
+
var AccountApi = class {
|
|
1341
|
+
constructor(testkit, directory) {
|
|
1342
|
+
this.testkit = testkit;
|
|
1343
|
+
this.directory = directory;
|
|
1344
|
+
}
|
|
1345
|
+
testkit;
|
|
1346
|
+
directory;
|
|
1347
|
+
async handle(req, res, url) {
|
|
1348
|
+
if (!url.pathname.startsWith("/account_api/v1/")) return false;
|
|
1349
|
+
if ((req.method ?? "GET") !== "GET") {
|
|
1350
|
+
sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
|
|
1351
|
+
return true;
|
|
1352
|
+
}
|
|
1353
|
+
const header = req.headers.authorization ?? "";
|
|
1354
|
+
let token;
|
|
1355
|
+
try {
|
|
1356
|
+
if (!header.startsWith("Bearer ")) throw new Error("missing");
|
|
1357
|
+
token = await this.testkit.verify(header.slice(7));
|
|
1358
|
+
} catch {
|
|
1359
|
+
sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
|
|
1360
|
+
return true;
|
|
1361
|
+
}
|
|
1362
|
+
if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
|
|
1363
|
+
sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
|
|
1364
|
+
return true;
|
|
1365
|
+
}
|
|
1366
|
+
const userId = token.sub;
|
|
1367
|
+
const orgCode = typeof token.org_code === "string" ? token.org_code : null;
|
|
1368
|
+
const path = url.pathname.slice("/account_api/v1/".length);
|
|
1369
|
+
const d = this.directory;
|
|
1370
|
+
const membership = orgCode ? d.membership(userId, orgCode) : void 0;
|
|
1371
|
+
if (path === "permissions") {
|
|
1372
|
+
const items = effectivePermissions(d.seed, membership).map((key) => {
|
|
1373
|
+
const p = d.ensurePermission(key);
|
|
1374
|
+
return { id: p.id, name: p.name, key: p.key };
|
|
1375
|
+
});
|
|
1376
|
+
sendPage(res, url, "permissions", items, { org_code: orgCode });
|
|
1377
|
+
return true;
|
|
1378
|
+
}
|
|
1379
|
+
if (path.startsWith("permission/")) {
|
|
1380
|
+
const key = decodeURIComponent(path.slice("permission/".length));
|
|
1381
|
+
sendJson2(res, 200, {
|
|
1382
|
+
data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
|
|
1383
|
+
});
|
|
1384
|
+
return true;
|
|
1385
|
+
}
|
|
1386
|
+
if (path === "roles") {
|
|
1387
|
+
const items = (membership?.roles ?? []).map((key) => {
|
|
1388
|
+
const r = d.ensureRole(key);
|
|
1389
|
+
return { id: r.id, name: r.name, key: r.key };
|
|
1390
|
+
});
|
|
1391
|
+
sendPage(res, url, "roles", items, { org_code: orgCode });
|
|
1392
|
+
return true;
|
|
1393
|
+
}
|
|
1394
|
+
if (path === "feature_flags") {
|
|
1395
|
+
const items = d.seed.featureFlags.map((flag) => ({
|
|
1396
|
+
id: flag.id,
|
|
1397
|
+
name: flag.name,
|
|
1398
|
+
key: flag.key,
|
|
1399
|
+
type: flag.type,
|
|
1400
|
+
value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
|
|
1401
|
+
}));
|
|
1402
|
+
sendPage(res, url, "feature_flags", items, {});
|
|
1403
|
+
return true;
|
|
1404
|
+
}
|
|
1405
|
+
if (path === "properties") {
|
|
1406
|
+
const values = d.seed.userProperties[userId] ?? {};
|
|
1407
|
+
const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
|
|
1408
|
+
sendPage(res, url, "properties", items, {});
|
|
1409
|
+
return true;
|
|
1410
|
+
}
|
|
1411
|
+
if (path === "entitlements" || path.startsWith("entitlement")) {
|
|
1412
|
+
const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
|
|
1413
|
+
const entitlements = (plan?.entitlements ?? []).map((e) => ({
|
|
1414
|
+
id: e.id,
|
|
1415
|
+
fixed_charge: e.fixedCharge,
|
|
1416
|
+
price_name: e.priceName,
|
|
1417
|
+
unit_amount: e.unitAmount,
|
|
1418
|
+
feature_key: e.featureKey,
|
|
1419
|
+
feature_name: e.featureName,
|
|
1420
|
+
entitlement_limit_max: e.limitMax,
|
|
1421
|
+
entitlement_limit_min: e.limitMin
|
|
1422
|
+
}));
|
|
1423
|
+
if (path === "entitlements") {
|
|
1424
|
+
const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
|
|
1425
|
+
sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
|
|
1426
|
+
return true;
|
|
1427
|
+
}
|
|
1428
|
+
const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
|
|
1429
|
+
const entitlement = entitlements.find((e) => e.feature_key === key);
|
|
1430
|
+
if (!entitlement) {
|
|
1431
|
+
sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
|
|
1432
|
+
} else {
|
|
1433
|
+
sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
|
|
1434
|
+
}
|
|
1435
|
+
return true;
|
|
1436
|
+
}
|
|
1437
|
+
if (path === "portal_link") {
|
|
1438
|
+
sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
|
|
1439
|
+
return true;
|
|
1440
|
+
}
|
|
1441
|
+
sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
|
|
1442
|
+
return true;
|
|
1443
|
+
}
|
|
1444
|
+
};
|
|
1445
|
+
function sendPage(res, url, field, items, extra) {
|
|
1446
|
+
const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
|
|
1447
|
+
const after = url.searchParams.get("starting_after");
|
|
1448
|
+
const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
|
|
1449
|
+
const page = items.slice(start, start + size);
|
|
1450
|
+
const hasMore = start + size < items.length;
|
|
1451
|
+
sendJson2(res, 200, {
|
|
1452
|
+
data: { ...extra, [field]: page },
|
|
1453
|
+
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
1454
|
+
});
|
|
1455
|
+
}
|
|
1456
|
+
function errors(code, message) {
|
|
1457
|
+
return { errors: [{ code, message }] };
|
|
1458
|
+
}
|
|
1459
|
+
function sendJson2(res, status, body) {
|
|
1460
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1461
|
+
res.end(JSON.stringify(body));
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// src/directory.ts
|
|
1465
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1466
|
+
var Directory = class {
|
|
1467
|
+
constructor(seed) {
|
|
1468
|
+
this.seed = seed;
|
|
1469
|
+
this.snapshot = JSON.stringify(seed);
|
|
1470
|
+
}
|
|
1471
|
+
seed;
|
|
1472
|
+
userMeta = /* @__PURE__ */ new Map();
|
|
1473
|
+
orgMeta = /* @__PURE__ */ new Map();
|
|
1474
|
+
snapshot;
|
|
1475
|
+
restore() {
|
|
1476
|
+
const original = JSON.parse(this.snapshot);
|
|
1477
|
+
for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
|
|
1478
|
+
this.seed[key].splice(0, this.seed[key].length, ...original[key]);
|
|
1479
|
+
}
|
|
1480
|
+
this.userMeta.clear();
|
|
1481
|
+
this.orgMeta.clear();
|
|
1482
|
+
}
|
|
1483
|
+
/** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
|
|
1484
|
+
load(next) {
|
|
1485
|
+
for (const key of Object.keys(next)) {
|
|
1486
|
+
const current = this.seed[key];
|
|
1487
|
+
if (Array.isArray(current)) {
|
|
1488
|
+
current.splice(0, current.length, ...next[key]);
|
|
1489
|
+
} else {
|
|
1490
|
+
const record = current;
|
|
1491
|
+
for (const name of Object.keys(record)) delete record[name];
|
|
1492
|
+
Object.assign(record, next[key]);
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
this.snapshot = JSON.stringify(this.seed);
|
|
1496
|
+
this.userMeta.clear();
|
|
1497
|
+
this.orgMeta.clear();
|
|
1498
|
+
}
|
|
1499
|
+
user(id) {
|
|
1500
|
+
return this.seed.users.find((user) => user.id === id);
|
|
1501
|
+
}
|
|
1502
|
+
meta(user) {
|
|
1503
|
+
let meta = this.userMeta.get(user.id);
|
|
1504
|
+
if (!meta) {
|
|
1505
|
+
meta = {
|
|
1506
|
+
providedId: null,
|
|
1507
|
+
isSuspended: false,
|
|
1508
|
+
isPasswordResetRequested: false,
|
|
1509
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1510
|
+
totalSignIns: 0,
|
|
1511
|
+
lastSignedIn: null
|
|
1512
|
+
};
|
|
1513
|
+
this.userMeta.set(user.id, meta);
|
|
1514
|
+
}
|
|
1515
|
+
return meta;
|
|
1516
|
+
}
|
|
1517
|
+
isSuspended(userId) {
|
|
1518
|
+
return this.userMeta.get(userId)?.isSuspended ?? false;
|
|
1519
|
+
}
|
|
1520
|
+
recordSignIn(user, organizationCode) {
|
|
1521
|
+
const meta = this.meta(user);
|
|
1522
|
+
meta.totalSignIns += 1;
|
|
1523
|
+
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
1524
|
+
void organizationCode;
|
|
1525
|
+
}
|
|
1526
|
+
createUser(input) {
|
|
1527
|
+
const user = createKindeUser({
|
|
1528
|
+
id: `kp_${randomBytes3(16).toString("hex")}`,
|
|
1529
|
+
email: input.email ?? null,
|
|
1530
|
+
givenName: input.givenName ?? null,
|
|
1531
|
+
familyName: input.familyName ?? null,
|
|
1532
|
+
picture: input.picture ?? null
|
|
1533
|
+
});
|
|
1534
|
+
this.seed.users.push(user);
|
|
1535
|
+
this.meta(user).providedId = input.providedId ?? null;
|
|
1536
|
+
return user;
|
|
1537
|
+
}
|
|
1538
|
+
deleteUser(id) {
|
|
1539
|
+
const index = this.seed.users.findIndex((user) => user.id === id);
|
|
1540
|
+
if (index < 0) return false;
|
|
1541
|
+
this.seed.users.splice(index, 1);
|
|
1542
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1543
|
+
if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
|
|
1544
|
+
}
|
|
1545
|
+
this.userMeta.delete(id);
|
|
1546
|
+
return true;
|
|
1547
|
+
}
|
|
1548
|
+
organization(code) {
|
|
1549
|
+
return this.seed.organizations.find((org) => org.code === code);
|
|
1550
|
+
}
|
|
1551
|
+
orgInfo(org) {
|
|
1552
|
+
let meta = this.orgMeta.get(org.code);
|
|
1553
|
+
if (!meta) {
|
|
1554
|
+
meta = {
|
|
1555
|
+
externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
|
|
1556
|
+
handle: slug(org.name),
|
|
1557
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1558
|
+
isAllowRegistrations: false
|
|
1559
|
+
};
|
|
1560
|
+
this.orgMeta.set(org.code, meta);
|
|
1561
|
+
}
|
|
1562
|
+
return meta;
|
|
1563
|
+
}
|
|
1564
|
+
createOrganization(input) {
|
|
1565
|
+
const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
|
|
1566
|
+
this.seed.organizations.push(org);
|
|
1567
|
+
const meta = this.orgInfo(org);
|
|
1568
|
+
meta.externalId = input.externalId ?? null;
|
|
1569
|
+
if (input.handle) meta.handle = input.handle;
|
|
1570
|
+
return org;
|
|
1571
|
+
}
|
|
1572
|
+
deleteOrganization(code) {
|
|
1573
|
+
const index = this.seed.organizations.findIndex((org) => org.code === code);
|
|
1574
|
+
if (index < 0) return false;
|
|
1575
|
+
this.seed.organizations.splice(index, 1);
|
|
1576
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1577
|
+
if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
|
|
1578
|
+
}
|
|
1579
|
+
this.orgMeta.delete(code);
|
|
1580
|
+
return true;
|
|
1581
|
+
}
|
|
1582
|
+
membership(userId, organizationCode) {
|
|
1583
|
+
return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1584
|
+
}
|
|
1585
|
+
addMembership(userId, organizationCode, roles = [], permissions = []) {
|
|
1586
|
+
const existing = this.membership(userId, organizationCode);
|
|
1587
|
+
if (existing) return existing;
|
|
1588
|
+
const membership = createMembership({ userId, organizationCode, roles, permissions });
|
|
1589
|
+
this.seed.memberships.push(membership);
|
|
1590
|
+
for (const key of roles) this.ensureRole(key);
|
|
1591
|
+
for (const key of permissions) this.ensurePermission(key);
|
|
1592
|
+
return membership;
|
|
1593
|
+
}
|
|
1594
|
+
removeMembership(userId, organizationCode) {
|
|
1595
|
+
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1596
|
+
if (index < 0) return false;
|
|
1597
|
+
this.seed.memberships.splice(index, 1);
|
|
1598
|
+
return true;
|
|
1599
|
+
}
|
|
1600
|
+
role(idOrKey) {
|
|
1601
|
+
return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
|
|
1602
|
+
}
|
|
1603
|
+
permission(idOrKey) {
|
|
1604
|
+
return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
|
|
1605
|
+
}
|
|
1606
|
+
ensureRole(key, extra = {}) {
|
|
1607
|
+
const existing = this.role(key);
|
|
1608
|
+
if (existing) return existing;
|
|
1609
|
+
const role = roleRecord(key, extra);
|
|
1610
|
+
this.seed.roles.push(role);
|
|
1611
|
+
return role;
|
|
1612
|
+
}
|
|
1613
|
+
ensurePermission(key, extra = {}) {
|
|
1614
|
+
const existing = this.permission(key);
|
|
1615
|
+
if (existing) return existing;
|
|
1616
|
+
const permission = permissionRecord(key, extra);
|
|
1617
|
+
this.seed.permissions.push(permission);
|
|
1618
|
+
return permission;
|
|
1619
|
+
}
|
|
1620
|
+
deleteRole(id) {
|
|
1621
|
+
const role = this.role(id);
|
|
1622
|
+
if (!role) return void 0;
|
|
1623
|
+
this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
|
|
1624
|
+
for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
|
|
1625
|
+
return role;
|
|
1626
|
+
}
|
|
1627
|
+
deletePermission(id) {
|
|
1628
|
+
const permission = this.permission(id);
|
|
1629
|
+
if (!permission) return void 0;
|
|
1630
|
+
this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
|
|
1631
|
+
for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
|
|
1632
|
+
for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
|
|
1633
|
+
return permission;
|
|
1634
|
+
}
|
|
1635
|
+
};
|
|
1636
|
+
|
|
1637
|
+
// src/management.ts
|
|
1638
|
+
var OK = { code: "OK", message: "Success" };
|
|
1639
|
+
var DEFAULT_PAGE_SIZE2 = 10;
|
|
1640
|
+
var MAX_PAGE_SIZE = 500;
|
|
1641
|
+
var ManagementApi = class {
|
|
1642
|
+
constructor(testkit, directory, webhooks) {
|
|
1643
|
+
this.testkit = testkit;
|
|
1644
|
+
this.directory = directory;
|
|
1645
|
+
this.webhooks = webhooks;
|
|
1646
|
+
this.register();
|
|
1647
|
+
}
|
|
1648
|
+
testkit;
|
|
1649
|
+
directory;
|
|
1650
|
+
webhooks;
|
|
1651
|
+
routes = [];
|
|
1652
|
+
async handle(req, res, url, readBody) {
|
|
1653
|
+
if (!url.pathname.startsWith("/api/v1/")) return false;
|
|
1654
|
+
const method = req.method ?? "GET";
|
|
1655
|
+
const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
1656
|
+
if (!route) {
|
|
1657
|
+
sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
|
|
1658
|
+
return true;
|
|
1659
|
+
}
|
|
1660
|
+
const token = await this.authenticate(req.headers.authorization);
|
|
1661
|
+
if ("error" in token) {
|
|
1662
|
+
sendJson3(res, 403, errors2(token.code, token.error));
|
|
1663
|
+
return true;
|
|
1664
|
+
}
|
|
1665
|
+
const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
|
|
1666
|
+
if (granted.length > 0 && !granted.includes(route.scope)) {
|
|
1667
|
+
sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
|
|
1668
|
+
return true;
|
|
1669
|
+
}
|
|
1670
|
+
const match = route.pattern.exec(url.pathname);
|
|
1671
|
+
const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
|
|
1672
|
+
const body = method === "GET" || method === "DELETE" ? {} : await readBody();
|
|
1673
|
+
const [status, payload] = await route.handler({ params, query: url.searchParams, body });
|
|
1674
|
+
sendJson3(res, status, payload);
|
|
1675
|
+
return true;
|
|
1676
|
+
}
|
|
1677
|
+
async authenticate(header) {
|
|
1678
|
+
if (!header?.startsWith("Bearer ")) {
|
|
1679
|
+
return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
|
|
1680
|
+
}
|
|
1681
|
+
let payload;
|
|
1682
|
+
try {
|
|
1683
|
+
payload = await this.testkit.verify(header.slice(7));
|
|
1684
|
+
} catch {
|
|
1685
|
+
return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
|
|
1686
|
+
}
|
|
1687
|
+
const audience = `${this.testkit.issuer}/api`;
|
|
1688
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
1689
|
+
if (!aud.includes(audience)) {
|
|
1690
|
+
return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
|
|
1691
|
+
}
|
|
1692
|
+
if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
|
|
1693
|
+
return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
|
|
1694
|
+
}
|
|
1695
|
+
return { payload };
|
|
1696
|
+
}
|
|
1697
|
+
route(method, path, scope, handler) {
|
|
1698
|
+
const keys = [];
|
|
1699
|
+
const pattern = new RegExp(
|
|
1700
|
+
`^${path.replace(/\{(\w+)\}/g, (_, key) => {
|
|
1701
|
+
keys.push(key);
|
|
1702
|
+
return "([^/]+)";
|
|
1703
|
+
})}$`
|
|
1704
|
+
);
|
|
1705
|
+
this.routes.push({ method, pattern, keys, scope, handler });
|
|
1706
|
+
}
|
|
1707
|
+
register() {
|
|
1708
|
+
const d = this.directory;
|
|
1709
|
+
this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
|
|
1710
|
+
let users = [...d.seed.users];
|
|
1711
|
+
const userId = query.get("user_id");
|
|
1712
|
+
const email = query.get("email")?.toLowerCase();
|
|
1713
|
+
if (userId) users = users.filter((u) => u.id === userId);
|
|
1714
|
+
if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
|
|
1715
|
+
const page = paginate(users, query);
|
|
1716
|
+
return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
|
|
1717
|
+
});
|
|
1718
|
+
this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
|
|
1719
|
+
const user = d.user(query.get("id") ?? "");
|
|
1720
|
+
return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
|
|
1721
|
+
});
|
|
1722
|
+
this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
|
|
1723
|
+
const profile = body.profile ?? {};
|
|
1724
|
+
const identities = Array.isArray(body.identities) ? body.identities : [];
|
|
1725
|
+
const emailIdentity = identities.find((i) => i.type === "email");
|
|
1726
|
+
const email = (emailIdentity?.details ?? {}).email;
|
|
1727
|
+
if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
|
|
1728
|
+
return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
|
|
1729
|
+
}
|
|
1730
|
+
const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
|
|
1731
|
+
if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
|
|
1732
|
+
const user = d.createUser({
|
|
1733
|
+
email: typeof email === "string" ? email : null,
|
|
1734
|
+
givenName: str(profile.given_name),
|
|
1735
|
+
familyName: str(profile.family_name),
|
|
1736
|
+
picture: str(profile.picture),
|
|
1737
|
+
providedId: str(body.provided_id)
|
|
1738
|
+
});
|
|
1739
|
+
if (orgCode) d.addMembership(user.id, orgCode);
|
|
1740
|
+
this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
|
|
1741
|
+
return [
|
|
1742
|
+
200,
|
|
1743
|
+
{ id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
|
|
1744
|
+
];
|
|
1745
|
+
});
|
|
1746
|
+
this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
|
|
1747
|
+
const user = d.user(query.get("id") ?? "");
|
|
1748
|
+
if (!user) return notFound("USER_INVALID", "No user has that id.");
|
|
1749
|
+
if (typeof body.given_name === "string") user.givenName = body.given_name;
|
|
1750
|
+
if (typeof body.family_name === "string") user.familyName = body.family_name;
|
|
1751
|
+
if (typeof body.picture === "string") user.picture = body.picture;
|
|
1752
|
+
const meta = d.meta(user);
|
|
1753
|
+
if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
|
|
1754
|
+
if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
|
|
1755
|
+
if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
|
|
1756
|
+
this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
|
|
1757
|
+
return [
|
|
1758
|
+
200,
|
|
1759
|
+
{
|
|
1760
|
+
id: user.id,
|
|
1761
|
+
given_name: user.givenName,
|
|
1762
|
+
family_name: user.familyName,
|
|
1763
|
+
email: user.email,
|
|
1764
|
+
is_suspended: meta.isSuspended,
|
|
1765
|
+
is_password_reset_requested: meta.isPasswordResetRequested,
|
|
1766
|
+
picture: user.picture
|
|
1767
|
+
}
|
|
1768
|
+
];
|
|
1769
|
+
});
|
|
1770
|
+
this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
|
|
1771
|
+
const id = query.get("id") ?? "";
|
|
1772
|
+
if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
|
|
1773
|
+
this.webhooks.emit("user.deleted", { user: { id } });
|
|
1774
|
+
return [200, OK];
|
|
1775
|
+
});
|
|
1776
|
+
this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
|
|
1777
|
+
const page = paginate(d.seed.organizations, query);
|
|
1778
|
+
return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
|
|
1779
|
+
});
|
|
1780
|
+
this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
|
|
1781
|
+
const org = d.organization(query.get("code") ?? "");
|
|
1782
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1783
|
+
const meta = d.orgInfo(org);
|
|
1784
|
+
return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
|
|
1785
|
+
});
|
|
1786
|
+
this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
|
|
1787
|
+
if (typeof body.name !== "string" || body.name.trim() === "") {
|
|
1788
|
+
return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
|
|
1789
|
+
}
|
|
1790
|
+
const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
|
|
1791
|
+
if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
|
|
1792
|
+
this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
|
|
1793
|
+
return [200, { ...OK, organization: { code: org.code } }];
|
|
1794
|
+
});
|
|
1795
|
+
this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
|
|
1796
|
+
const org = d.organization(params.org_code);
|
|
1797
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1798
|
+
const meta = d.orgInfo(org);
|
|
1799
|
+
if (typeof body.name === "string") org.name = body.name;
|
|
1800
|
+
if (typeof body.external_id === "string") meta.externalId = body.external_id;
|
|
1801
|
+
if (typeof body.handle === "string") meta.handle = body.handle;
|
|
1802
|
+
if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
|
|
1803
|
+
this.webhooks.emit("organization.updated", {
|
|
1804
|
+
organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
|
|
1805
|
+
});
|
|
1806
|
+
return [200, OK];
|
|
1807
|
+
});
|
|
1808
|
+
this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
|
|
1809
|
+
if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1810
|
+
this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
|
|
1811
|
+
return [200, OK];
|
|
1812
|
+
});
|
|
1813
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
|
|
1814
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1815
|
+
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);
|
|
1816
|
+
const page = paginate(members, query);
|
|
1817
|
+
return [
|
|
1818
|
+
200,
|
|
1819
|
+
{
|
|
1820
|
+
...OK,
|
|
1821
|
+
organization_users: page.items.map(({ membership, user }) => ({
|
|
1822
|
+
id: user.id,
|
|
1823
|
+
email: user.email,
|
|
1824
|
+
full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
|
|
1825
|
+
last_name: user.familyName,
|
|
1826
|
+
first_name: user.givenName,
|
|
1827
|
+
picture: user.picture,
|
|
1828
|
+
joined_on: d.meta(user).createdOn,
|
|
1829
|
+
last_accessed_on: d.meta(user).lastSignedIn,
|
|
1830
|
+
is_suspended: d.meta(user).isSuspended,
|
|
1831
|
+
roles: [...membership.roles]
|
|
1832
|
+
})),
|
|
1833
|
+
next_token: page.nextToken
|
|
1834
|
+
}
|
|
1835
|
+
];
|
|
1836
|
+
});
|
|
1837
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
|
|
1838
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1839
|
+
const users = Array.isArray(body.users) ? body.users : [];
|
|
1840
|
+
const added = [];
|
|
1841
|
+
const blocked = [];
|
|
1842
|
+
for (const entry of users) {
|
|
1843
|
+
const id = typeof entry.id === "string" ? entry.id : "";
|
|
1844
|
+
if (!d.user(id)) {
|
|
1845
|
+
blocked.push(id);
|
|
1846
|
+
continue;
|
|
1847
|
+
}
|
|
1848
|
+
d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
|
|
1849
|
+
added.push(id);
|
|
1850
|
+
}
|
|
1851
|
+
return [200, { ...OK, users_added: added, users_blocked: blocked }];
|
|
1852
|
+
});
|
|
1853
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
|
|
1854
|
+
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}.`);
|
|
1855
|
+
});
|
|
1856
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
|
|
1857
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1858
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1859
|
+
const roles = membership.roles.map((key) => d.ensureRole(key));
|
|
1860
|
+
return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
|
|
1861
|
+
});
|
|
1862
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
|
|
1863
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1864
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1865
|
+
const role = d.role(str(body.role_id) ?? "");
|
|
1866
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1867
|
+
if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
|
|
1868
|
+
return [200, OK];
|
|
1869
|
+
});
|
|
1870
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
|
|
1871
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1872
|
+
const role = d.role(params.role_id);
|
|
1873
|
+
if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
|
|
1874
|
+
membership.roles = membership.roles.filter((key) => key !== role.key);
|
|
1875
|
+
return [200, OK];
|
|
1876
|
+
});
|
|
1877
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
|
|
1878
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1879
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1880
|
+
const permissions = effectivePermissions(d.seed, membership).map((key) => {
|
|
1881
|
+
const permission = d.ensurePermission(key);
|
|
1882
|
+
const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
|
|
1883
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
|
|
1884
|
+
});
|
|
1885
|
+
return [200, { ...OK, permissions }];
|
|
1886
|
+
});
|
|
1887
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
|
|
1888
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1889
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1890
|
+
const permission = d.permission(str(body.permission_id) ?? "");
|
|
1891
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1892
|
+
if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
|
|
1893
|
+
return [200, OK];
|
|
1894
|
+
});
|
|
1895
|
+
this.route(
|
|
1896
|
+
"DELETE",
|
|
1897
|
+
"/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
|
|
1898
|
+
"delete:organization_user_permissions",
|
|
1899
|
+
({ params }) => {
|
|
1900
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
1901
|
+
const permission = d.permission(params.permission_id);
|
|
1902
|
+
if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
|
|
1903
|
+
membership.permissions = membership.permissions.filter((key) => key !== permission.key);
|
|
1904
|
+
return [200, OK];
|
|
1905
|
+
}
|
|
1906
|
+
);
|
|
1907
|
+
this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
|
|
1908
|
+
const page = paginate(d.seed.roles, query);
|
|
1909
|
+
return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
|
|
1910
|
+
});
|
|
1911
|
+
this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
|
|
1912
|
+
const key = str(body.key);
|
|
1913
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
|
|
1914
|
+
if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
|
|
1915
|
+
const role = d.ensureRole(key, {
|
|
1916
|
+
name: str(body.name) ?? void 0,
|
|
1917
|
+
description: str(body.description) ?? void 0,
|
|
1918
|
+
isDefault: body.is_default_role === true
|
|
1919
|
+
});
|
|
1920
|
+
this.webhooks.emit("role.created", {
|
|
1921
|
+
role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
|
|
1922
|
+
});
|
|
1923
|
+
return [201, { ...OK, role: { id: role.id } }];
|
|
1924
|
+
});
|
|
1925
|
+
this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
|
|
1926
|
+
const role = d.role(params.role_id);
|
|
1927
|
+
return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
|
|
1928
|
+
});
|
|
1929
|
+
this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
|
|
1930
|
+
const role = d.deleteRole(params.role_id);
|
|
1931
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1932
|
+
this.webhooks.emit("role.deleted", { role: { id: role.id } });
|
|
1933
|
+
return [200, OK];
|
|
1934
|
+
});
|
|
1935
|
+
this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
|
|
1936
|
+
const role = d.role(params.role_id);
|
|
1937
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1938
|
+
return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
|
|
1939
|
+
});
|
|
1940
|
+
this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
|
|
1941
|
+
const page = paginate(d.seed.permissions, query);
|
|
1942
|
+
return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
|
|
1943
|
+
});
|
|
1944
|
+
this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
|
|
1945
|
+
const key = str(body.key);
|
|
1946
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
|
|
1947
|
+
if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
|
|
1948
|
+
const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
|
|
1949
|
+
this.webhooks.emit("permission.created", {
|
|
1950
|
+
permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
|
|
1951
|
+
});
|
|
1952
|
+
return [201, OK];
|
|
1953
|
+
});
|
|
1954
|
+
this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
|
|
1955
|
+
const permission = d.deletePermission(params.permission_id);
|
|
1956
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1957
|
+
this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
|
|
1958
|
+
return [200, OK];
|
|
1959
|
+
});
|
|
1960
|
+
}
|
|
1961
|
+
userListItem(user) {
|
|
1962
|
+
const meta = this.directory.meta(user);
|
|
1963
|
+
return {
|
|
1964
|
+
id: user.id,
|
|
1965
|
+
provided_id: meta.providedId,
|
|
1966
|
+
email: user.email,
|
|
1967
|
+
phone: null,
|
|
1968
|
+
username: null,
|
|
1969
|
+
last_name: user.familyName,
|
|
1970
|
+
first_name: user.givenName,
|
|
1971
|
+
is_suspended: meta.isSuspended,
|
|
1972
|
+
picture: user.picture,
|
|
1973
|
+
total_sign_ins: meta.totalSignIns,
|
|
1974
|
+
failed_sign_ins: 0,
|
|
1975
|
+
last_signed_in: meta.lastSignedIn,
|
|
1976
|
+
created_on: meta.createdOn,
|
|
1977
|
+
organizations: this.organizationsOf(user),
|
|
1978
|
+
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
1979
|
+
};
|
|
1980
|
+
}
|
|
1981
|
+
userDetail(user) {
|
|
1982
|
+
const { email, ...rest } = this.userListItem(user);
|
|
1983
|
+
return { ...rest, preferred_email: email };
|
|
1984
|
+
}
|
|
1985
|
+
organizationsOf(user) {
|
|
1986
|
+
return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
|
|
1987
|
+
}
|
|
1988
|
+
organizationItem(org) {
|
|
1989
|
+
const meta = this.directory.orgInfo(org);
|
|
1990
|
+
return {
|
|
1991
|
+
code: org.code,
|
|
1992
|
+
name: org.name,
|
|
1993
|
+
handle: meta.handle,
|
|
1994
|
+
is_default: false,
|
|
1995
|
+
external_id: meta.externalId,
|
|
1996
|
+
is_auto_membership_enabled: false
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
organizationEvent(org) {
|
|
2000
|
+
const meta = this.directory.orgInfo(org);
|
|
2001
|
+
return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
|
|
2002
|
+
}
|
|
2003
|
+
roleItem(role) {
|
|
2004
|
+
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
2005
|
+
}
|
|
2006
|
+
permissionItem(permission) {
|
|
2007
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
2008
|
+
}
|
|
2009
|
+
};
|
|
2010
|
+
function paginate(items, query) {
|
|
2011
|
+
const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
|
|
2012
|
+
const token = query.get("next_token");
|
|
2013
|
+
const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
|
|
2014
|
+
const page = items.slice(offset, offset + size);
|
|
2015
|
+
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
2016
|
+
return { items: page, nextToken: next };
|
|
2017
|
+
}
|
|
2018
|
+
function errors2(code, message) {
|
|
2019
|
+
return { errors: [{ code, message }] };
|
|
2020
|
+
}
|
|
2021
|
+
function notFound(code, message) {
|
|
2022
|
+
return [404, errors2(code, message)];
|
|
2023
|
+
}
|
|
2024
|
+
function str(value) {
|
|
2025
|
+
return typeof value === "string" ? value : null;
|
|
2026
|
+
}
|
|
2027
|
+
function strings(value) {
|
|
2028
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
2029
|
+
}
|
|
2030
|
+
function sendJson3(res, status, body) {
|
|
2031
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
2032
|
+
res.end(JSON.stringify(body));
|
|
2033
|
+
}
|
|
2034
|
+
|
|
1020
2035
|
// src/failures.ts
|
|
1021
2036
|
var MAX_DELAY_MS = 6e4;
|
|
1022
2037
|
var FailureInjector = class {
|
|
@@ -1098,7 +2113,7 @@ function validate(rule) {
|
|
|
1098
2113
|
}
|
|
1099
2114
|
|
|
1100
2115
|
// src/webhooks.ts
|
|
1101
|
-
import { randomBytes as
|
|
2116
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
1102
2117
|
var WEBHOOK_EVENT_TYPES = [
|
|
1103
2118
|
"user.created",
|
|
1104
2119
|
"user.updated",
|
|
@@ -1147,6 +2162,8 @@ var WebhookDispatcher = class {
|
|
|
1147
2162
|
nextEndpoint = 1;
|
|
1148
2163
|
retryDelaysMs;
|
|
1149
2164
|
timeoutMs;
|
|
2165
|
+
/** Set by the server to record coverage. */
|
|
2166
|
+
observe = () => void 0;
|
|
1150
2167
|
addEndpoint(input) {
|
|
1151
2168
|
if (!isHttpUrl2(input.url)) {
|
|
1152
2169
|
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
@@ -1158,6 +2175,14 @@ var WebhookDispatcher = class {
|
|
|
1158
2175
|
this.endpoints.push(endpoint);
|
|
1159
2176
|
return { ...endpoint };
|
|
1160
2177
|
}
|
|
2178
|
+
/** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
|
|
2179
|
+
replaceSeededEndpoints(endpoints) {
|
|
2180
|
+
const seeded = new Set(this.seededEndpoints.map((e) => e.id));
|
|
2181
|
+
this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
|
|
2182
|
+
const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
|
|
2183
|
+
const ids = new Set(added.map((e) => e.id));
|
|
2184
|
+
this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
|
|
2185
|
+
}
|
|
1161
2186
|
removeEndpoint(id) {
|
|
1162
2187
|
const before = this.endpoints.length;
|
|
1163
2188
|
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
@@ -1181,7 +2206,7 @@ var WebhookDispatcher = class {
|
|
|
1181
2206
|
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1182
2207
|
const event = {
|
|
1183
2208
|
data: options.data ?? this.buildData(options),
|
|
1184
|
-
event_id: `event_${
|
|
2209
|
+
event_id: `event_${randomBytes4(16).toString("hex")}`,
|
|
1185
2210
|
event_timestamp: timestamp,
|
|
1186
2211
|
source: options.source ?? "admin",
|
|
1187
2212
|
timestamp,
|
|
@@ -1208,16 +2233,23 @@ var WebhookDispatcher = class {
|
|
|
1208
2233
|
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
1209
2234
|
);
|
|
1210
2235
|
}
|
|
2236
|
+
if (copies > 1) this.observe("webhook.duplicate");
|
|
2237
|
+
if (options.invalid === "stale") this.observe("webhook.stale");
|
|
2238
|
+
else if (options.invalid) this.observe("webhook.forged");
|
|
1211
2239
|
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
1212
2240
|
const signed = await this.testkit.signPayload(
|
|
1213
2241
|
event,
|
|
1214
2242
|
options.invalid === "stale" ? void 0 : options.invalid
|
|
1215
2243
|
);
|
|
1216
2244
|
const jobs = targets.flatMap((target) => {
|
|
1217
|
-
const webhookId = `wh_${
|
|
2245
|
+
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
1218
2246
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1219
2247
|
});
|
|
1220
|
-
|
|
2248
|
+
const deliveries = await Promise.all(jobs);
|
|
2249
|
+
if (!options.invalid) {
|
|
2250
|
+
for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
|
|
2251
|
+
}
|
|
2252
|
+
return deliveries;
|
|
1221
2253
|
}
|
|
1222
2254
|
async deliver(url, webhookId, body, event, copy) {
|
|
1223
2255
|
const delivery = {
|
|
@@ -1295,6 +2327,13 @@ var WebhookDispatcher = class {
|
|
|
1295
2327
|
);
|
|
1296
2328
|
}
|
|
1297
2329
|
}
|
|
2330
|
+
emit(type, data, source = "api") {
|
|
2331
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2332
|
+
void this.send({ type, data, source }).catch(() => void 0);
|
|
2333
|
+
}
|
|
2334
|
+
userEventData(user) {
|
|
2335
|
+
return this.userPayload(user);
|
|
2336
|
+
}
|
|
1298
2337
|
emitForUser(type, user) {
|
|
1299
2338
|
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1300
2339
|
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
@@ -1359,7 +2398,463 @@ function isHttpUrl2(value) {
|
|
|
1359
2398
|
}
|
|
1360
2399
|
}
|
|
1361
2400
|
function sleep(ms) {
|
|
1362
|
-
return new Promise((
|
|
2401
|
+
return new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
2402
|
+
}
|
|
2403
|
+
|
|
2404
|
+
// src/activity.ts
|
|
2405
|
+
var LIMIT = 200;
|
|
2406
|
+
var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
|
|
2407
|
+
var ActivityLog = class {
|
|
2408
|
+
requestLog = [];
|
|
2409
|
+
tokenLog = [];
|
|
2410
|
+
request(entry) {
|
|
2411
|
+
const query = new URLSearchParams(entry.query);
|
|
2412
|
+
for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
|
|
2413
|
+
const search = query.toString();
|
|
2414
|
+
push(this.requestLog, {
|
|
2415
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2416
|
+
method: entry.method,
|
|
2417
|
+
path: search ? `${entry.path}?${search}` : entry.path,
|
|
2418
|
+
status: entry.status,
|
|
2419
|
+
durationMs: entry.durationMs,
|
|
2420
|
+
injected: entry.injected
|
|
2421
|
+
});
|
|
2422
|
+
}
|
|
2423
|
+
token(kind, claims, invalid2, token) {
|
|
2424
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
2425
|
+
push(this.tokenLog, {
|
|
2426
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2427
|
+
kind,
|
|
2428
|
+
subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
|
|
2429
|
+
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
2430
|
+
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
2431
|
+
roles,
|
|
2432
|
+
invalid: invalid2 ?? null,
|
|
2433
|
+
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
2434
|
+
claims,
|
|
2435
|
+
token
|
|
2436
|
+
});
|
|
2437
|
+
}
|
|
2438
|
+
requests() {
|
|
2439
|
+
return [...this.requestLog];
|
|
2440
|
+
}
|
|
2441
|
+
tokens() {
|
|
2442
|
+
return [...this.tokenLog];
|
|
2443
|
+
}
|
|
2444
|
+
reset() {
|
|
2445
|
+
this.requestLog = [];
|
|
2446
|
+
this.tokenLog = [];
|
|
2447
|
+
}
|
|
2448
|
+
};
|
|
2449
|
+
function push(list, entry) {
|
|
2450
|
+
list.push(entry);
|
|
2451
|
+
if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
// src/coverage.ts
|
|
2455
|
+
import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
2456
|
+
import { join as join2, resolve as resolve2 } from "path";
|
|
2457
|
+
var COVERAGE_GROUPS = [
|
|
2458
|
+
{
|
|
2459
|
+
name: "Identity",
|
|
2460
|
+
items: [
|
|
2461
|
+
{ id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
|
|
2462
|
+
{ id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
|
|
2463
|
+
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
2464
|
+
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
2465
|
+
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
2466
|
+
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
|
|
2467
|
+
]
|
|
2468
|
+
},
|
|
2469
|
+
{
|
|
2470
|
+
name: "Organizations",
|
|
2471
|
+
items: [
|
|
2472
|
+
{ id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
|
|
2473
|
+
{ id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
|
|
2474
|
+
{ id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
|
|
2475
|
+
{ 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." },
|
|
2476
|
+
{ id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
|
|
2477
|
+
]
|
|
2478
|
+
},
|
|
2479
|
+
{
|
|
2480
|
+
name: "Permissions",
|
|
2481
|
+
items: [
|
|
2482
|
+
{ id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
|
|
2483
|
+
{ 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." },
|
|
2484
|
+
{ id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
|
|
2485
|
+
{ id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
|
|
2486
|
+
{ id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
|
|
2487
|
+
]
|
|
2488
|
+
},
|
|
2489
|
+
{
|
|
2490
|
+
name: "Token validation",
|
|
2491
|
+
items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
|
|
2492
|
+
(kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
|
|
2493
|
+
)
|
|
2494
|
+
},
|
|
2495
|
+
{
|
|
2496
|
+
name: "Sessions",
|
|
2497
|
+
items: [
|
|
2498
|
+
{ id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
|
|
2499
|
+
{ id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
|
|
2500
|
+
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
2501
|
+
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
2502
|
+
{ id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
|
|
2503
|
+
]
|
|
2504
|
+
},
|
|
2505
|
+
{
|
|
2506
|
+
name: "Machine-to-machine",
|
|
2507
|
+
items: [
|
|
2508
|
+
{ id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
|
|
2509
|
+
{ id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
|
|
2510
|
+
{ id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
|
|
2511
|
+
{ id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
|
|
2512
|
+
]
|
|
2513
|
+
},
|
|
2514
|
+
{
|
|
2515
|
+
name: "Kinde APIs",
|
|
2516
|
+
items: [
|
|
2517
|
+
{ id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
|
|
2518
|
+
{ id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
|
|
2519
|
+
{ id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
|
|
2520
|
+
{ id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
|
|
2521
|
+
]
|
|
2522
|
+
},
|
|
2523
|
+
{
|
|
2524
|
+
name: "Webhooks",
|
|
2525
|
+
items: [
|
|
2526
|
+
{ id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
|
|
2527
|
+
{ id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
|
|
2528
|
+
{ id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
|
|
2529
|
+
{ id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
|
|
2530
|
+
{ id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
|
|
2531
|
+
]
|
|
2532
|
+
},
|
|
2533
|
+
{
|
|
2534
|
+
name: "Outages",
|
|
2535
|
+
items: [
|
|
2536
|
+
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
2537
|
+
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
2538
|
+
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
2539
|
+
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
|
|
2540
|
+
]
|
|
2541
|
+
}
|
|
2542
|
+
];
|
|
2543
|
+
var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
|
|
2544
|
+
function tokenLabel(kind) {
|
|
2545
|
+
return {
|
|
2546
|
+
expired: "Expired token",
|
|
2547
|
+
"future-iat": "Token issued in the future",
|
|
2548
|
+
"wrong-issuer": "Wrong issuer",
|
|
2549
|
+
"wrong-audience": "Wrong audience",
|
|
2550
|
+
"bad-signature": "Tampered signature",
|
|
2551
|
+
"unknown-key": "Unknown signing key",
|
|
2552
|
+
unsigned: "Unsigned token",
|
|
2553
|
+
"missing-subject": "No subject"
|
|
2554
|
+
}[kind];
|
|
2555
|
+
}
|
|
2556
|
+
var CoverageRecorder = class {
|
|
2557
|
+
hits = /* @__PURE__ */ new Map();
|
|
2558
|
+
userOrganizations = /* @__PURE__ */ new Map();
|
|
2559
|
+
organizationUsers = /* @__PURE__ */ new Map();
|
|
2560
|
+
organizationPermissionSets = /* @__PURE__ */ new Map();
|
|
2561
|
+
hit(id) {
|
|
2562
|
+
if (!ALL_IDS.has(id)) return;
|
|
2563
|
+
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
2564
|
+
}
|
|
2565
|
+
/** Called for every access token the testkit signs. */
|
|
2566
|
+
observeAccessToken(payload, invalid2) {
|
|
2567
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
2568
|
+
this.hit("m2m.token");
|
|
2569
|
+
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
2570
|
+
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
2571
|
+
if (invalid2) this.hit("m2m.invalid");
|
|
2572
|
+
return;
|
|
2573
|
+
}
|
|
2574
|
+
if (invalid2 === "missing-organization") return this.hit("organization.missing");
|
|
2575
|
+
if (invalid2 === "missing-permissions") return this.hit("permission.none");
|
|
2576
|
+
if (invalid2) return this.hit(`token.${invalid2}`);
|
|
2577
|
+
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
2578
|
+
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
2579
|
+
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
2580
|
+
if (subject) this.hit("identity.user");
|
|
2581
|
+
if (!organization) this.hit("identity.no-organization");
|
|
2582
|
+
if (permissions.length > 0) this.hit("permission.granted");
|
|
2583
|
+
else this.hit("permission.none");
|
|
2584
|
+
if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
|
|
2585
|
+
if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
|
|
2586
|
+
if (!organization) return;
|
|
2587
|
+
this.hit("organization.token");
|
|
2588
|
+
if (subject) {
|
|
2589
|
+
const organizations = add(this.userOrganizations, subject, organization);
|
|
2590
|
+
if (organizations.size > 1) this.hit("organization.two-for-one-user");
|
|
2591
|
+
add(this.organizationUsers, organization, subject);
|
|
2592
|
+
const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
|
|
2593
|
+
const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
|
|
2594
|
+
if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
|
|
2595
|
+
}
|
|
2596
|
+
const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
|
|
2597
|
+
if (sets.size > 1) this.hit("permission.different-sets");
|
|
2598
|
+
}
|
|
2599
|
+
report() {
|
|
2600
|
+
return buildReport(Object.fromEntries(this.hits));
|
|
2601
|
+
}
|
|
2602
|
+
snapshot() {
|
|
2603
|
+
return { version: 1, hits: Object.fromEntries(this.hits) };
|
|
2604
|
+
}
|
|
2605
|
+
reset() {
|
|
2606
|
+
this.hits.clear();
|
|
2607
|
+
this.userOrganizations.clear();
|
|
2608
|
+
this.organizationUsers.clear();
|
|
2609
|
+
this.organizationPermissionSets.clear();
|
|
2610
|
+
}
|
|
2611
|
+
/** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
|
|
2612
|
+
write(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2613
|
+
const folder = resolve2(directory);
|
|
2614
|
+
mkdirSync2(folder, { recursive: true });
|
|
2615
|
+
const file = join2(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
|
|
2616
|
+
writeFileSync2(file, `${JSON.stringify(this.snapshot())}
|
|
2617
|
+
`);
|
|
2618
|
+
return file;
|
|
2619
|
+
}
|
|
2620
|
+
};
|
|
2621
|
+
var DEFAULT_COVERAGE_DIRECTORY = join2(".kinde-testkit", "coverage");
|
|
2622
|
+
function add(map, key, value) {
|
|
2623
|
+
let set2 = map.get(key);
|
|
2624
|
+
if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
|
|
2625
|
+
set2.add(value);
|
|
2626
|
+
return set2;
|
|
2627
|
+
}
|
|
2628
|
+
function buildReport(hits) {
|
|
2629
|
+
const groups = COVERAGE_GROUPS.map((group) => {
|
|
2630
|
+
const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
|
|
2631
|
+
return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
|
|
2632
|
+
});
|
|
2633
|
+
return {
|
|
2634
|
+
covered: groups.reduce((sum, g) => sum + g.covered, 0),
|
|
2635
|
+
total: groups.reduce((sum, g) => sum + g.total, 0),
|
|
2636
|
+
groups
|
|
2637
|
+
};
|
|
2638
|
+
}
|
|
2639
|
+
|
|
2640
|
+
// src/dashboard.ts
|
|
2641
|
+
var STYLE2 = `
|
|
2642
|
+
: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}
|
|
2643
|
+
@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}}
|
|
2644
|
+
*{box-sizing:border-box}
|
|
2645
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
2646
|
+
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)}
|
|
2647
|
+
header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
|
|
2648
|
+
header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2649
|
+
nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
|
|
2650
|
+
nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
|
|
2651
|
+
main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
|
|
2652
|
+
section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
|
|
2653
|
+
h2{margin:0 0 4px;font-size:16px;font-weight:600}
|
|
2654
|
+
.sub{margin:0 0 14px;color:var(--muted);font-size:13px}
|
|
2655
|
+
table{width:100%;border-collapse:collapse;font-size:13px}
|
|
2656
|
+
th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
|
|
2657
|
+
td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
|
|
2658
|
+
tr:last-child td{border-bottom:0}
|
|
2659
|
+
code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2660
|
+
.chips{display:flex;flex-wrap:wrap;gap:4px}
|
|
2661
|
+
.chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
|
|
2662
|
+
.ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
|
|
2663
|
+
.empty{color:var(--muted);font-size:13px;margin:0}
|
|
2664
|
+
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
|
|
2665
|
+
label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
|
|
2666
|
+
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}
|
|
2667
|
+
input[type=checkbox]{height:auto}
|
|
2668
|
+
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}
|
|
2669
|
+
button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
|
|
2670
|
+
button:hover{border-color:var(--muted)}
|
|
2671
|
+
details summary{cursor:pointer;color:var(--muted)}
|
|
2672
|
+
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}
|
|
2673
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
|
|
2674
|
+
.group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
|
|
2675
|
+
.group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
|
|
2676
|
+
.notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
|
|
2677
|
+
.split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
|
|
2678
|
+
`;
|
|
2679
|
+
function renderDashboard(data) {
|
|
2680
|
+
const e = escapeHtml;
|
|
2681
|
+
const { seed } = data;
|
|
2682
|
+
const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
|
|
2683
|
+
const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
|
|
2684
|
+
const users = seed.users.length ? table(
|
|
2685
|
+
["User", "ID", "Organizations", "Sign-ins", "Status"],
|
|
2686
|
+
seed.users.map((user) => [
|
|
2687
|
+
e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
|
|
2688
|
+
`<code>${e(user.id)}</code>`,
|
|
2689
|
+
chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
|
|
2690
|
+
String(data.signIns(user.id)),
|
|
2691
|
+
data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
|
|
2692
|
+
])
|
|
2693
|
+
) : empty("No users yet. Seed some, or sign in with any email.");
|
|
2694
|
+
const organizations = seed.organizations.length ? table(
|
|
2695
|
+
["Organization", "Code", "Members"],
|
|
2696
|
+
seed.organizations.map((org) => [
|
|
2697
|
+
e(org.name),
|
|
2698
|
+
`<code>${e(org.code)}</code>`,
|
|
2699
|
+
String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
|
|
2700
|
+
])
|
|
2701
|
+
) : empty("No organizations.");
|
|
2702
|
+
const memberships = seed.memberships.length ? table(
|
|
2703
|
+
["User", "Organization", "Roles", "Permissions in the token"],
|
|
2704
|
+
seed.memberships.map((m) => [
|
|
2705
|
+
e(userLabel(m.userId)),
|
|
2706
|
+
e(orgName(m.organizationCode)),
|
|
2707
|
+
chips(m.roles),
|
|
2708
|
+
chips(effectivePermissions(seed, m))
|
|
2709
|
+
])
|
|
2710
|
+
) : empty("No memberships.");
|
|
2711
|
+
const applications = seed.applications.length ? table(
|
|
2712
|
+
["Client ID", "Organization", "Scopes"],
|
|
2713
|
+
seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
|
|
2714
|
+
) : "";
|
|
2715
|
+
const tokens = data.tokens.length ? table(
|
|
2716
|
+
["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
|
|
2717
|
+
[...data.tokens].reverse().slice(0, 50).map((t) => [
|
|
2718
|
+
time(t.at),
|
|
2719
|
+
t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
|
|
2720
|
+
`<code>${e(t.subject ?? "none")}</code>`,
|
|
2721
|
+
e(t.organization ?? "none"),
|
|
2722
|
+
chips(t.permissions),
|
|
2723
|
+
`<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
|
|
2724
|
+
])
|
|
2725
|
+
) : empty("No tokens issued yet.");
|
|
2726
|
+
const requests = data.requests.length ? table(
|
|
2727
|
+
["Time", "Request", "Status", "Time taken"],
|
|
2728
|
+
[...data.requests].reverse().slice(0, 100).map((r) => [
|
|
2729
|
+
time(r.at),
|
|
2730
|
+
`<code>${e(r.method)} ${e(r.path)}</code>`,
|
|
2731
|
+
`<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
|
|
2732
|
+
`${r.durationMs} ms`
|
|
2733
|
+
])
|
|
2734
|
+
) : empty("No requests yet.");
|
|
2735
|
+
const deliveries = data.deliveries.length ? table(
|
|
2736
|
+
["Event", "Endpoint", "Copy", "Result"],
|
|
2737
|
+
[...data.deliveries].reverse().slice(0, 50).map((d) => [
|
|
2738
|
+
`<code>${e(d.type)}</code>`,
|
|
2739
|
+
`<code>${e(d.url)}</code>`,
|
|
2740
|
+
String(d.copy),
|
|
2741
|
+
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>`
|
|
2742
|
+
])
|
|
2743
|
+
) : empty("No webhooks sent yet.");
|
|
2744
|
+
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>`;
|
|
2745
|
+
const webhookForm = data.endpoints.length ? form(
|
|
2746
|
+
"/dashboard/webhooks",
|
|
2747
|
+
`<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
|
|
2748
|
+
<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>
|
|
2749
|
+
<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>
|
|
2750
|
+
<label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
|
|
2751
|
+
<button class="primary">Send</button>`
|
|
2752
|
+
) : "";
|
|
2753
|
+
const failures = data.failures.length ? table(
|
|
2754
|
+
["Path", "Method", "Effect", "Remaining", "Hits", ""],
|
|
2755
|
+
data.failures.map((f) => [
|
|
2756
|
+
`<code>${e(f.path)}</code>`,
|
|
2757
|
+
e(f.method ?? "any"),
|
|
2758
|
+
e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
|
|
2759
|
+
f.remaining === null ? "Until removed" : String(f.remaining),
|
|
2760
|
+
String(f.hits),
|
|
2761
|
+
form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
|
|
2762
|
+
])
|
|
2763
|
+
) : empty("No failure rules.");
|
|
2764
|
+
const coverage = `<div class="grid">${data.coverage.groups.map(
|
|
2765
|
+
(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>`
|
|
2766
|
+
).join("")}</div>`;
|
|
2767
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2768
|
+
${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
|
|
2769
|
+
<title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
|
|
2770
|
+
<header>
|
|
2771
|
+
<div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
|
|
2772
|
+
<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>
|
|
2773
|
+
<div class="row">
|
|
2774
|
+
<a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
|
|
2775
|
+
${form("/dashboard/reset", `<button>Reset state</button>`)}
|
|
2776
|
+
</div>
|
|
2777
|
+
</header>
|
|
2778
|
+
<main>
|
|
2779
|
+
${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
|
|
2780
|
+
<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>
|
|
2781
|
+
<div class="split">
|
|
2782
|
+
<section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
|
|
2783
|
+
<section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
|
|
2784
|
+
</div>
|
|
2785
|
+
${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
|
|
2786
|
+
<section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
|
|
2787
|
+
<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>
|
|
2788
|
+
<section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
|
|
2789
|
+
<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>
|
|
2790
|
+
${form(
|
|
2791
|
+
"/dashboard/failures",
|
|
2792
|
+
`<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
|
|
2793
|
+
<label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
|
|
2794
|
+
<label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
|
|
2795
|
+
<label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
|
|
2796
|
+
<label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
|
|
2797
|
+
<label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
|
|
2798
|
+
<button class="primary">Add rule</button>`
|
|
2799
|
+
)}
|
|
2800
|
+
<div style="margin-top:14px">${failures}</div>
|
|
2801
|
+
${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
|
|
2802
|
+
</section>
|
|
2803
|
+
<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}
|
|
2804
|
+
<div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
|
|
2805
|
+
</main></body></html>`;
|
|
2806
|
+
}
|
|
2807
|
+
function table(headers, rows) {
|
|
2808
|
+
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>`;
|
|
2809
|
+
}
|
|
2810
|
+
function chips(values) {
|
|
2811
|
+
if (values.length === 0) return `<span class="muted">none</span>`;
|
|
2812
|
+
return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
|
|
2813
|
+
}
|
|
2814
|
+
function empty(text) {
|
|
2815
|
+
return `<p class="empty">${escapeHtml(text)}</p>`;
|
|
2816
|
+
}
|
|
2817
|
+
function time(iso) {
|
|
2818
|
+
return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
|
|
2819
|
+
}
|
|
2820
|
+
function form(action, body) {
|
|
2821
|
+
return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
|
|
2822
|
+
}
|
|
2823
|
+
|
|
2824
|
+
// src/seed-file.ts
|
|
2825
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
2826
|
+
import { extname, resolve as resolve3 } from "path";
|
|
2827
|
+
import { pathToFileURL } from "url";
|
|
2828
|
+
import { parse as parseYaml } from "yaml";
|
|
2829
|
+
async function loadSeedFile(path) {
|
|
2830
|
+
const file = resolve3(path);
|
|
2831
|
+
const extension = extname(file).toLowerCase();
|
|
2832
|
+
let value;
|
|
2833
|
+
try {
|
|
2834
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
2835
|
+
value = parseYaml(readFileSync3(file, "utf8"));
|
|
2836
|
+
} else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
|
|
2837
|
+
const module = await import(pathToFileURL(file).href);
|
|
2838
|
+
value = module.seed ?? module.default;
|
|
2839
|
+
if (value && typeof value === "object" && "default" in value && !("users" in value)) {
|
|
2840
|
+
value = value.default;
|
|
2841
|
+
}
|
|
2842
|
+
} else {
|
|
2843
|
+
value = JSON.parse(readFileSync3(file, "utf8"));
|
|
2844
|
+
}
|
|
2845
|
+
} catch (error) {
|
|
2846
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2847
|
+
const details = [message];
|
|
2848
|
+
if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message)) {
|
|
2849
|
+
details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
|
|
2850
|
+
}
|
|
2851
|
+
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
|
|
2852
|
+
}
|
|
2853
|
+
if (value === null || value === void 0) value = {};
|
|
2854
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
2855
|
+
throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
|
|
2856
|
+
}
|
|
2857
|
+
return value;
|
|
1363
2858
|
}
|
|
1364
2859
|
|
|
1365
2860
|
// src/server.ts
|
|
@@ -1374,33 +2869,74 @@ async function startKindeTestkit(options = {}) {
|
|
|
1374
2869
|
`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).`
|
|
1375
2870
|
);
|
|
1376
2871
|
}
|
|
1377
|
-
const
|
|
2872
|
+
const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
|
|
2873
|
+
const seed = resolveSeed(seedInput);
|
|
1378
2874
|
const failures = new FailureInjector();
|
|
1379
2875
|
let ready;
|
|
1380
|
-
const testkitReady = new Promise((
|
|
1381
|
-
const
|
|
2876
|
+
const testkitReady = new Promise((resolve4) => ready = resolve4);
|
|
2877
|
+
const listener = (req, res) => {
|
|
1382
2878
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1383
|
-
}
|
|
1384
|
-
|
|
2879
|
+
};
|
|
2880
|
+
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
2881
|
+
const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
|
|
2882
|
+
await new Promise((resolve4, reject) => {
|
|
1385
2883
|
server.once("error", reject);
|
|
1386
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
2884
|
+
server.listen(options.port ?? 4400, host, () => resolve4());
|
|
1387
2885
|
});
|
|
1388
2886
|
const { port } = server.address();
|
|
1389
|
-
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1390
|
-
const url =
|
|
2887
|
+
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
2888
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1391
2889
|
const testkit = await KindeTestkit.create({
|
|
1392
|
-
issuer: options.issuer ??
|
|
1393
|
-
audience: options.audience ??
|
|
1394
|
-
clientId: options.clientId ??
|
|
2890
|
+
issuer: options.issuer ?? seedInput.issuer ?? url,
|
|
2891
|
+
audience: options.audience ?? seedInput.audience,
|
|
2892
|
+
clientId: options.clientId ?? seedInput.clientId
|
|
2893
|
+
});
|
|
2894
|
+
const coverage = new CoverageRecorder();
|
|
2895
|
+
const activity = new ActivityLog();
|
|
2896
|
+
testkit.observe({
|
|
2897
|
+
accessToken(payload, invalid2, token) {
|
|
2898
|
+
coverage.observeAccessToken(payload, invalid2);
|
|
2899
|
+
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
2900
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid2, token);
|
|
2901
|
+
},
|
|
2902
|
+
idToken(payload, token) {
|
|
2903
|
+
coverage.hit("identity.id-token");
|
|
2904
|
+
activity.token("id", payload, void 0, token);
|
|
2905
|
+
},
|
|
2906
|
+
anonymous() {
|
|
2907
|
+
coverage.hit("identity.anonymous");
|
|
2908
|
+
}
|
|
1395
2909
|
});
|
|
2910
|
+
const observe = (id) => coverage.hit(id);
|
|
2911
|
+
const directory = new Directory(seed);
|
|
1396
2912
|
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
1397
|
-
|
|
2913
|
+
webhooks.observe = observe;
|
|
2914
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
|
|
2915
|
+
const management = new ManagementApi(testkit, directory, webhooks);
|
|
2916
|
+
const account = new AccountApi(testkit, directory);
|
|
1398
2917
|
const reset = () => {
|
|
1399
2918
|
auth.reset();
|
|
1400
2919
|
failures.clear();
|
|
1401
2920
|
webhooks.reset();
|
|
2921
|
+
directory.restore();
|
|
1402
2922
|
};
|
|
1403
|
-
|
|
2923
|
+
const loadSeed = (input) => {
|
|
2924
|
+
const next = resolveSeed(input);
|
|
2925
|
+
directory.load(next);
|
|
2926
|
+
webhooks.replaceSeededEndpoints(next.webhooks);
|
|
2927
|
+
reset();
|
|
2928
|
+
};
|
|
2929
|
+
let closed = false;
|
|
2930
|
+
const close = () => new Promise((resolve4, reject) => {
|
|
2931
|
+
if (closed) return resolve4();
|
|
2932
|
+
closed = true;
|
|
2933
|
+
if (options.coverage) {
|
|
2934
|
+
coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
|
|
2935
|
+
}
|
|
2936
|
+
server.closeAllConnections();
|
|
2937
|
+
server.close((error) => error ? reject(error) : resolve4());
|
|
2938
|
+
});
|
|
2939
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
|
|
1404
2940
|
return {
|
|
1405
2941
|
url,
|
|
1406
2942
|
issuer: testkit.issuer,
|
|
@@ -1410,84 +2946,224 @@ async function startKindeTestkit(options = {}) {
|
|
|
1410
2946
|
seed,
|
|
1411
2947
|
failures,
|
|
1412
2948
|
webhooks,
|
|
2949
|
+
directory,
|
|
2950
|
+
certificatePath: certificate?.certPath ?? null,
|
|
2951
|
+
coverage,
|
|
2952
|
+
activity,
|
|
2953
|
+
loadSeed,
|
|
1413
2954
|
reset,
|
|
1414
|
-
close
|
|
1415
|
-
server.closeAllConnections();
|
|
1416
|
-
server.close((error) => error ? reject(error) : resolve());
|
|
1417
|
-
})
|
|
2955
|
+
close
|
|
1418
2956
|
};
|
|
1419
2957
|
}
|
|
1420
2958
|
async function handle(req, res, context) {
|
|
1421
|
-
const { testkit, auth, seed, failures, webhooks } = context;
|
|
2959
|
+
const { testkit, auth, seed, failures, webhooks, coverage } = context;
|
|
1422
2960
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1423
2961
|
const { pathname } = url;
|
|
1424
2962
|
const method = req.method ?? "GET";
|
|
1425
|
-
|
|
2963
|
+
const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
|
|
2964
|
+
let injected = false;
|
|
2965
|
+
if (!internal && pathname !== "/favicon.ico") {
|
|
2966
|
+
const started = Date.now();
|
|
2967
|
+
res.once("close", () => {
|
|
2968
|
+
context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
|
|
2969
|
+
});
|
|
2970
|
+
}
|
|
2971
|
+
if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
|
|
2972
|
+
if (!internal) {
|
|
1426
2973
|
const failure = failures.take(method, pathname);
|
|
1427
2974
|
if (failure) {
|
|
2975
|
+
injected = true;
|
|
2976
|
+
if (failure.hang) coverage.hit("outage.timeout");
|
|
2977
|
+
else if (failure.status === 429) coverage.hit("outage.rate-limit");
|
|
2978
|
+
else if (failure.status !== null) coverage.hit("outage.error");
|
|
2979
|
+
if (failure.delayMs > 0) coverage.hit("outage.slow");
|
|
1428
2980
|
if (failure.hang) return;
|
|
1429
|
-
if (failure.delayMs > 0) await new Promise((
|
|
2981
|
+
if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
|
|
1430
2982
|
if (failure.status !== null) {
|
|
1431
2983
|
const headers = {};
|
|
1432
2984
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1433
|
-
return
|
|
2985
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1434
2986
|
}
|
|
1435
2987
|
}
|
|
1436
2988
|
}
|
|
1437
2989
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
2990
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) {
|
|
2991
|
+
if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
|
|
2992
|
+
else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
|
|
2993
|
+
return;
|
|
2994
|
+
}
|
|
2995
|
+
if (await context.account.handle(req, res, url)) {
|
|
2996
|
+
if (res.statusCode < 400) coverage.hit("api.account");
|
|
2997
|
+
return;
|
|
2998
|
+
}
|
|
2999
|
+
if (method === "GET" && pathname === "/testkit/portal") {
|
|
3000
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
3001
|
+
res.end(
|
|
3002
|
+
`<!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>`
|
|
3003
|
+
);
|
|
3004
|
+
return;
|
|
3005
|
+
}
|
|
1438
3006
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1439
|
-
return
|
|
3007
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1440
3008
|
}
|
|
1441
3009
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1442
|
-
return
|
|
3010
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1443
3011
|
}
|
|
1444
3012
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1445
|
-
return
|
|
3013
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1446
3014
|
}
|
|
1447
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
3015
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
1448
3016
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1449
|
-
return
|
|
3017
|
+
return sendJson4(res, 200, seed.organizations);
|
|
1450
3018
|
}
|
|
1451
3019
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1452
|
-
return
|
|
3020
|
+
return sendJson4(res, 200, seed.memberships);
|
|
1453
3021
|
}
|
|
1454
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
3022
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1455
3023
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1456
|
-
return
|
|
3024
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1457
3025
|
}
|
|
1458
3026
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1459
3027
|
failures.clear();
|
|
1460
|
-
return
|
|
3028
|
+
return sendJson4(res, 200, { ok: true });
|
|
1461
3029
|
}
|
|
1462
3030
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1463
3031
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1464
|
-
return
|
|
3032
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1465
3033
|
}
|
|
1466
3034
|
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1467
|
-
return
|
|
3035
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
1468
3036
|
}
|
|
1469
3037
|
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1470
|
-
return
|
|
3038
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1471
3039
|
}
|
|
1472
|
-
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return
|
|
1473
|
-
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return
|
|
3040
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
|
|
3041
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
|
|
1474
3042
|
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1475
|
-
return
|
|
3043
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1476
3044
|
}
|
|
1477
3045
|
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1478
3046
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1479
|
-
return
|
|
3047
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1480
3048
|
}
|
|
1481
3049
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1482
3050
|
context.reset();
|
|
1483
|
-
return
|
|
3051
|
+
return sendJson4(res, 200, { ok: true });
|
|
1484
3052
|
}
|
|
1485
3053
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1486
3054
|
const body = await readJson(req);
|
|
1487
|
-
|
|
1488
|
-
|
|
3055
|
+
let accessToken;
|
|
3056
|
+
try {
|
|
3057
|
+
accessToken = await issueToken(testkit, seed, body);
|
|
3058
|
+
} catch (error) {
|
|
3059
|
+
if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
|
|
3060
|
+
throw error;
|
|
3061
|
+
}
|
|
3062
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
3063
|
+
}
|
|
3064
|
+
if (method === "GET" && pathname === "/testkit/coverage") {
|
|
3065
|
+
return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
|
|
3066
|
+
}
|
|
3067
|
+
if (method === "DELETE" && pathname === "/testkit/coverage") {
|
|
3068
|
+
coverage.reset();
|
|
3069
|
+
return sendJson4(res, 200, { ok: true });
|
|
3070
|
+
}
|
|
3071
|
+
if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
|
|
3072
|
+
if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
|
|
3073
|
+
if (method === "POST" && pathname === "/testkit/seed") {
|
|
3074
|
+
const body = await readJson(req);
|
|
3075
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
3076
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
3077
|
+
}
|
|
3078
|
+
context.loadSeed(body);
|
|
3079
|
+
return sendJson4(res, 200, {
|
|
3080
|
+
ok: true,
|
|
3081
|
+
users: seed.users.length,
|
|
3082
|
+
organizations: seed.organizations.length,
|
|
3083
|
+
memberships: seed.memberships.length
|
|
3084
|
+
});
|
|
3085
|
+
}
|
|
3086
|
+
if (method === "POST" && pathname === "/testkit/stop") {
|
|
3087
|
+
sendJson4(res, 200, { ok: true });
|
|
3088
|
+
res.once("finish", () => void context.close().catch(() => void 0));
|
|
3089
|
+
return;
|
|
3090
|
+
}
|
|
3091
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3092
|
+
}
|
|
3093
|
+
async function dashboard(req, res, url, context) {
|
|
3094
|
+
const method = req.method ?? "GET";
|
|
3095
|
+
const { pathname } = url;
|
|
3096
|
+
if (method === "GET" && pathname === "/dashboard") {
|
|
3097
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
3098
|
+
res.end(
|
|
3099
|
+
renderDashboard({
|
|
3100
|
+
issuer: context.testkit.issuer,
|
|
3101
|
+
seed: context.seed,
|
|
3102
|
+
suspended: (id) => context.directory.isSuspended(id),
|
|
3103
|
+
signIns: (id) => {
|
|
3104
|
+
const user = context.directory.user(id);
|
|
3105
|
+
return user ? context.directory.meta(user).totalSignIns : 0;
|
|
3106
|
+
},
|
|
3107
|
+
tokens: context.activity.tokens(),
|
|
3108
|
+
requests: context.activity.requests(),
|
|
3109
|
+
deliveries: context.webhooks.deliveries(),
|
|
3110
|
+
endpoints: context.webhooks.listEndpoints(),
|
|
3111
|
+
failures: context.failures.list(),
|
|
3112
|
+
coverage: context.coverage.report(),
|
|
3113
|
+
webhookTypes: WEBHOOK_EVENT_TYPES,
|
|
3114
|
+
live: url.searchParams.has("live"),
|
|
3115
|
+
notice: url.searchParams.get("notice")
|
|
3116
|
+
})
|
|
3117
|
+
);
|
|
3118
|
+
return;
|
|
3119
|
+
}
|
|
3120
|
+
if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3121
|
+
const origin = req.headers.origin;
|
|
3122
|
+
if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
|
|
3123
|
+
return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
|
|
3124
|
+
}
|
|
3125
|
+
const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
|
|
3126
|
+
let notice = "Done.";
|
|
3127
|
+
try {
|
|
3128
|
+
if (pathname === "/dashboard/reset") {
|
|
3129
|
+
context.reset();
|
|
3130
|
+
notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
|
|
3131
|
+
} else if (pathname === "/dashboard/coverage/reset") {
|
|
3132
|
+
context.coverage.reset();
|
|
3133
|
+
notice = "Cleared coverage.";
|
|
3134
|
+
} else if (pathname === "/dashboard/failures/clear") {
|
|
3135
|
+
context.failures.clear();
|
|
3136
|
+
notice = "Removed every failure rule.";
|
|
3137
|
+
} else if (pathname === "/dashboard/failures") {
|
|
3138
|
+
const rule = { path: form2.path ?? "" };
|
|
3139
|
+
if (form2.method) rule.method = form2.method;
|
|
3140
|
+
if (form2.status) rule.status = Number(form2.status);
|
|
3141
|
+
if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
|
|
3142
|
+
if (form2.times) rule.times = Number(form2.times);
|
|
3143
|
+
if (form2.hang) rule.hang = true;
|
|
3144
|
+
const added = context.failures.add(rule);
|
|
3145
|
+
notice = `Added ${added.id} for ${added.path}.`;
|
|
3146
|
+
} else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
|
|
3147
|
+
const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
|
|
3148
|
+
notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
|
|
3149
|
+
} else if (pathname === "/dashboard/webhooks") {
|
|
3150
|
+
const deliveries = await context.webhooks.send({
|
|
3151
|
+
type: form2.type ?? "",
|
|
3152
|
+
user: form2.user || void 0,
|
|
3153
|
+
invalid: form2.invalid || void 0,
|
|
3154
|
+
duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
|
|
3155
|
+
});
|
|
3156
|
+
const delivered = deliveries.filter((d) => d.delivered).length;
|
|
3157
|
+
notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
|
|
3158
|
+
} else {
|
|
3159
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
|
|
3160
|
+
}
|
|
3161
|
+
} catch (error) {
|
|
3162
|
+
notice = error.message.replace(/\s+/g, " ").trim();
|
|
1489
3163
|
}
|
|
1490
|
-
|
|
3164
|
+
const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
|
|
3165
|
+
res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
|
|
3166
|
+
res.end();
|
|
1491
3167
|
}
|
|
1492
3168
|
function discovery(testkit) {
|
|
1493
3169
|
const base = testkit.issuer;
|
|
@@ -1546,7 +3222,11 @@ async function issueToken(testkit, seed, body) {
|
|
|
1546
3222
|
});
|
|
1547
3223
|
if (permissions) scenario.permissions = permissions;
|
|
1548
3224
|
if (roles) scenario.roles = roles;
|
|
1549
|
-
return await testkit.tokenFor(scenario, {
|
|
3225
|
+
return await testkit.tokenFor(scenario, {
|
|
3226
|
+
expiresIn,
|
|
3227
|
+
invalid: invalid2,
|
|
3228
|
+
featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
|
|
3229
|
+
});
|
|
1550
3230
|
}
|
|
1551
3231
|
const options = {
|
|
1552
3232
|
subject: optionalString(input, "subject"),
|
|
@@ -1611,7 +3291,7 @@ async function readText(req) {
|
|
|
1611
3291
|
}
|
|
1612
3292
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1613
3293
|
}
|
|
1614
|
-
function
|
|
3294
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1615
3295
|
res.writeHead(status, {
|
|
1616
3296
|
"content-type": "application/json; charset=utf-8",
|
|
1617
3297
|
"cache-control": "no-store",
|
|
@@ -1625,16 +3305,16 @@ function sendError(res, error) {
|
|
|
1625
3305
|
return;
|
|
1626
3306
|
}
|
|
1627
3307
|
if (error instanceof TestkitError) {
|
|
1628
|
-
|
|
3308
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1629
3309
|
return;
|
|
1630
3310
|
}
|
|
1631
|
-
|
|
3311
|
+
sendJson4(res, 500, {
|
|
1632
3312
|
error: "server_error",
|
|
1633
3313
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1634
3314
|
});
|
|
1635
3315
|
}
|
|
1636
3316
|
|
|
1637
|
-
// src/
|
|
3317
|
+
// src/handle.ts
|
|
1638
3318
|
async function kindeTest(options) {
|
|
1639
3319
|
const testkit = options.testkit ?? await getDefaultTestkit();
|
|
1640
3320
|
const token = await testkit.tokenFor(options.scenario, options.token);
|
|
@@ -1646,17 +3326,17 @@ async function kindeTest(options) {
|
|
|
1646
3326
|
request: { headers }
|
|
1647
3327
|
};
|
|
1648
3328
|
}
|
|
1649
|
-
function
|
|
3329
|
+
function createKindeTestkitHandle(hooks, options, name) {
|
|
1650
3330
|
let running = null;
|
|
1651
|
-
beforeAll(async () => {
|
|
3331
|
+
hooks.beforeAll(async () => {
|
|
1652
3332
|
running = await startKindeTestkit({ port: 0, ...options });
|
|
1653
3333
|
});
|
|
1654
|
-
afterAll(async () => {
|
|
3334
|
+
hooks.afterAll(async () => {
|
|
1655
3335
|
await running?.close();
|
|
1656
3336
|
running = null;
|
|
1657
3337
|
});
|
|
1658
3338
|
const current = () => {
|
|
1659
|
-
if (!running) throw new Error(
|
|
3339
|
+
if (!running) throw new Error(`${name}() is only ready inside tests and hooks, after beforeAll runs.`);
|
|
1660
3340
|
return running;
|
|
1661
3341
|
};
|
|
1662
3342
|
return {
|
|
@@ -1678,10 +3358,28 @@ function useKindeTestkit(options = {}) {
|
|
|
1678
3358
|
get webhooks() {
|
|
1679
3359
|
return current().webhooks;
|
|
1680
3360
|
},
|
|
3361
|
+
get directory() {
|
|
3362
|
+
return current().directory;
|
|
3363
|
+
},
|
|
3364
|
+
get coverage() {
|
|
3365
|
+
return current().coverage;
|
|
3366
|
+
},
|
|
3367
|
+
get activity() {
|
|
3368
|
+
return current().activity;
|
|
3369
|
+
},
|
|
3370
|
+
get certificatePath() {
|
|
3371
|
+
return current().certificatePath;
|
|
3372
|
+
},
|
|
1681
3373
|
auth: (scenario, token) => kindeTest({ scenario, testkit: current().testkit, token }),
|
|
3374
|
+
loadSeed: (seed) => current().loadSeed(seed),
|
|
1682
3375
|
reset: () => current().reset()
|
|
1683
3376
|
};
|
|
1684
3377
|
}
|
|
3378
|
+
|
|
3379
|
+
// src/vitest.ts
|
|
3380
|
+
function useKindeTestkit(options = {}) {
|
|
3381
|
+
return createKindeTestkitHandle({ beforeAll, afterAll }, options, "useKindeTestkit");
|
|
3382
|
+
}
|
|
1685
3383
|
export {
|
|
1686
3384
|
kindeTest,
|
|
1687
3385
|
useKindeTestkit
|