kinde-testkit 0.5.0 → 0.6.1

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/dist/vitest.js CHANGED
@@ -1,2684 +1,13 @@
1
- // src/vitest.ts
2
- import { afterAll, beforeAll } from "vitest";
3
-
4
- // src/testkit.ts
5
- import { randomUUID } from "crypto";
6
1
  import {
7
- SignJWT,
8
- base64url,
9
- calculateJwkThumbprint,
10
- exportJWK,
11
- generateKeyPair,
12
- jwtVerify
13
- } from "jose";
14
-
15
- // src/ids.ts
16
- import { createHash } from "crypto";
17
- var counters = /* @__PURE__ */ new Map();
18
- function stableId(prefix, seed) {
19
- return `${prefix}_${createHash("sha256").update(seed).digest("hex").slice(0, 16)}`;
20
- }
21
- function nextSequence(prefix) {
22
- const next = (counters.get(prefix) ?? 0) + 1;
23
- counters.set(prefix, next);
24
- return next;
25
- }
26
- function slug(value) {
27
- return value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
28
- }
29
- function titleCase(value) {
30
- return value.replace(/^org_/, "").split(/[_\-\s]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
31
- }
32
-
33
- // src/factories.ts
34
- function createKindeUser(options = {}) {
35
- const email = options.email === void 0 ? `user-${nextSequence("user")}@example.test` : options.email;
36
- const id = options.id ?? (email ? stableId("kp", email) : `kp_test_${nextSequence("kp")}`);
37
- return {
38
- id,
39
- email,
40
- emailVerified: options.emailVerified ?? email !== null,
41
- givenName: options.givenName === void 0 ? null : options.givenName,
42
- familyName: options.familyName === void 0 ? null : options.familyName,
43
- picture: options.picture === void 0 ? null : options.picture,
44
- claims: { ...options.claims ?? {} }
45
- };
46
- }
47
- function createKindeOrganization(options = {}) {
48
- const code = options.code ?? (options.name ? `org_${slug(options.name)}` : `org_test_${nextSequence("org")}`);
49
- return {
50
- code,
51
- name: options.name ?? titleCase(code),
52
- metadata: { ...options.metadata ?? {} }
53
- };
54
- }
55
- function createMembership(options) {
56
- return {
57
- userId: options.userId,
58
- organizationCode: options.organizationCode,
59
- roles: unique(options.roles ?? []),
60
- permissions: unique(options.permissions ?? [])
61
- };
62
- }
63
- function toKindeRole(role) {
64
- if (typeof role !== "string") return role;
65
- return { id: stableId("role", role), key: role, name: titleCase(role) };
66
- }
67
- function unique(values) {
68
- return [...new Set(values)];
69
- }
70
-
71
- // src/errors.ts
72
- var TestkitError = class extends Error {
73
- code;
74
- details;
75
- constructor(code, message, details = []) {
76
- super(details.length > 0 ? `${message}
77
-
78
- ${details.map((d) => ` - ${d}`).join("\n")}` : message);
79
- this.name = "TestkitError";
80
- this.code = code;
81
- this.details = details;
82
- }
83
- toString() {
84
- return `${this.code}
85
-
86
- ${this.message}`;
87
- }
88
- };
89
-
90
- // src/duration.ts
91
- var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
92
- function toSeconds(value) {
93
- if (typeof value === "number") {
94
- if (!Number.isFinite(value) || value < 0) throw invalid(String(value));
95
- return Math.floor(value);
96
- }
97
- const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
98
- if (!match) {
99
- if (/^\d+$/.test(value.trim())) return Number(value.trim());
100
- throw invalid(value);
101
- }
102
- return Number(match[1]) * UNITS[match[2]];
103
- }
104
- function invalid(value) {
105
- return new TestkitError(
106
- "INVALID_DURATION",
107
- `"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
108
- );
109
- }
110
-
111
- // src/testkit.ts
112
- var DEFAULT_ISSUER = "http://localhost:4400";
113
- var DEFAULT_CLIENT_ID = "kinde_testkit_client";
114
- var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
115
- var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
116
- var DEFAULT_AUTH_METHODS = ["email"];
117
- var INVALID_TOKEN_KINDS = [
118
- "expired",
119
- "wrong-issuer",
120
- "wrong-audience",
121
- "missing-subject",
122
- "missing-organization",
123
- "missing-permissions",
124
- "future-iat",
125
- "bad-signature",
126
- "unknown-key",
127
- "unsigned"
128
- ];
129
- var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
130
- var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
131
- var KindeTestkit = class _KindeTestkit {
132
- issuer;
133
- audience;
134
- clientId;
135
- accessTokenExpiresIn;
136
- idTokenExpiresIn;
137
- clock;
138
- signingKey;
139
- strangerKey = null;
140
- static async create(options = {}) {
141
- return new _KindeTestkit(options, await createSigningKey("kinde-testkit"));
142
- }
143
- constructor(options, signingKey) {
144
- this.issuer = trimSlash(options.issuer ?? DEFAULT_ISSUER);
145
- this.audience = toArray(options.audience);
146
- this.clientId = options.clientId ?? DEFAULT_CLIENT_ID;
147
- this.accessTokenExpiresIn = options.accessTokenExpiresIn ?? "24h";
148
- this.idTokenExpiresIn = options.idTokenExpiresIn ?? "1h";
149
- this.clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
150
- this.signingKey = signingKey;
151
- warnIfRealKindeDomain(this.issuer);
152
- }
153
- get jwksUri() {
154
- return `${this.issuer}/.well-known/jwks`;
155
- }
156
- get keyId() {
157
- return this.signingKey.kid;
158
- }
159
- get accessTokenLifetime() {
160
- return toSeconds(this.accessTokenExpiresIn);
161
- }
162
- async verify(token) {
163
- const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
164
- issuer: this.issuer,
165
- algorithms: ["RS256"]
166
- });
167
- return payload;
168
- }
169
- jwks() {
170
- return { keys: [{ ...this.signingKey.publicJwk }] };
171
- }
172
- async token(options = {}) {
173
- const now = this.clock();
174
- const payload = {
175
- amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
176
- aud: [...options.audience ?? this.audience],
177
- auth_time: options.authTime ?? now,
178
- azp: options.clientId ?? this.clientId,
179
- exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
180
- iat: now,
181
- iss: this.issuer,
182
- jti: randomUUID(),
183
- scp: [...options.scopes ?? DEFAULT_SCOPES],
184
- sub: options.subject ?? stableId("kp", "default-test-user")
185
- };
186
- if (options.permissions !== void 0) payload.permissions = [...options.permissions];
187
- if (options.roles !== void 0) payload.roles = options.roles.map(toKindeRole);
188
- if (options.organizationCode) payload.org_code = options.organizationCode;
189
- if (options.featureFlags) payload.feature_flags = options.featureFlags;
190
- Object.assign(payload, options.claims ?? {});
191
- return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
192
- }
193
- async m2mToken(options = {}) {
194
- const now = this.clock();
195
- const requested = [...options.scopes ?? []];
196
- const granted = [...options.grantedScopes ?? requested];
197
- const payload = {
198
- aud: [...options.audience ?? this.audience],
199
- azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
200
- exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
201
- gty: ["client_credentials"],
202
- iat: now,
203
- iss: this.issuer,
204
- jti: randomUUID(),
205
- scope: granted.join(" "),
206
- scp: requested,
207
- v: "2"
208
- };
209
- if (options.organizationCode) payload.org_code = options.organizationCode;
210
- if (options.permissions !== void 0) payload.permissions = [...options.permissions];
211
- Object.assign(payload, options.claims ?? {});
212
- return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
213
- }
214
- async tokenFor(scenario, overrides = {}) {
215
- if (scenario.kind === "unauthenticated") return null;
216
- return this.token({
217
- subject: scenario.user.id,
218
- organizationCode: scenario.organization?.code ?? null,
219
- roles: scenario.roles.length > 0 ? scenario.roles : void 0,
220
- permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
221
- ...overrides,
222
- claims: { ...scenario.claims, ...overrides.claims ?? {} }
223
- });
224
- }
225
- async idTokenFor(scenario, options = {}) {
226
- if (scenario.kind === "unauthenticated") return null;
227
- const { user, organization } = scenario;
228
- const now = this.clock();
229
- const authTime = options.authTime ?? now;
230
- const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
231
- const clientId = options.clientId ?? this.clientId;
232
- const payload = {
233
- amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
234
- aud: [clientId],
235
- auth_time: authTime,
236
- azp: clientId,
237
- email: user.email,
238
- email_verified: user.emailVerified,
239
- exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
240
- family_name: user.familyName,
241
- given_name: user.givenName,
242
- iat: now,
243
- iss: this.issuer,
244
- jti: randomUUID(),
245
- name: name || null,
246
- nonce: options.nonce,
247
- org_codes: organization ? [organization.code] : void 0,
248
- picture: user.picture,
249
- rat: authTime,
250
- sub: user.id,
251
- updated_at: now,
252
- ...user.claims
253
- };
254
- for (const key of Object.keys(payload)) {
255
- if (payload[key] === null || payload[key] === void 0) delete payload[key];
256
- }
257
- return this.sign(payload);
258
- }
259
- async headersFor(scenario, overrides = {}) {
260
- const token = await this.tokenFor(scenario, overrides);
261
- return token ? { authorization: `Bearer ${token}` } : {};
262
- }
263
- principalFor(scenario) {
264
- if (scenario.kind === "unauthenticated") return null;
265
- return scenarioPrincipal(scenario, this.issuer);
266
- }
267
- async signPayload(payload, invalid2) {
268
- return this.sign(payload, invalid2);
269
- }
270
- async sign(payload, invalid2) {
271
- if (invalid2 === "unsigned") {
272
- const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
273
- return `${header}.${base64url.encode(JSON.stringify(payload))}.`;
274
- }
275
- const key = invalid2 === "unknown-key" ? await this.stranger() : this.signingKey;
276
- const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
277
- return invalid2 === "bad-signature" ? tamperSignature(jwt) : jwt;
278
- }
279
- stranger() {
280
- this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
281
- return this.strangerKey;
282
- }
283
- };
284
- function scenarioPrincipal(scenario, issuer) {
285
- return {
286
- type: "user",
287
- subject: scenario.user.id,
288
- issuer,
289
- organization: scenario.organization ? { code: scenario.organization.code } : null,
290
- roles: [...scenario.roles],
291
- permissions: [...scenario.permissions],
292
- claims: { ...scenario.claims }
293
- };
294
- }
295
- function applyInvalidClaims(payload, invalid2, now) {
296
- const next = { ...payload };
297
- switch (invalid2) {
298
- case "expired":
299
- next.iat = now - 7200;
300
- next.exp = now - 3600;
301
- break;
302
- case "future-iat":
303
- next.iat = now + 3600;
304
- next.exp = now + 7200;
305
- break;
306
- case "wrong-issuer":
307
- next.iss = WRONG_ISSUER;
308
- break;
309
- case "wrong-audience":
310
- next.aud = [WRONG_AUDIENCE];
311
- break;
312
- case "missing-subject":
313
- delete next.sub;
314
- break;
315
- case "missing-organization":
316
- delete next.org_code;
317
- break;
318
- case "missing-permissions":
319
- next.permissions = [];
320
- break;
321
- default:
322
- break;
323
- }
324
- return next;
325
- }
326
- async function createSigningKey(prefix) {
327
- const { privateKey, publicKey } = await generateKeyPair("RS256");
328
- const jwk = await exportJWK(publicKey);
329
- const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
330
- return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
331
- }
332
- function tamperSignature(jwt) {
333
- const [header, payload, signature] = jwt.split(".");
334
- const bytes = base64url.decode(signature);
335
- bytes[0] = (bytes[0] ?? 0) ^ 255;
336
- return `${header}.${payload}.${base64url.encode(bytes)}`;
337
- }
338
- function toArray(value) {
339
- if (value === void 0) return [];
340
- return Array.isArray(value) ? [...value] : [value];
341
- }
342
- function trimSlash(value) {
343
- return value.replace(/\/+$/, "");
344
- }
345
- function warnIfRealKindeDomain(issuer) {
346
- if (/^https:\/\/[^/]+\.kinde\.com$/i.test(issuer)) {
347
- process.emitWarning(
348
- `kinde-testkit issuer is set to ${issuer}, which looks like a real Kinde domain. Test tokens are signed with a local key and will never verify against Kinde's JWKS.`,
349
- { code: "KINDE_TESTKIT_REAL_ISSUER" }
350
- );
351
- }
352
- }
353
- var defaultTestkit = null;
354
- function getDefaultTestkit() {
355
- defaultTestkit ??= KindeTestkit.create({
356
- issuer: process.env.KINDE_TESTKIT_ISSUER ?? DEFAULT_ISSUER,
357
- audience: process.env.KINDE_TESTKIT_AUDIENCE?.split(",").filter(Boolean)
358
- });
359
- return defaultTestkit;
360
- }
361
-
362
- // src/server.ts
363
- import { createServer } from "http";
364
- import { createServer as createHttpsServer } from "https";
365
-
366
- // src/certificate.ts
367
- import { createHash as createHash2, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
368
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
369
- import { join, resolve } from "path";
370
- var CERT_FILE = "localhost-cert.pem";
371
- var KEY_FILE = "localhost-key.pem";
372
- var VALID_DAYS = 825;
373
- function ensureLocalCertificate(directory = ".kinde-testkit") {
374
- const dir = resolve(directory);
375
- const certPath = join(dir, CERT_FILE);
376
- const keyPath = join(dir, KEY_FILE);
377
- if (existsSync(certPath) && existsSync(keyPath)) {
378
- const cert2 = readFileSync(certPath, "utf8");
379
- const key2 = readFileSync(keyPath, "utf8");
380
- try {
381
- if (new Date(new X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
382
- return { cert: cert2, key: key2, certPath, keyPath, created: false };
383
- }
384
- } catch {
385
- }
386
- }
387
- const { cert, key } = createLocalCertificate();
388
- mkdirSync(dir, { recursive: true });
389
- writeFileSync(certPath, cert);
390
- writeFileSync(keyPath, key, { mode: 384 });
391
- writeFileSync(join(dir, ".gitignore"), "*\n");
392
- return { cert, key, certPath, keyPath, created: true };
393
- }
394
- function createLocalCertificate() {
395
- const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
396
- const spki = publicKey.export({ type: "spki", format: "der" });
397
- const keyId = createHash2("sha1").update(subjectPublicKeyBits(spki)).digest();
398
- const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
399
- const now = Date.now();
400
- const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
401
- const serial = randomBytes(16);
402
- serial[0] &= 127;
403
- const extensions = seq(
404
- seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
405
- seq(oid("2.5.29.14"), octets(octets(keyId))),
406
- seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
407
- seq(
408
- oid("2.5.29.17"),
409
- octets(
410
- seq(
411
- tlv(130, Buffer.from("localhost")),
412
- tlv(135, Buffer.from([127, 0, 0, 1])),
413
- tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
414
- )
415
- )
416
- )
417
- );
418
- const tbs = seq(
419
- tlv(160, integer(Buffer.from([2]))),
420
- integer(serial),
421
- algorithm,
422
- name,
423
- seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
424
- name,
425
- spki,
426
- tlv(163, extensions)
427
- );
428
- const signature = sign("sha256", tbs, privateKey);
429
- const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
430
- return {
431
- cert: pem("CERTIFICATE", der),
432
- key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
433
- };
434
- }
435
- function subjectPublicKeyBits(spki) {
436
- const outer = readTlv(spki, 0);
437
- const algorithm = readTlv(spki, outer.start);
438
- const bits = readTlv(spki, algorithm.end);
439
- return spki.subarray(bits.start + 1, bits.end);
440
- }
441
- function readTlv(buf, offset) {
442
- let len = buf[offset + 1];
443
- let header = 2;
444
- if (len & 128) {
445
- const n = len & 127;
446
- len = 0;
447
- for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
448
- header += n;
449
- }
450
- return { start: offset + header, end: offset + header + len };
451
- }
452
- function tlv(tag, content) {
453
- return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
454
- }
455
- function length(n) {
456
- if (n < 128) return Buffer.from([n]);
457
- const bytes = [];
458
- while (n > 0) {
459
- bytes.unshift(n & 255);
460
- n >>= 8;
461
- }
462
- return Buffer.from([128 | bytes.length, ...bytes]);
463
- }
464
- function seq(...items) {
465
- return tlv(48, Buffer.concat(items));
466
- }
467
- function set(...items) {
468
- return tlv(49, Buffer.concat(items));
469
- }
470
- function octets(content) {
471
- return tlv(4, content);
472
- }
473
- function integer(bytes) {
474
- return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
475
- }
476
- function oid(dotted) {
477
- const parts = dotted.split(".").map(Number);
478
- const bytes = [parts[0] * 40 + parts[1]];
479
- for (const part of parts.slice(2)) {
480
- const chunk = [part & 127];
481
- let value = part >> 7;
482
- while (value > 0) {
483
- chunk.unshift(value & 127 | 128);
484
- value >>= 7;
485
- }
486
- bytes.push(...chunk);
487
- }
488
- return tlv(6, Buffer.from(bytes));
489
- }
490
- function utcTime(date) {
491
- const iso = date.toISOString();
492
- const value = `${iso.slice(2, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`;
493
- return tlv(23, Buffer.from(value));
494
- }
495
- function pem(label, der) {
496
- const body = der.toString("base64").match(/.{1,64}/g).join("\n");
497
- return `-----BEGIN ${label}-----
498
- ${body}
499
- -----END ${label}-----
500
- `;
501
- }
502
-
503
- // src/login-page.ts
504
- var STYLE = `
505
- :root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--warn:#8a5a00;--warn-bg:#fff6e0}
506
- @media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--warn:#f0c46a;--warn-bg:#2a2210}}
507
- *{box-sizing:border-box}
508
- body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;padding:24px}
509
- main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
510
- .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
511
- h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
512
- p{margin:0;color:var(--muted)}
513
- .note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
514
- form{margin:0}
515
- label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
516
- input[type=email]{width:100%;height:42px;padding:0 12px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit}
517
- input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
518
- .primary{margin-top:12px;width:100%;height:42px;border:0;border-radius:8px;background:var(--accent);color:var(--accent-ink);font-family:inherit;font-size:15px;font-weight:600;cursor:pointer}
519
- h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
520
- .list{display:grid;gap:8px}
521
- .option{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;padding:11px 12px;border:1px solid var(--line);border-radius:8px;background:transparent;color:var(--ink);font:inherit;cursor:pointer}
522
- .option:hover{border-color:var(--muted)}
523
- .option strong{display:block;font-weight:500}
524
- .option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
525
- .tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
526
- .error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
527
- `;
528
- function escapeHtml(value) {
529
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
530
- }
531
- function layout(title, body) {
532
- return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body><main><div class="brand">kinde-testkit</div>${body}</main></body></html>`;
533
- }
534
- function displayName(user) {
535
- return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
536
- }
537
- function renderSignIn(options) {
538
- const users = options.users.map(({ user, organizations }) => {
539
- const value = escapeHtml(user.email ?? user.id);
540
- const hasName = Boolean(user.givenName || user.familyName);
541
- const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
542
- const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
543
- return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag}</span></button>`;
544
- }).join("");
545
- const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
546
- return layout(
547
- "Sign in",
548
- `<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}</form>`
549
- );
550
- }
551
- function renderOrganizationPicker(options) {
552
- const choices = options.organizations.map(
553
- (org) => `<button class="option" type="submit" name="org" value="${escapeHtml(org.code)}"><span><strong>${escapeHtml(org.name)}</strong><small>${escapeHtml(org.code)}</small></span></button>`
554
- ).join("");
555
- return layout(
556
- "Choose an organization",
557
- `<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}"><div class="list" style="margin-top:20px">${choices}</div></form>`
558
- );
559
- }
560
- function renderMessage(title, message) {
561
- return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
562
- }
563
-
564
- // src/seed.ts
565
- function roleRecord(key, extra = {}) {
566
- return {
567
- id: stableId("role", key),
568
- key,
569
- name: extra.name ?? titleCase(key),
570
- description: extra.description ?? null,
571
- isDefault: extra.isDefault ?? false,
572
- permissions: [...extra.permissions ?? []]
573
- };
574
- }
575
- function permissionRecord(key, extra = {}) {
576
- return {
577
- id: stableId("perm", key),
578
- key,
579
- name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
580
- description: extra.description ?? null
581
- };
582
- }
583
- function effectivePermissions(seed, membership) {
584
- if (!membership) return [];
585
- const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
586
- return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
587
- }
588
- function resolveSeed(input) {
589
- const problems = [];
590
- if (!isRecord(input)) {
591
- throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
592
- }
593
- const rawUsers = listOf(input.users, "users", problems);
594
- const rawOrganizations = listOf(input.organizations, "organizations", problems);
595
- const rawMemberships = listOf(input.memberships, "memberships", problems);
596
- const rawApplications = listOf(input.applications, "applications", problems);
597
- const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
598
- const rawRoles = listOf(input.roles, "roles", problems);
599
- const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
600
- const rawPlans = listOf(input.plans, "plans", problems);
601
- const rawPermissions = listOf(input.permissions, "permissions", problems);
602
- const webhooks = [];
603
- rawWebhooks.forEach((raw, index) => {
604
- if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
605
- problems.push(`webhooks[${index}] needs an http or https "url".`);
606
- return;
607
- }
608
- if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
609
- problems.push(`webhooks[${index}].events must be a list of event type names.`);
610
- return;
611
- }
612
- webhooks.push({ url: raw.url, events: raw.events });
613
- });
614
- const users = [];
615
- rawUsers.forEach((raw, index) => {
616
- if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
617
- problems.push(`users[${index}] needs a string "id".`);
618
- return;
619
- }
620
- if (users.some((user) => user.id === raw.id)) {
621
- problems.push(`users[${index}] repeats the id "${raw.id}".`);
622
- return;
623
- }
624
- users.push(createKindeUser(raw));
625
- });
626
- const organizations = [];
627
- rawOrganizations.forEach((raw, index) => {
628
- if (!isRecord(raw) || typeof raw.code !== "string" || raw.code.length === 0) {
629
- problems.push(`organizations[${index}] needs a string "code".`);
630
- return;
631
- }
632
- if (organizations.some((org) => org.code === raw.code)) {
633
- problems.push(`organizations[${index}] repeats the code "${raw.code}".`);
634
- return;
635
- }
636
- organizations.push(createKindeOrganization(raw));
637
- });
638
- const memberships = [];
639
- rawMemberships.forEach((raw, index) => {
640
- if (!isRecord(raw) || typeof raw.user !== "string" || typeof raw.organization !== "string") {
641
- problems.push(`memberships[${index}] needs string "user" and "organization" fields.`);
642
- return;
643
- }
644
- const user = findUser(users, raw.user);
645
- if (!user) problems.push(`memberships[${index}] points to an unknown user "${raw.user}".`);
646
- if (!organizations.some((org) => org.code === raw.organization)) {
647
- problems.push(`memberships[${index}] points to an unknown organization "${raw.organization}".`);
648
- }
649
- for (const field of ["roles", "permissions"]) {
650
- const value = raw[field];
651
- if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
652
- problems.push(`memberships[${index}].${field} must be a list of strings.`);
653
- }
654
- }
655
- if (!user) return;
656
- if (memberships.some((m) => m.userId === user.id && m.organizationCode === raw.organization)) {
657
- problems.push(`memberships[${index}] repeats ${user.id} in ${raw.organization}.`);
658
- return;
659
- }
660
- memberships.push(
661
- createMembership({
662
- userId: user.id,
663
- organizationCode: raw.organization,
664
- roles: raw.roles,
665
- permissions: raw.permissions
666
- })
667
- );
668
- });
669
- const applications = [];
670
- rawApplications.forEach((raw, index) => {
671
- if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
672
- problems.push(`applications[${index}] needs a string "clientId".`);
673
- return;
674
- }
675
- if (applications.some((app) => app.clientId === raw.clientId)) {
676
- problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
677
- return;
678
- }
679
- if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
680
- problems.push(`applications[${index}].clientSecret must be a string.`);
681
- }
682
- if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
683
- problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
684
- }
685
- for (const field of ["scopes", "permissions"]) {
686
- const value = raw[field];
687
- if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
688
- problems.push(`applications[${index}].${field} must be a list of strings.`);
689
- }
690
- }
691
- const audience = raw.audience;
692
- applications.push({
693
- clientId: raw.clientId,
694
- clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
695
- name: typeof raw.name === "string" ? raw.name : raw.clientId,
696
- organizationCode: typeof raw.organization === "string" ? raw.organization : null,
697
- scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
698
- permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
699
- audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
700
- });
701
- });
702
- if (problems.length > 0) {
703
- throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
704
- }
705
- const permissions = [];
706
- rawPermissions.forEach((raw, index) => {
707
- if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
708
- problems.push(`permissions[${index}] needs a string "key".`);
709
- return;
710
- }
711
- if (permissions.some((p) => p.key === raw.key)) {
712
- problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
713
- return;
714
- }
715
- permissions.push(
716
- permissionRecord(raw.key, {
717
- name: typeof raw.name === "string" ? raw.name : void 0,
718
- description: typeof raw.description === "string" ? raw.description : void 0
719
- })
720
- );
721
- });
722
- const roles = [];
723
- rawRoles.forEach((raw, index) => {
724
- if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
725
- problems.push(`roles[${index}] needs a string "key".`);
726
- return;
727
- }
728
- if (roles.some((r) => r.key === raw.key)) {
729
- problems.push(`roles[${index}] repeats the key "${raw.key}".`);
730
- return;
731
- }
732
- if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
733
- problems.push(`roles[${index}].permissions must be a list of permission keys.`);
734
- return;
735
- }
736
- roles.push(
737
- roleRecord(raw.key, {
738
- name: typeof raw.name === "string" ? raw.name : void 0,
739
- description: typeof raw.description === "string" ? raw.description : void 0,
740
- isDefault: raw.isDefault === true,
741
- permissions: raw.permissions ?? []
742
- })
743
- );
744
- });
745
- if (problems.length > 0) {
746
- throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
747
- }
748
- const featureFlags = [];
749
- rawFlags.forEach((raw, index) => {
750
- if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
751
- problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
752
- return;
753
- }
754
- const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
755
- featureFlags.push({
756
- id: stableId("flag", raw.key),
757
- key: raw.key,
758
- name: typeof raw.name === "string" ? raw.name : raw.key,
759
- type,
760
- value: raw.value,
761
- organizations: isRecord(raw.organizations) ? raw.organizations : {}
762
- });
763
- });
764
- const plans = [];
765
- rawPlans.forEach((raw, index) => {
766
- if (!isRecord(raw) || typeof raw.key !== "string") {
767
- problems.push(`plans[${index}] needs a string "key".`);
768
- return;
769
- }
770
- const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
771
- plans.push({
772
- key: raw.key,
773
- name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
774
- subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
775
- subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
776
- entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
777
- id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
778
- featureKey: e.featureKey,
779
- featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
780
- priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
781
- fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
782
- unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
783
- limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
784
- limitMin: typeof e.limitMin === "number" ? e.limitMin : null
785
- }))
786
- });
787
- });
788
- const userProperties = {};
789
- rawUsers.forEach((raw) => {
790
- if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
791
- userProperties[raw.id] = raw.properties;
792
- }
793
- });
794
- if (problems.length > 0) {
795
- throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
796
- }
797
- const usedRoles = new Set(memberships.flatMap((m) => m.roles));
798
- for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
799
- const usedPermissions = /* @__PURE__ */ new Set([
800
- ...memberships.flatMap((m) => m.permissions),
801
- ...roles.flatMap((r) => r.permissions),
802
- ...applications.flatMap((a) => a.permissions ?? [])
803
- ]);
804
- for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
805
- return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
806
- }
807
- function findUser(users, ref) {
808
- const needle = ref.toLowerCase();
809
- return users.find((user) => user.id === ref || user.email?.toLowerCase() === needle);
810
- }
811
- function seedScenario(seed, ref) {
812
- const user = findUser(seed.users, ref.user);
813
- if (!user) {
814
- throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${ref.user}".`, [
815
- `Known users: ${seed.users.map((u) => u.email ?? u.id).join(", ") || "none"}`
816
- ]);
817
- }
818
- const userMemberships = seed.memberships.filter((m) => m.userId === user.id);
819
- let membership;
820
- if (ref.organization) {
821
- if (!seed.organizations.some((org) => org.code === ref.organization)) {
822
- throw new TestkitError(
823
- "SEED_UNKNOWN_ORGANIZATION",
824
- `No seeded organization has the code "${ref.organization}".`
825
- );
826
- }
827
- membership = userMemberships.find((m) => m.organizationCode === ref.organization);
828
- if (!membership) {
829
- throw new TestkitError(
830
- "SEED_NO_MEMBERSHIP",
831
- `${user.email ?? user.id} is not a member of ${ref.organization}, so Kinde would not issue a token for that organization.`,
832
- [`Member of: ${userMemberships.map((m) => m.organizationCode).join(", ") || "no organizations"}`]
833
- );
834
- }
835
- } else if (userMemberships.length === 1) {
836
- membership = userMemberships[0];
837
- } else if (userMemberships.length > 1) {
838
- throw new TestkitError(
839
- "INVALID_REQUEST",
840
- `${user.email ?? user.id} belongs to ${userMemberships.length} organizations. Choose the active one.`,
841
- [`Organizations: ${userMemberships.map((m) => m.organizationCode).join(", ")}`]
842
- );
843
- }
844
- const organization = membership ? seed.organizations.find((org) => org.code === membership.organizationCode) ?? null : null;
845
- return {
846
- kind: "authenticated",
847
- user,
848
- organization,
849
- roles: [...membership?.roles ?? []],
850
- permissions: effectivePermissions(seed, membership),
851
- claims: {}
852
- };
853
- }
854
- function listOf(value, field, problems) {
855
- if (value === void 0) return [];
856
- if (!Array.isArray(value)) {
857
- problems.push(`"${field}" must be a list.`);
858
- return [];
859
- }
860
- return value;
861
- }
862
- function isRecord(value) {
863
- return typeof value === "object" && value !== null && !Array.isArray(value);
864
- }
865
- function featureFlagsFor(seed, organizationCode) {
866
- if (seed.featureFlags.length === 0) return void 0;
867
- const claim = {};
868
- for (const flag of seed.featureFlags) {
869
- const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
870
- claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
871
- }
872
- return claim;
873
- }
874
-
875
- // src/oauth.ts
876
- import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
877
- var CODE_LIFETIME_MS = 10 * 60 * 1e3;
878
- var OAuthError = class extends Error {
879
- constructor(status, error, description) {
880
- super(description);
881
- this.status = status;
882
- this.error = error;
883
- }
884
- status;
885
- error;
886
- };
887
- var AuthorizationServer = class {
888
- constructor(testkit, seed, emit = () => void 0, directory) {
889
- this.testkit = testkit;
890
- this.seed = seed;
891
- this.emit = emit;
892
- this.directory = directory;
893
- }
894
- testkit;
895
- seed;
896
- emit;
897
- directory;
898
- codes = /* @__PURE__ */ new Map();
899
- refreshTokens = /* @__PURE__ */ new Map();
900
- signedUpUsers = /* @__PURE__ */ new Map();
901
- async handle(req, res, url, readBody) {
902
- const method = req.method ?? "GET";
903
- switch (`${method} ${url.pathname}`) {
904
- case "GET /oauth2/auth":
905
- this.authorize(res, url.searchParams);
906
- return true;
907
- case "POST /oauth2/auth/login":
908
- this.login(res, await readBody());
909
- return true;
910
- case "POST /oauth2/token":
911
- await this.token(req, res, await readBody());
912
- return true;
913
- case "GET /oauth2/v2/user_profile":
914
- await this.profile(req, res);
915
- return true;
916
- case "POST /oauth2/revoke":
917
- this.revoke(res, await readBody());
918
- return true;
919
- case "GET /logout":
920
- this.logout(res, url.searchParams);
921
- return true;
922
- default:
923
- return false;
924
- }
925
- }
926
- authorize(res, params) {
927
- let request;
928
- try {
929
- request = parseAuthorizeRequest(params);
930
- } catch (error) {
931
- return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
932
- }
933
- if (params.get("prompt") === "none") {
934
- return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
935
- }
936
- sendHtml(
937
- res,
938
- 200,
939
- renderSignIn({
940
- request: encodeRequest(request),
941
- users: this.loginPageUsers(),
942
- loginHint: request.loginHint ?? void 0,
943
- requiredOrganization: request.orgCode ?? void 0
944
- })
945
- );
946
- }
947
- login(res, form) {
948
- let request;
949
- try {
950
- request = decodeRequest(form.request ?? "");
951
- } catch {
952
- return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
953
- }
954
- const encoded = encodeRequest(request);
955
- const ref = (form.user || form.email || "").trim();
956
- if (!ref) {
957
- 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." }));
958
- }
959
- const user = this.resolveUser(ref);
960
- if (!user) {
961
- return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
962
- }
963
- if (this.directory?.isSuspended(user.id)) {
964
- return sendHtml(
965
- res,
966
- 403,
967
- renderSignIn({
968
- request: encoded,
969
- users: this.loginPageUsers(),
970
- requiredOrganization: request.orgCode ?? void 0,
971
- error: `${user.email ?? user.id} is suspended and cannot sign in.`
972
- })
973
- );
974
- }
975
- const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
976
- const wanted = request.orgCode ?? form.org ?? null;
977
- let organizationCode = null;
978
- if (wanted) {
979
- if (!memberships.some((m) => m.organizationCode === wanted)) {
980
- return sendHtml(
981
- res,
982
- 403,
983
- renderSignIn({
984
- request: encoded,
985
- users: this.loginPageUsers(),
986
- requiredOrganization: request.orgCode ?? void 0,
987
- error: `${user.email ?? user.id} is not a member of ${wanted}.`
988
- })
989
- );
990
- }
991
- organizationCode = wanted;
992
- } else if (memberships.length === 1) {
993
- organizationCode = memberships[0].organizationCode;
994
- } else if (memberships.length > 1) {
995
- return sendHtml(
996
- res,
997
- 200,
998
- renderOrganizationPicker({
999
- request: encoded,
1000
- user,
1001
- organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
1002
- })
1003
- );
1004
- }
1005
- const membership = memberships.find((m) => m.organizationCode === organizationCode);
1006
- const scenario = {
1007
- kind: "authenticated",
1008
- user,
1009
- organization: organizationCode ? this.organization(organizationCode) : null,
1010
- roles: [...membership?.roles ?? []],
1011
- permissions: effectivePermissions(this.seed, membership),
1012
- claims: {}
1013
- };
1014
- const code = randomToken();
1015
- this.codes.set(code, {
1016
- clientId: request.clientId,
1017
- redirectUri: request.redirectUri,
1018
- scenario,
1019
- scope: request.scope,
1020
- audience: request.audience,
1021
- nonce: request.nonce,
1022
- authTime: Math.floor(Date.now() / 1e3),
1023
- codeChallenge: request.codeChallenge,
1024
- codeChallengeMethod: request.codeChallengeMethod,
1025
- expiresAt: Date.now() + CODE_LIFETIME_MS
1026
- });
1027
- this.directory?.recordSignIn(user, organizationCode);
1028
- this.emit("user.authenticated", user);
1029
- const target = new URL(request.redirectUri);
1030
- target.searchParams.set("code", code);
1031
- if (request.state !== null) target.searchParams.set("state", request.state);
1032
- redirect(res, target.toString());
1033
- }
1034
- async token(req, res, form) {
1035
- try {
1036
- const clientId = clientIdFrom(req, form);
1037
- const grantType = form.grant_type;
1038
- if (grantType === "client_credentials") {
1039
- return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
1040
- }
1041
- let grant;
1042
- if (grantType === "authorization_code") {
1043
- grant = this.redeemCode(form, clientId);
1044
- } else if (grantType === "refresh_token") {
1045
- grant = this.redeemRefreshToken(form, clientId);
1046
- } else {
1047
- throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
1048
- }
1049
- sendJson(res, 200, await this.issueTokens(grant));
1050
- } catch (error) {
1051
- if (error instanceof OAuthError) {
1052
- return sendJson(res, error.status, { error: error.error, error_description: error.message });
1053
- }
1054
- throw error;
1055
- }
1056
- }
1057
- async clientCredentials(clientId, clientSecret, form) {
1058
- const app = this.seed.applications.find((a) => a.clientId === clientId);
1059
- if (app?.clientSecret && app.clientSecret !== clientSecret) {
1060
- throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
1061
- }
1062
- const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
1063
- const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
1064
- const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
1065
- return {
1066
- access_token: await this.testkit.m2mToken({
1067
- clientId,
1068
- organizationCode: app?.organizationCode ?? null,
1069
- scopes: requested,
1070
- grantedScopes: granted,
1071
- audience: audience.length > 0 ? audience : app?.audience ?? void 0,
1072
- permissions: app?.permissions ?? void 0
1073
- }),
1074
- expires_in: this.testkit.accessTokenLifetime,
1075
- scope: granted.join(" "),
1076
- token_type: "bearer"
1077
- };
1078
- }
1079
- reset() {
1080
- this.codes.clear();
1081
- this.refreshTokens.clear();
1082
- this.signedUpUsers.clear();
1083
- }
1084
- redeemCode(form, clientId) {
1085
- const code = form.code ?? "";
1086
- const pending = this.codes.get(code);
1087
- this.codes.delete(code);
1088
- if (!pending || pending.expiresAt < Date.now()) {
1089
- throw new OAuthError(400, "invalid_grant", "The authorization code is unknown, expired or already used.");
1090
- }
1091
- if (pending.clientId !== clientId) {
1092
- throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
1093
- }
1094
- if (form.redirect_uri !== pending.redirectUri) {
1095
- throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
1096
- }
1097
- if (pending.codeChallenge) {
1098
- const verifier = form.code_verifier ?? "";
1099
- const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
1100
- if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
1101
- throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
1102
- }
1103
- }
1104
- return pending;
1105
- }
1106
- redeemRefreshToken(form, clientId) {
1107
- const token = form.refresh_token ?? "";
1108
- const grant = this.refreshTokens.get(token);
1109
- this.refreshTokens.delete(token);
1110
- if (!grant) {
1111
- throw new OAuthError(400, "invalid_grant", "The refresh token is unknown, revoked or already used.");
1112
- }
1113
- if (grant.clientId !== clientId) {
1114
- throw new OAuthError(400, "invalid_grant", "The refresh token was issued to a different client.");
1115
- }
1116
- return grant;
1117
- }
1118
- async issueTokens(grant) {
1119
- const { scenario } = grant;
1120
- const body = {
1121
- access_token: await this.testkit.token({
1122
- subject: scenario.user.id,
1123
- organizationCode: scenario.organization?.code ?? null,
1124
- roles: scenario.roles.length > 0 ? scenario.roles : void 0,
1125
- permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
1126
- scopes: grant.scope,
1127
- clientId: grant.clientId,
1128
- audience: grant.audience.length > 0 ? grant.audience : void 0,
1129
- authTime: grant.authTime,
1130
- featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
1131
- }),
1132
- expires_in: this.testkit.accessTokenLifetime,
1133
- scope: grant.scope.join(" "),
1134
- token_type: "bearer"
1135
- };
1136
- if (grant.scope.includes("openid")) {
1137
- body.id_token = await this.testkit.idTokenFor(scenario, {
1138
- clientId: grant.clientId,
1139
- nonce: grant.nonce ?? void 0,
1140
- authTime: grant.authTime
1141
- });
1142
- }
1143
- if (grant.scope.includes("offline")) {
1144
- const refreshToken = randomToken();
1145
- this.refreshTokens.set(refreshToken, { ...grant, nonce: null });
1146
- body.refresh_token = refreshToken;
1147
- }
1148
- return body;
1149
- }
1150
- async profile(req, res) {
1151
- const header = req.headers.authorization ?? "";
1152
- if (!header.startsWith("Bearer ")) {
1153
- return sendJson(res, 401, { error: "invalid_token", error_description: "Send the access token as a Bearer token." });
1154
- }
1155
- let sub;
1156
- try {
1157
- sub = String((await this.testkit.verify(header.slice(7))).sub ?? "");
1158
- } catch {
1159
- return sendJson(res, 401, { error: "invalid_token", error_description: "The access token is not valid for this issuer." });
1160
- }
1161
- const user = this.seed.users.find((u) => u.id === sub) ?? this.signedUpUsers.get(sub);
1162
- if (!user) {
1163
- return sendJson(res, 404, { error: "not_found", error_description: `No user has the id ${sub}.` });
1164
- }
1165
- const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
1166
- sendJson(res, 200, {
1167
- id: user.id,
1168
- sub: user.id,
1169
- provided_id: null,
1170
- name: name || null,
1171
- given_name: user.givenName,
1172
- family_name: user.familyName,
1173
- updated_at: Math.floor(Date.now() / 1e3),
1174
- email: user.email,
1175
- email_verified: user.emailVerified,
1176
- picture: user.picture,
1177
- preferred_username: null,
1178
- phone: null
1179
- });
1180
- }
1181
- revoke(res, form) {
1182
- if (form.token) this.refreshTokens.delete(form.token);
1183
- sendJson(res, 200, {});
1184
- }
1185
- logout(res, params) {
1186
- const target = params.get("redirect");
1187
- if (target && isHttpUrl(target)) return redirect(res, target);
1188
- sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
1189
- }
1190
- resolveUser(ref) {
1191
- const seeded = findUser(this.seed.users, ref);
1192
- if (seeded) return seeded;
1193
- if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
1194
- const user = createKindeUser({ email: ref.toLowerCase() });
1195
- if (!this.signedUpUsers.has(user.id)) {
1196
- this.signedUpUsers.set(user.id, user);
1197
- if (this.directory) this.seed.users.push(user);
1198
- this.emit("user.created", user);
1199
- }
1200
- return this.signedUpUsers.get(user.id);
1201
- }
1202
- organization(code) {
1203
- return this.seed.organizations.find((org) => org.code === code) ?? null;
1204
- }
1205
- loginPageUsers() {
1206
- return this.seed.users.map((user) => ({
1207
- user,
1208
- organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
1209
- }));
1210
- }
1211
- };
1212
- function parseAuthorizeRequest(params) {
1213
- const clientId = params.get("client_id");
1214
- const redirectUri = params.get("redirect_uri");
1215
- if (!clientId) throw new Error("client_id is missing.");
1216
- if (!redirectUri || !isHttpUrl(redirectUri)) {
1217
- throw new Error("redirect_uri must be an absolute http or https URL.");
1218
- }
1219
- if (params.get("response_type") !== "code") {
1220
- throw new Error('response_type must be "code".');
1221
- }
1222
- const method = params.get("code_challenge_method");
1223
- const challenge = params.get("code_challenge");
1224
- if (challenge && method && method !== "S256" && method !== "plain") {
1225
- throw new Error('code_challenge_method must be "S256" or "plain".');
1226
- }
1227
- return {
1228
- clientId,
1229
- redirectUri,
1230
- state: params.get("state"),
1231
- scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
1232
- nonce: params.get("nonce"),
1233
- audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
1234
- orgCode: params.get("org_code"),
1235
- loginHint: params.get("login_hint"),
1236
- codeChallenge: challenge,
1237
- codeChallengeMethod: challenge ? method ?? "plain" : null
1238
- };
1239
- }
1240
- function encodeRequest(request) {
1241
- return Buffer.from(JSON.stringify(request)).toString("base64url");
1242
- }
1243
- function decodeRequest(value) {
1244
- const request = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
1245
- if (!request.clientId || !request.redirectUri || !isHttpUrl(request.redirectUri)) {
1246
- throw new Error("invalid request");
1247
- }
1248
- return request;
1249
- }
1250
- function clientIdFrom(req, form) {
1251
- const header = req.headers.authorization ?? "";
1252
- if (header.startsWith("Basic ")) {
1253
- const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
1254
- const id = decodeURIComponent(decoded.split(":")[0] ?? "");
1255
- if (id) return id;
1256
- }
1257
- if (form.client_id) return form.client_id;
1258
- throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
1259
- }
1260
- function clientSecretFrom(req, form) {
1261
- const header = req.headers.authorization ?? "";
1262
- if (header.startsWith("Basic ")) {
1263
- const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
1264
- const index = decoded.indexOf(":");
1265
- if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
1266
- }
1267
- return form.client_secret ?? null;
1268
- }
1269
- function redirectWithError(res, request, error, description) {
1270
- const target = new URL(request.redirectUri);
1271
- target.searchParams.set("error", error);
1272
- target.searchParams.set("error_description", description);
1273
- if (request.state !== null) target.searchParams.set("state", request.state);
1274
- redirect(res, target.toString());
1275
- }
1276
- function isHttpUrl(value) {
1277
- try {
1278
- const { protocol } = new URL(value);
1279
- return protocol === "http:" || protocol === "https:";
1280
- } catch {
1281
- return false;
1282
- }
1283
- }
1284
- function randomToken() {
1285
- return randomBytes2(32).toString("base64url");
1286
- }
1287
- function safeEqual(a, b) {
1288
- const left = Buffer.from(a);
1289
- const right = Buffer.from(b);
1290
- return left.length === right.length && timingSafeEqual(left, right);
1291
- }
1292
- function redirect(res, location) {
1293
- res.writeHead(303, { location, "cache-control": "no-store" });
1294
- res.end();
1295
- }
1296
- function sendHtml(res, status, html) {
1297
- res.writeHead(status, {
1298
- "content-type": "text/html; charset=utf-8",
1299
- "cache-control": "no-store",
1300
- "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
1301
- });
1302
- res.end(html);
1303
- }
1304
- function sendJson(res, status, body) {
1305
- res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1306
- res.end(JSON.stringify(body));
1307
- }
1308
-
1309
- // src/account.ts
1310
- var DEFAULT_PAGE_SIZE = 10;
1311
- var AccountApi = class {
1312
- constructor(testkit, directory) {
1313
- this.testkit = testkit;
1314
- this.directory = directory;
1315
- }
1316
- testkit;
1317
- directory;
1318
- async handle(req, res, url) {
1319
- if (!url.pathname.startsWith("/account_api/v1/")) return false;
1320
- if ((req.method ?? "GET") !== "GET") {
1321
- sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
1322
- return true;
1323
- }
1324
- const header = req.headers.authorization ?? "";
1325
- let token;
1326
- try {
1327
- if (!header.startsWith("Bearer ")) throw new Error("missing");
1328
- token = await this.testkit.verify(header.slice(7));
1329
- } catch {
1330
- sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
1331
- return true;
1332
- }
1333
- if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
1334
- sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
1335
- return true;
1336
- }
1337
- const userId = token.sub;
1338
- const orgCode = typeof token.org_code === "string" ? token.org_code : null;
1339
- const path = url.pathname.slice("/account_api/v1/".length);
1340
- const d = this.directory;
1341
- const membership = orgCode ? d.membership(userId, orgCode) : void 0;
1342
- if (path === "permissions") {
1343
- const items = effectivePermissions(d.seed, membership).map((key) => {
1344
- const p = d.ensurePermission(key);
1345
- return { id: p.id, name: p.name, key: p.key };
1346
- });
1347
- sendPage(res, url, "permissions", items, { org_code: orgCode });
1348
- return true;
1349
- }
1350
- if (path.startsWith("permission/")) {
1351
- const key = decodeURIComponent(path.slice("permission/".length));
1352
- sendJson2(res, 200, {
1353
- data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
1354
- });
1355
- return true;
1356
- }
1357
- if (path === "roles") {
1358
- const items = (membership?.roles ?? []).map((key) => {
1359
- const r = d.ensureRole(key);
1360
- return { id: r.id, name: r.name, key: r.key };
1361
- });
1362
- sendPage(res, url, "roles", items, { org_code: orgCode });
1363
- return true;
1364
- }
1365
- if (path === "feature_flags") {
1366
- const items = d.seed.featureFlags.map((flag) => ({
1367
- id: flag.id,
1368
- name: flag.name,
1369
- key: flag.key,
1370
- type: flag.type,
1371
- value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
1372
- }));
1373
- sendPage(res, url, "feature_flags", items, {});
1374
- return true;
1375
- }
1376
- if (path === "properties") {
1377
- const values = d.seed.userProperties[userId] ?? {};
1378
- const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
1379
- sendPage(res, url, "properties", items, {});
1380
- return true;
1381
- }
1382
- if (path === "entitlements" || path.startsWith("entitlement")) {
1383
- const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
1384
- const entitlements = (plan?.entitlements ?? []).map((e) => ({
1385
- id: e.id,
1386
- fixed_charge: e.fixedCharge,
1387
- price_name: e.priceName,
1388
- unit_amount: e.unitAmount,
1389
- feature_key: e.featureKey,
1390
- feature_name: e.featureName,
1391
- entitlement_limit_max: e.limitMax,
1392
- entitlement_limit_min: e.limitMin
1393
- }));
1394
- if (path === "entitlements") {
1395
- const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
1396
- sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
1397
- return true;
1398
- }
1399
- const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
1400
- const entitlement = entitlements.find((e) => e.feature_key === key);
1401
- if (!entitlement) {
1402
- sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
1403
- } else {
1404
- sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
1405
- }
1406
- return true;
1407
- }
1408
- if (path === "portal_link") {
1409
- sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
1410
- return true;
1411
- }
1412
- sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
1413
- return true;
1414
- }
1415
- };
1416
- function sendPage(res, url, field, items, extra) {
1417
- const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
1418
- const after = url.searchParams.get("starting_after");
1419
- const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
1420
- const page = items.slice(start, start + size);
1421
- const hasMore = start + size < items.length;
1422
- sendJson2(res, 200, {
1423
- data: { ...extra, [field]: page },
1424
- metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
1425
- });
1426
- }
1427
- function errors(code, message) {
1428
- return { errors: [{ code, message }] };
1429
- }
1430
- function sendJson2(res, status, body) {
1431
- res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1432
- res.end(JSON.stringify(body));
1433
- }
1434
-
1435
- // src/directory.ts
1436
- import { randomBytes as randomBytes3 } from "crypto";
1437
- var Directory = class {
1438
- constructor(seed) {
1439
- this.seed = seed;
1440
- this.snapshot = JSON.stringify(seed);
1441
- }
1442
- seed;
1443
- userMeta = /* @__PURE__ */ new Map();
1444
- orgMeta = /* @__PURE__ */ new Map();
1445
- snapshot;
1446
- restore() {
1447
- const original = JSON.parse(this.snapshot);
1448
- for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
1449
- this.seed[key].splice(0, this.seed[key].length, ...original[key]);
1450
- }
1451
- this.userMeta.clear();
1452
- this.orgMeta.clear();
1453
- }
1454
- user(id) {
1455
- return this.seed.users.find((user) => user.id === id);
1456
- }
1457
- meta(user) {
1458
- let meta = this.userMeta.get(user.id);
1459
- if (!meta) {
1460
- meta = {
1461
- providedId: null,
1462
- isSuspended: false,
1463
- isPasswordResetRequested: false,
1464
- createdOn: (/* @__PURE__ */ new Date()).toISOString(),
1465
- totalSignIns: 0,
1466
- lastSignedIn: null
1467
- };
1468
- this.userMeta.set(user.id, meta);
1469
- }
1470
- return meta;
1471
- }
1472
- isSuspended(userId) {
1473
- return this.userMeta.get(userId)?.isSuspended ?? false;
1474
- }
1475
- recordSignIn(user, organizationCode) {
1476
- const meta = this.meta(user);
1477
- meta.totalSignIns += 1;
1478
- meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
1479
- void organizationCode;
1480
- }
1481
- createUser(input) {
1482
- const user = createKindeUser({
1483
- id: `kp_${randomBytes3(16).toString("hex")}`,
1484
- email: input.email ?? null,
1485
- givenName: input.givenName ?? null,
1486
- familyName: input.familyName ?? null,
1487
- picture: input.picture ?? null
1488
- });
1489
- this.seed.users.push(user);
1490
- this.meta(user).providedId = input.providedId ?? null;
1491
- return user;
1492
- }
1493
- deleteUser(id) {
1494
- const index = this.seed.users.findIndex((user) => user.id === id);
1495
- if (index < 0) return false;
1496
- this.seed.users.splice(index, 1);
1497
- for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
1498
- if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
1499
- }
1500
- this.userMeta.delete(id);
1501
- return true;
1502
- }
1503
- organization(code) {
1504
- return this.seed.organizations.find((org) => org.code === code);
1505
- }
1506
- orgInfo(org) {
1507
- let meta = this.orgMeta.get(org.code);
1508
- if (!meta) {
1509
- meta = {
1510
- externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
1511
- handle: slug(org.name),
1512
- createdOn: (/* @__PURE__ */ new Date()).toISOString(),
1513
- isAllowRegistrations: false
1514
- };
1515
- this.orgMeta.set(org.code, meta);
1516
- }
1517
- return meta;
1518
- }
1519
- createOrganization(input) {
1520
- const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
1521
- this.seed.organizations.push(org);
1522
- const meta = this.orgInfo(org);
1523
- meta.externalId = input.externalId ?? null;
1524
- if (input.handle) meta.handle = input.handle;
1525
- return org;
1526
- }
1527
- deleteOrganization(code) {
1528
- const index = this.seed.organizations.findIndex((org) => org.code === code);
1529
- if (index < 0) return false;
1530
- this.seed.organizations.splice(index, 1);
1531
- for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
1532
- if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
1533
- }
1534
- this.orgMeta.delete(code);
1535
- return true;
1536
- }
1537
- membership(userId, organizationCode) {
1538
- return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
1539
- }
1540
- addMembership(userId, organizationCode, roles = [], permissions = []) {
1541
- const existing = this.membership(userId, organizationCode);
1542
- if (existing) return existing;
1543
- const membership = createMembership({ userId, organizationCode, roles, permissions });
1544
- this.seed.memberships.push(membership);
1545
- for (const key of roles) this.ensureRole(key);
1546
- for (const key of permissions) this.ensurePermission(key);
1547
- return membership;
1548
- }
1549
- removeMembership(userId, organizationCode) {
1550
- const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
1551
- if (index < 0) return false;
1552
- this.seed.memberships.splice(index, 1);
1553
- return true;
1554
- }
1555
- role(idOrKey) {
1556
- return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
1557
- }
1558
- permission(idOrKey) {
1559
- return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
1560
- }
1561
- ensureRole(key, extra = {}) {
1562
- const existing = this.role(key);
1563
- if (existing) return existing;
1564
- const role = roleRecord(key, extra);
1565
- this.seed.roles.push(role);
1566
- return role;
1567
- }
1568
- ensurePermission(key, extra = {}) {
1569
- const existing = this.permission(key);
1570
- if (existing) return existing;
1571
- const permission = permissionRecord(key, extra);
1572
- this.seed.permissions.push(permission);
1573
- return permission;
1574
- }
1575
- deleteRole(id) {
1576
- const role = this.role(id);
1577
- if (!role) return void 0;
1578
- this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
1579
- for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
1580
- return role;
1581
- }
1582
- deletePermission(id) {
1583
- const permission = this.permission(id);
1584
- if (!permission) return void 0;
1585
- this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
1586
- for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
1587
- for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
1588
- return permission;
1589
- }
1590
- };
1591
-
1592
- // src/management.ts
1593
- var OK = { code: "OK", message: "Success" };
1594
- var DEFAULT_PAGE_SIZE2 = 10;
1595
- var MAX_PAGE_SIZE = 500;
1596
- var ManagementApi = class {
1597
- constructor(testkit, directory, webhooks) {
1598
- this.testkit = testkit;
1599
- this.directory = directory;
1600
- this.webhooks = webhooks;
1601
- this.register();
1602
- }
1603
- testkit;
1604
- directory;
1605
- webhooks;
1606
- routes = [];
1607
- async handle(req, res, url, readBody) {
1608
- if (!url.pathname.startsWith("/api/v1/")) return false;
1609
- const method = req.method ?? "GET";
1610
- const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
1611
- if (!route) {
1612
- sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
1613
- return true;
1614
- }
1615
- const token = await this.authenticate(req.headers.authorization);
1616
- if ("error" in token) {
1617
- sendJson3(res, 403, errors2(token.code, token.error));
1618
- return true;
1619
- }
1620
- const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
1621
- if (granted.length > 0 && !granted.includes(route.scope)) {
1622
- sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
1623
- return true;
1624
- }
1625
- const match = route.pattern.exec(url.pathname);
1626
- const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
1627
- const body = method === "GET" || method === "DELETE" ? {} : await readBody();
1628
- const [status, payload] = await route.handler({ params, query: url.searchParams, body });
1629
- sendJson3(res, status, payload);
1630
- return true;
1631
- }
1632
- async authenticate(header) {
1633
- if (!header?.startsWith("Bearer ")) {
1634
- return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
1635
- }
1636
- let payload;
1637
- try {
1638
- payload = await this.testkit.verify(header.slice(7));
1639
- } catch {
1640
- return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
1641
- }
1642
- const audience = `${this.testkit.issuer}/api`;
1643
- const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
1644
- if (!aud.includes(audience)) {
1645
- return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
1646
- }
1647
- if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
1648
- return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
1649
- }
1650
- return { payload };
1651
- }
1652
- route(method, path, scope, handler) {
1653
- const keys = [];
1654
- const pattern = new RegExp(
1655
- `^${path.replace(/\{(\w+)\}/g, (_, key) => {
1656
- keys.push(key);
1657
- return "([^/]+)";
1658
- })}$`
1659
- );
1660
- this.routes.push({ method, pattern, keys, scope, handler });
1661
- }
1662
- register() {
1663
- const d = this.directory;
1664
- this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
1665
- let users = [...d.seed.users];
1666
- const userId = query.get("user_id");
1667
- const email = query.get("email")?.toLowerCase();
1668
- if (userId) users = users.filter((u) => u.id === userId);
1669
- if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
1670
- const page = paginate(users, query);
1671
- return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
1672
- });
1673
- this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
1674
- const user = d.user(query.get("id") ?? "");
1675
- return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
1676
- });
1677
- this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
1678
- const profile = body.profile ?? {};
1679
- const identities = Array.isArray(body.identities) ? body.identities : [];
1680
- const emailIdentity = identities.find((i) => i.type === "email");
1681
- const email = (emailIdentity?.details ?? {}).email;
1682
- if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
1683
- return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
1684
- }
1685
- const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
1686
- if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
1687
- const user = d.createUser({
1688
- email: typeof email === "string" ? email : null,
1689
- givenName: str(profile.given_name),
1690
- familyName: str(profile.family_name),
1691
- picture: str(profile.picture),
1692
- providedId: str(body.provided_id)
1693
- });
1694
- if (orgCode) d.addMembership(user.id, orgCode);
1695
- this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
1696
- return [
1697
- 200,
1698
- { id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
1699
- ];
1700
- });
1701
- this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
1702
- const user = d.user(query.get("id") ?? "");
1703
- if (!user) return notFound("USER_INVALID", "No user has that id.");
1704
- if (typeof body.given_name === "string") user.givenName = body.given_name;
1705
- if (typeof body.family_name === "string") user.familyName = body.family_name;
1706
- if (typeof body.picture === "string") user.picture = body.picture;
1707
- const meta = d.meta(user);
1708
- if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
1709
- if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
1710
- if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
1711
- this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
1712
- return [
1713
- 200,
1714
- {
1715
- id: user.id,
1716
- given_name: user.givenName,
1717
- family_name: user.familyName,
1718
- email: user.email,
1719
- is_suspended: meta.isSuspended,
1720
- is_password_reset_requested: meta.isPasswordResetRequested,
1721
- picture: user.picture
1722
- }
1723
- ];
1724
- });
1725
- this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
1726
- const id = query.get("id") ?? "";
1727
- if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
1728
- this.webhooks.emit("user.deleted", { user: { id } });
1729
- return [200, OK];
1730
- });
1731
- this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
1732
- const page = paginate(d.seed.organizations, query);
1733
- return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
1734
- });
1735
- this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
1736
- const org = d.organization(query.get("code") ?? "");
1737
- if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1738
- const meta = d.orgInfo(org);
1739
- return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
1740
- });
1741
- this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
1742
- if (typeof body.name !== "string" || body.name.trim() === "") {
1743
- return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
1744
- }
1745
- const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
1746
- if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
1747
- this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
1748
- return [200, { ...OK, organization: { code: org.code } }];
1749
- });
1750
- this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
1751
- const org = d.organization(params.org_code);
1752
- if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1753
- const meta = d.orgInfo(org);
1754
- if (typeof body.name === "string") org.name = body.name;
1755
- if (typeof body.external_id === "string") meta.externalId = body.external_id;
1756
- if (typeof body.handle === "string") meta.handle = body.handle;
1757
- if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
1758
- this.webhooks.emit("organization.updated", {
1759
- organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
1760
- });
1761
- return [200, OK];
1762
- });
1763
- this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
1764
- if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1765
- this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
1766
- return [200, OK];
1767
- });
1768
- this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
1769
- if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1770
- const members = d.seed.memberships.filter((m) => m.organizationCode === params.org_code).map((m) => ({ membership: m, user: d.user(m.userId) })).filter((m) => m.user !== void 0);
1771
- const page = paginate(members, query);
1772
- return [
1773
- 200,
1774
- {
1775
- ...OK,
1776
- organization_users: page.items.map(({ membership, user }) => ({
1777
- id: user.id,
1778
- email: user.email,
1779
- full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
1780
- last_name: user.familyName,
1781
- first_name: user.givenName,
1782
- picture: user.picture,
1783
- joined_on: d.meta(user).createdOn,
1784
- last_accessed_on: d.meta(user).lastSignedIn,
1785
- is_suspended: d.meta(user).isSuspended,
1786
- roles: [...membership.roles]
1787
- })),
1788
- next_token: page.nextToken
1789
- }
1790
- ];
1791
- });
1792
- this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
1793
- if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
1794
- const users = Array.isArray(body.users) ? body.users : [];
1795
- const added = [];
1796
- const blocked = [];
1797
- for (const entry of users) {
1798
- const id = typeof entry.id === "string" ? entry.id : "";
1799
- if (!d.user(id)) {
1800
- blocked.push(id);
1801
- continue;
1802
- }
1803
- d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
1804
- added.push(id);
1805
- }
1806
- return [200, { ...OK, users_added: added, users_blocked: blocked }];
1807
- });
1808
- this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
1809
- return d.removeMembership(params.user_id, params.org_code) ? [200, OK] : notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1810
- });
1811
- this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
1812
- const membership = d.membership(params.user_id, params.org_code);
1813
- if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1814
- const roles = membership.roles.map((key) => d.ensureRole(key));
1815
- return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
1816
- });
1817
- this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
1818
- const membership = d.membership(params.user_id, params.org_code);
1819
- if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1820
- const role = d.role(str(body.role_id) ?? "");
1821
- if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1822
- if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
1823
- return [200, OK];
1824
- });
1825
- this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
1826
- const membership = d.membership(params.user_id, params.org_code);
1827
- const role = d.role(params.role_id);
1828
- if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
1829
- membership.roles = membership.roles.filter((key) => key !== role.key);
1830
- return [200, OK];
1831
- });
1832
- this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
1833
- const membership = d.membership(params.user_id, params.org_code);
1834
- if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1835
- const permissions = effectivePermissions(d.seed, membership).map((key) => {
1836
- const permission = d.ensurePermission(key);
1837
- const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
1838
- return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
1839
- });
1840
- return [200, { ...OK, permissions }];
1841
- });
1842
- this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
1843
- const membership = d.membership(params.user_id, params.org_code);
1844
- if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
1845
- const permission = d.permission(str(body.permission_id) ?? "");
1846
- if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
1847
- if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
1848
- return [200, OK];
1849
- });
1850
- this.route(
1851
- "DELETE",
1852
- "/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
1853
- "delete:organization_user_permissions",
1854
- ({ params }) => {
1855
- const membership = d.membership(params.user_id, params.org_code);
1856
- const permission = d.permission(params.permission_id);
1857
- if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
1858
- membership.permissions = membership.permissions.filter((key) => key !== permission.key);
1859
- return [200, OK];
1860
- }
1861
- );
1862
- this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
1863
- const page = paginate(d.seed.roles, query);
1864
- return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
1865
- });
1866
- this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
1867
- const key = str(body.key);
1868
- if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
1869
- if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
1870
- const role = d.ensureRole(key, {
1871
- name: str(body.name) ?? void 0,
1872
- description: str(body.description) ?? void 0,
1873
- isDefault: body.is_default_role === true
1874
- });
1875
- this.webhooks.emit("role.created", {
1876
- role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
1877
- });
1878
- return [201, { ...OK, role: { id: role.id } }];
1879
- });
1880
- this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
1881
- const role = d.role(params.role_id);
1882
- return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
1883
- });
1884
- this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
1885
- const role = d.deleteRole(params.role_id);
1886
- if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1887
- this.webhooks.emit("role.deleted", { role: { id: role.id } });
1888
- return [200, OK];
1889
- });
1890
- this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
1891
- const role = d.role(params.role_id);
1892
- if (!role) return notFound("ROLE_INVALID", "No role has that id.");
1893
- return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
1894
- });
1895
- this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
1896
- const page = paginate(d.seed.permissions, query);
1897
- return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
1898
- });
1899
- this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
1900
- const key = str(body.key);
1901
- if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
1902
- if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
1903
- const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
1904
- this.webhooks.emit("permission.created", {
1905
- permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
1906
- });
1907
- return [201, OK];
1908
- });
1909
- this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
1910
- const permission = d.deletePermission(params.permission_id);
1911
- if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
1912
- this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
1913
- return [200, OK];
1914
- });
1915
- }
1916
- userListItem(user) {
1917
- const meta = this.directory.meta(user);
1918
- return {
1919
- id: user.id,
1920
- provided_id: meta.providedId,
1921
- email: user.email,
1922
- phone: null,
1923
- username: null,
1924
- last_name: user.familyName,
1925
- first_name: user.givenName,
1926
- is_suspended: meta.isSuspended,
1927
- picture: user.picture,
1928
- total_sign_ins: meta.totalSignIns,
1929
- failed_sign_ins: 0,
1930
- last_signed_in: meta.lastSignedIn,
1931
- created_on: meta.createdOn,
1932
- organizations: this.organizationsOf(user),
1933
- identities: user.email ? [{ type: "email", identity: user.email }] : []
1934
- };
1935
- }
1936
- userDetail(user) {
1937
- const { email, ...rest } = this.userListItem(user);
1938
- return { ...rest, preferred_email: email };
1939
- }
1940
- organizationsOf(user) {
1941
- return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
1942
- }
1943
- organizationItem(org) {
1944
- const meta = this.directory.orgInfo(org);
1945
- return {
1946
- code: org.code,
1947
- name: org.name,
1948
- handle: meta.handle,
1949
- is_default: false,
1950
- external_id: meta.externalId,
1951
- is_auto_membership_enabled: false
1952
- };
1953
- }
1954
- organizationEvent(org) {
1955
- const meta = this.directory.orgInfo(org);
1956
- return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
1957
- }
1958
- roleItem(role) {
1959
- return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
1960
- }
1961
- permissionItem(permission) {
1962
- return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
1963
- }
1964
- };
1965
- function paginate(items, query) {
1966
- const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
1967
- const token = query.get("next_token");
1968
- const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
1969
- const page = items.slice(offset, offset + size);
1970
- const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
1971
- return { items: page, nextToken: next };
1972
- }
1973
- function errors2(code, message) {
1974
- return { errors: [{ code, message }] };
1975
- }
1976
- function notFound(code, message) {
1977
- return [404, errors2(code, message)];
1978
- }
1979
- function str(value) {
1980
- return typeof value === "string" ? value : null;
1981
- }
1982
- function strings(value) {
1983
- return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
1984
- }
1985
- function sendJson3(res, status, body) {
1986
- res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1987
- res.end(JSON.stringify(body));
1988
- }
1989
-
1990
- // src/failures.ts
1991
- var MAX_DELAY_MS = 6e4;
1992
- var FailureInjector = class {
1993
- rules = [];
1994
- nextId = 1;
1995
- add(rule) {
1996
- const problems = validate(rule);
1997
- if (problems.length > 0) {
1998
- throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
1999
- }
2000
- const active = {
2001
- id: `failure_${this.nextId++}`,
2002
- path: rule.path,
2003
- method: rule.method ? rule.method.toUpperCase() : null,
2004
- status: rule.status ?? null,
2005
- delayMs: rule.delayMs ?? 0,
2006
- hang: rule.hang ?? false,
2007
- remaining: rule.times ?? null,
2008
- retryAfter: rule.retryAfter ?? 1,
2009
- hits: 0
2010
- };
2011
- this.rules.push(active);
2012
- return { ...active };
2013
- }
2014
- remove(id) {
2015
- const before = this.rules.length;
2016
- this.rules = this.rules.filter((rule) => rule.id !== id);
2017
- return this.rules.length < before;
2018
- }
2019
- clear() {
2020
- this.rules = [];
2021
- }
2022
- list() {
2023
- return this.rules.map((rule) => ({ ...rule }));
2024
- }
2025
- take(method, path) {
2026
- const rule = this.rules.find((r) => matches(r, method, path));
2027
- if (!rule) return null;
2028
- rule.hits += 1;
2029
- if (rule.remaining !== null) {
2030
- rule.remaining -= 1;
2031
- if (rule.remaining <= 0) this.remove(rule.id);
2032
- }
2033
- return { ...rule };
2034
- }
2035
- };
2036
- function failureBody(status) {
2037
- const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
2038
- return { error, error_description: `kinde-testkit injected a ${status} response.` };
2039
- }
2040
- function matches(rule, method, path) {
2041
- if (rule.method && rule.method !== method.toUpperCase()) return false;
2042
- if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
2043
- return rule.path === path;
2044
- }
2045
- function validate(rule) {
2046
- const problems = [];
2047
- if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
2048
- problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
2049
- } else if (rule.path.startsWith("/testkit/")) {
2050
- problems.push("Failures cannot target /testkit/ control endpoints.");
2051
- }
2052
- if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
2053
- problems.push('"status" must be an HTTP error status between 400 and 599.');
2054
- }
2055
- if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
2056
- problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
2057
- }
2058
- if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
2059
- problems.push('"times" must be a whole number of 1 or more.');
2060
- }
2061
- if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
2062
- problems.push('"retryAfter" must be a whole number of seconds.');
2063
- }
2064
- if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
2065
- problems.push('Set at least one of "status", "delayMs" or "hang".');
2066
- }
2067
- return problems;
2068
- }
2069
-
2070
- // src/webhooks.ts
2071
- import { randomBytes as randomBytes4 } from "crypto";
2072
- var WEBHOOK_EVENT_TYPES = [
2073
- "user.created",
2074
- "user.updated",
2075
- "user.deleted",
2076
- "user.authenticated",
2077
- "user.authentication_failed",
2078
- "organization.created",
2079
- "organization.updated",
2080
- "organization.deleted",
2081
- "role.created",
2082
- "role.updated",
2083
- "role.deleted",
2084
- "permission.created",
2085
- "permission.updated",
2086
- "permission.deleted",
2087
- "subscriber.created",
2088
- "access_request.created"
2089
- ];
2090
- var BILLING_EVENT_TYPES = [
2091
- "customer.agreement_cancelled",
2092
- "customer.agreement_created",
2093
- "customer.invoice_overdue",
2094
- "customer.meter_usage_updated",
2095
- "customer.payment_failed",
2096
- "customer.payment_succeeded",
2097
- "customer.plan_assigned",
2098
- "customer.plan_changed"
2099
- ];
2100
- var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
2101
- var DEFAULT_TIMEOUT_MS = 5e3;
2102
- var MAX_DUPLICATES = 10;
2103
- var WebhookDispatcher = class {
2104
- constructor(testkit, seed, endpoints = [], options = {}) {
2105
- this.testkit = testkit;
2106
- this.seed = seed;
2107
- this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
2108
- this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2109
- for (const endpoint of endpoints) this.addEndpoint(endpoint);
2110
- this.seededEndpoints = [...this.endpoints];
2111
- }
2112
- testkit;
2113
- seed;
2114
- endpoints = [];
2115
- seededEndpoints = [];
2116
- log = [];
2117
- nextEndpoint = 1;
2118
- retryDelaysMs;
2119
- timeoutMs;
2120
- addEndpoint(input) {
2121
- if (!isHttpUrl2(input.url)) {
2122
- throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
2123
- }
2124
- if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
2125
- throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
2126
- }
2127
- const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
2128
- this.endpoints.push(endpoint);
2129
- return { ...endpoint };
2130
- }
2131
- removeEndpoint(id) {
2132
- const before = this.endpoints.length;
2133
- this.endpoints = this.endpoints.filter((e) => e.id !== id);
2134
- return this.endpoints.length < before;
2135
- }
2136
- listEndpoints() {
2137
- return this.endpoints.map((e) => ({ ...e }));
2138
- }
2139
- deliveries() {
2140
- return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
2141
- }
2142
- reset() {
2143
- this.log = [];
2144
- this.endpoints = [...this.seededEndpoints];
2145
- }
2146
- buildEvent(options) {
2147
- if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
2148
- throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
2149
- }
2150
- const now = /* @__PURE__ */ new Date();
2151
- const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
2152
- const event = {
2153
- data: options.data ?? this.buildData(options),
2154
- event_id: `event_${randomBytes4(16).toString("hex")}`,
2155
- event_timestamp: timestamp,
2156
- source: options.source ?? "admin",
2157
- timestamp,
2158
- type: options.type
2159
- };
2160
- if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
2161
- event.ip_address = options.ipAddress ?? "127.0.0.1";
2162
- }
2163
- return event;
2164
- }
2165
- async send(options) {
2166
- const event = this.buildEvent(options);
2167
- const copies = options.duplicate ?? 1;
2168
- if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
2169
- throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
2170
- }
2171
- const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
2172
- if (options.to && !isHttpUrl2(options.to)) {
2173
- throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
2174
- }
2175
- if (targets.length === 0) {
2176
- throw new TestkitError(
2177
- "INVALID_REQUEST",
2178
- `No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
2179
- );
2180
- }
2181
- if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
2182
- const signed = await this.testkit.signPayload(
2183
- event,
2184
- options.invalid === "stale" ? void 0 : options.invalid
2185
- );
2186
- const jobs = targets.flatMap((target) => {
2187
- const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
2188
- return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
2189
- });
2190
- return Promise.all(jobs);
2191
- }
2192
- async deliver(url, webhookId, body, event, copy) {
2193
- const delivery = {
2194
- webhookId,
2195
- eventId: String(event.event_id),
2196
- type: String(event.type),
2197
- url,
2198
- copy,
2199
- delivered: false,
2200
- attempts: [],
2201
- payload: event
2202
- };
2203
- this.log.push(delivery);
2204
- for (const [index, delay] of this.retryDelaysMs.entries()) {
2205
- if (delay > 0) await sleep(delay);
2206
- const started = Date.now();
2207
- try {
2208
- const response = await fetch(url, {
2209
- method: "POST",
2210
- headers: { "content-type": "application/jwt", "webhook-id": webhookId },
2211
- body,
2212
- signal: AbortSignal.timeout(this.timeoutMs)
2213
- });
2214
- await response.arrayBuffer().catch(() => void 0);
2215
- delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
2216
- if (response.status === 200) {
2217
- delivery.delivered = true;
2218
- break;
2219
- }
2220
- } catch (error) {
2221
- const name = error.name;
2222
- delivery.attempts.push({
2223
- attempt: index + 1,
2224
- status: null,
2225
- error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
2226
- durationMs: Date.now() - started
2227
- });
2228
- }
2229
- }
2230
- return { ...delivery, attempts: [...delivery.attempts] };
2231
- }
2232
- buildData(options) {
2233
- const [subject] = options.type.split(".");
2234
- switch (subject) {
2235
- case "user":
2236
- return { user: this.userData(options) };
2237
- case "organization":
2238
- return { organization: this.organizationData(options) };
2239
- case "role":
2240
- return { role: this.namedData(options, "role") };
2241
- case "permission":
2242
- return { permission: this.namedData(options, "permission") };
2243
- case "subscriber": {
2244
- const user = this.requireUser(options);
2245
- return {
2246
- subscriber: {
2247
- email: user.email,
2248
- first_name: user.givenName,
2249
- id: stableId("sub", user.id),
2250
- last_name: user.familyName,
2251
- user_id: user.id
2252
- }
2253
- };
2254
- }
2255
- case "access_request": {
2256
- const user = this.requireUser(options);
2257
- return {
2258
- access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
2259
- };
2260
- }
2261
- default:
2262
- throw new TestkitError(
2263
- "INVALID_REQUEST",
2264
- `kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
2265
- );
2266
- }
2267
- }
2268
- emit(type, data, source = "api") {
2269
- if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
2270
- void this.send({ type, data, source }).catch(() => void 0);
2271
- }
2272
- userEventData(user) {
2273
- return this.userPayload(user);
2274
- }
2275
- emitForUser(type, user) {
2276
- if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
2277
- const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
2278
- void this.send({ type, data, source: "user" }).catch(() => void 0);
2279
- }
2280
- userData(options) {
2281
- const user = this.requireUser(options);
2282
- if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
2283
- return this.userPayload(user);
2284
- }
2285
- userPayload(user) {
2286
- return {
2287
- email: user.email,
2288
- first_name: user.givenName,
2289
- id: user.id,
2290
- is_password_reset_requested: false,
2291
- is_suspended: false,
2292
- last_name: user.familyName,
2293
- organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
2294
- code: m.organizationCode,
2295
- permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
2296
- roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
2297
- })),
2298
- phone: null,
2299
- username: typeof user.claims.username === "string" ? user.claims.username : null
2300
- };
2301
- }
2302
- organizationData(options) {
2303
- if (!options.organization) {
2304
- throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
2305
- }
2306
- const org = this.seed.organizations.find((o) => o.code === options.organization);
2307
- if (options.type === "organization.deleted") return { code: options.organization };
2308
- const name = org?.name ?? titleCase(options.organization);
2309
- const data = { code: options.organization, external_id: null, handle: slug(name), name };
2310
- if (options.type === "organization.updated") data.is_allow_registrations = false;
2311
- return data;
2312
- }
2313
- namedData(options, kind) {
2314
- const key = kind === "role" ? options.role : options.permission;
2315
- if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
2316
- const id = stableId(kind === "role" ? "role" : "perm", key);
2317
- if (options.type.endsWith(".deleted")) return { id };
2318
- const data = { description: "", id, key, name: titleCase(key) };
2319
- if (kind === "role") data.is_default_role = false;
2320
- return data;
2321
- }
2322
- requireUser(options) {
2323
- if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
2324
- const user = findUser(this.seed.users, options.user);
2325
- if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
2326
- return user;
2327
- }
2328
- };
2329
- function isHttpUrl2(value) {
2330
- if (typeof value !== "string") return false;
2331
- try {
2332
- const { protocol } = new URL(value);
2333
- return protocol === "http:" || protocol === "https:";
2334
- } catch {
2335
- return false;
2336
- }
2337
- }
2338
- function sleep(ms) {
2339
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2340
- }
2341
-
2342
- // src/server.ts
2343
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
2344
- var MAX_BODY_BYTES = 64 * 1024;
2345
- var JWKS_PATHS = /* @__PURE__ */ new Set(["/.well-known/jwks", "/.well-known/jwks.json"]);
2346
- async function startKindeTestkit(options = {}) {
2347
- const host = options.host ?? "127.0.0.1";
2348
- if (!LOOPBACK_HOSTS.has(host) && !options.allowPublic) {
2349
- throw new TestkitError(
2350
- "PUBLIC_BIND_REFUSED",
2351
- `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).`
2352
- );
2353
- }
2354
- const seed = resolveSeed(options.seed ?? {});
2355
- const failures = new FailureInjector();
2356
- let ready;
2357
- const testkitReady = new Promise((resolve2) => ready = resolve2);
2358
- const listener = (req, res) => {
2359
- testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
2360
- };
2361
- const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
2362
- const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
2363
- await new Promise((resolve2, reject) => {
2364
- server.once("error", reject);
2365
- server.listen(options.port ?? 4400, host, () => resolve2());
2366
- });
2367
- const { port } = server.address();
2368
- const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
2369
- const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
2370
- const testkit = await KindeTestkit.create({
2371
- issuer: options.issuer ?? options.seed?.issuer ?? url,
2372
- audience: options.audience ?? options.seed?.audience,
2373
- clientId: options.clientId ?? options.seed?.clientId
2374
- });
2375
- const directory = new Directory(seed);
2376
- const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
2377
- const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
2378
- const management = new ManagementApi(testkit, directory, webhooks);
2379
- const account = new AccountApi(testkit, directory);
2380
- const reset = () => {
2381
- auth.reset();
2382
- failures.clear();
2383
- webhooks.reset();
2384
- directory.restore();
2385
- };
2386
- ready({ testkit, auth, seed, failures, webhooks, management, account, reset });
2387
- return {
2388
- url,
2389
- issuer: testkit.issuer,
2390
- discoveryUrl: `${url}/.well-known/openid-configuration`,
2391
- jwksUri: `${url}/.well-known/jwks`,
2392
- testkit,
2393
- seed,
2394
- failures,
2395
- webhooks,
2396
- directory,
2397
- certificatePath: certificate?.certPath ?? null,
2398
- reset,
2399
- close: () => new Promise((resolve2, reject) => {
2400
- server.closeAllConnections();
2401
- server.close((error) => error ? reject(error) : resolve2());
2402
- })
2403
- };
2404
- }
2405
- async function handle(req, res, context) {
2406
- const { testkit, auth, seed, failures, webhooks } = context;
2407
- const url = new URL(req.url ?? "/", "http://localhost");
2408
- const { pathname } = url;
2409
- const method = req.method ?? "GET";
2410
- if (!pathname.startsWith("/testkit/")) {
2411
- const failure = failures.take(method, pathname);
2412
- if (failure) {
2413
- if (failure.hang) return;
2414
- if (failure.delayMs > 0) await new Promise((resolve2) => setTimeout(resolve2, failure.delayMs));
2415
- if (failure.status !== null) {
2416
- const headers = {};
2417
- if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
2418
- return sendJson4(res, failure.status, failureBody(failure.status), headers);
2419
- }
2420
- }
2421
- }
2422
- if (await auth.handle(req, res, url, () => readForm(req))) return;
2423
- if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
2424
- if (await context.account.handle(req, res, url)) return;
2425
- if (method === "GET" && pathname === "/testkit/portal") {
2426
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2427
- res.end(
2428
- `<!doctype html><meta charset="utf-8"><title>Self-serve portal</title><body style="font:15px system-ui;padding:40px"><h1>Self-serve portal</h1><p>kinde-testkit does not emulate Kinde's self-serve portal. Your app linked here for <code>${escapeHtml(url.searchParams.get("subnav") ?? "profile")}</code>.</p>`
2429
- );
2430
- return;
2431
- }
2432
- if (method === "GET" && pathname === "/.well-known/openid-configuration") {
2433
- return sendJson4(res, 200, discovery(testkit));
2434
- }
2435
- if (method === "GET" && JWKS_PATHS.has(pathname)) {
2436
- return sendJson4(res, 200, testkit.jwks());
2437
- }
2438
- if (method === "GET" && pathname === "/testkit/health") {
2439
- return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
2440
- }
2441
- if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
2442
- if (method === "GET" && pathname === "/testkit/organizations") {
2443
- return sendJson4(res, 200, seed.organizations);
2444
- }
2445
- if (method === "GET" && pathname === "/testkit/memberships") {
2446
- return sendJson4(res, 200, seed.memberships);
2447
- }
2448
- if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
2449
- if (method === "POST" && pathname === "/testkit/failures") {
2450
- return sendJson4(res, 201, failures.add(await readJson(req)));
2451
- }
2452
- if (method === "DELETE" && pathname === "/testkit/failures") {
2453
- failures.clear();
2454
- return sendJson4(res, 200, { ok: true });
2455
- }
2456
- if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
2457
- const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
2458
- return sendJson4(res, removed ? 200 : 404, { ok: removed });
2459
- }
2460
- if (method === "POST" && pathname === "/testkit/webhooks") {
2461
- return sendJson4(res, 200, await webhooks.send(await readJson(req)));
2462
- }
2463
- if (method === "GET" && pathname === "/testkit/webhooks/types") {
2464
- return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
2465
- }
2466
- if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
2467
- if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
2468
- if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
2469
- return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
2470
- }
2471
- if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
2472
- const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
2473
- return sendJson4(res, removed ? 200 : 404, { ok: removed });
2474
- }
2475
- if (method === "POST" && pathname === "/testkit/reset") {
2476
- context.reset();
2477
- return sendJson4(res, 200, { ok: true });
2478
- }
2479
- if (method === "POST" && pathname === "/testkit/token") {
2480
- const body = await readJson(req);
2481
- const accessToken = await issueToken(testkit, seed, body);
2482
- return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
2483
- }
2484
- return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
2485
- }
2486
- function discovery(testkit) {
2487
- const base = testkit.issuer;
2488
- return {
2489
- issuer: base,
2490
- authorization_endpoint: `${base}/oauth2/auth`,
2491
- token_endpoint: `${base}/oauth2/token`,
2492
- userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
2493
- end_session_endpoint: `${base}/logout`,
2494
- revocation_endpoint: `${base}/oauth2/revoke`,
2495
- jwks_uri: `${base}/.well-known/jwks`,
2496
- response_types_supported: ["code"],
2497
- grant_types_supported: ["authorization_code", "refresh_token"],
2498
- code_challenge_methods_supported: ["S256", "plain"],
2499
- subject_types_supported: ["public"],
2500
- id_token_signing_alg_values_supported: ["RS256"],
2501
- scopes_supported: ["openid", "profile", "email", "offline"],
2502
- token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic", "none"],
2503
- claims_supported: ["aud", "exp", "iat", "iss", "sub", "org_code", "permissions", "roles", "scp"]
2504
- };
2505
- }
2506
- async function issueToken(testkit, seed, body) {
2507
- if (typeof body !== "object" || body === null || Array.isArray(body)) {
2508
- throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
2509
- }
2510
- const input = body;
2511
- const invalid2 = optionalString(input, "invalid");
2512
- if (invalid2 !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid2)) {
2513
- throw new TestkitError("INVALID_REQUEST", `"${invalid2}" is not a known invalid token kind.`, [
2514
- `Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
2515
- ]);
2516
- }
2517
- const expiresIn = input.expiresIn;
2518
- if (input.m2m === true) {
2519
- const clientId = optionalString(input, "clientId");
2520
- const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
2521
- const scopes = optionalStrings(input, "scopes") ?? [];
2522
- return testkit.m2mToken({
2523
- clientId,
2524
- organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
2525
- scopes,
2526
- grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
2527
- audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
2528
- permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
2529
- expiresIn,
2530
- invalid: invalid2
2531
- });
2532
- }
2533
- const permissions = optionalStrings(input, "permissions");
2534
- const roles = optionalStrings(input, "roles");
2535
- const userRef = optionalString(input, "user");
2536
- if (userRef) {
2537
- const scenario = seedScenario(seed, {
2538
- user: userRef,
2539
- organization: optionalString(input, "organization") ?? null
2540
- });
2541
- if (permissions) scenario.permissions = permissions;
2542
- if (roles) scenario.roles = roles;
2543
- return await testkit.tokenFor(scenario, {
2544
- expiresIn,
2545
- invalid: invalid2,
2546
- featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
2547
- });
2548
- }
2549
- const options = {
2550
- subject: optionalString(input, "subject"),
2551
- organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? null,
2552
- permissions,
2553
- roles,
2554
- scopes: optionalStrings(input, "scopes"),
2555
- expiresIn,
2556
- invalid: invalid2
2557
- };
2558
- if (typeof input.claims === "object" && input.claims !== null) {
2559
- options.claims = input.claims;
2560
- }
2561
- return testkit.token(options);
2562
- }
2563
- function optionalString(input, field) {
2564
- const value = input[field];
2565
- if (value === void 0 || value === null) return void 0;
2566
- if (typeof value !== "string") {
2567
- throw new TestkitError("INVALID_REQUEST", `"${field}" must be a string.`);
2568
- }
2569
- return value;
2570
- }
2571
- function optionalStrings(input, field) {
2572
- const value = input[field];
2573
- if (value === void 0) return void 0;
2574
- if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
2575
- throw new TestkitError("INVALID_REQUEST", `"${field}" must be a list of strings.`);
2576
- }
2577
- return value;
2578
- }
2579
- async function readForm(req) {
2580
- const text = await readText(req);
2581
- if ((req.headers["content-type"] ?? "").includes("application/json")) {
2582
- try {
2583
- const parsed = JSON.parse(text || "{}");
2584
- return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));
2585
- } catch {
2586
- throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
2587
- }
2588
- }
2589
- return Object.fromEntries(new URLSearchParams(text));
2590
- }
2591
- async function readJson(req) {
2592
- const text = await readText(req);
2593
- if (text.length === 0) return {};
2594
- try {
2595
- return JSON.parse(text);
2596
- } catch {
2597
- throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
2598
- }
2599
- }
2600
- async function readText(req) {
2601
- const chunks = [];
2602
- let size = 0;
2603
- for await (const chunk of req) {
2604
- size += chunk.length;
2605
- if (size > MAX_BODY_BYTES) {
2606
- throw new TestkitError("INVALID_REQUEST", "The request body is larger than 64 KB.");
2607
- }
2608
- chunks.push(chunk);
2609
- }
2610
- return Buffer.concat(chunks).toString("utf8").trim();
2611
- }
2612
- function sendJson4(res, status, body, headers = {}) {
2613
- res.writeHead(status, {
2614
- "content-type": "application/json; charset=utf-8",
2615
- "cache-control": "no-store",
2616
- ...headers
2617
- });
2618
- res.end(JSON.stringify(body));
2619
- }
2620
- function sendError(res, error) {
2621
- if (res.headersSent) {
2622
- res.end();
2623
- return;
2624
- }
2625
- if (error instanceof TestkitError) {
2626
- sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
2627
- return;
2628
- }
2629
- sendJson4(res, 500, {
2630
- error: "server_error",
2631
- error_description: error instanceof Error ? error.message : String(error)
2632
- });
2633
- }
2
+ createKindeTestkitHandle,
3
+ kindeTest
4
+ } from "./chunk-U2D47SCY.js";
5
+ import "./chunk-GCOZVCZY.js";
2634
6
 
2635
7
  // src/vitest.ts
2636
- async function kindeTest(options) {
2637
- const testkit = options.testkit ?? await getDefaultTestkit();
2638
- const token = await testkit.tokenFor(options.scenario, options.token);
2639
- const headers = token ? { authorization: `Bearer ${token}` } : {};
2640
- return {
2641
- token,
2642
- headers,
2643
- principal: testkit.principalFor(options.scenario),
2644
- request: { headers }
2645
- };
2646
- }
8
+ import { afterAll, beforeAll } from "vitest";
2647
9
  function useKindeTestkit(options = {}) {
2648
- let running = null;
2649
- beforeAll(async () => {
2650
- running = await startKindeTestkit({ port: 0, ...options });
2651
- });
2652
- afterAll(async () => {
2653
- await running?.close();
2654
- running = null;
2655
- });
2656
- const current = () => {
2657
- if (!running) throw new Error("useKindeTestkit() is only ready inside tests and hooks, after beforeAll runs.");
2658
- return running;
2659
- };
2660
- return {
2661
- get url() {
2662
- return current().url;
2663
- },
2664
- get issuer() {
2665
- return current().issuer;
2666
- },
2667
- get jwksUri() {
2668
- return current().jwksUri;
2669
- },
2670
- get testkit() {
2671
- return current().testkit;
2672
- },
2673
- get failures() {
2674
- return current().failures;
2675
- },
2676
- get webhooks() {
2677
- return current().webhooks;
2678
- },
2679
- auth: (scenario, token) => kindeTest({ scenario, testkit: current().testkit, token }),
2680
- reset: () => current().reset()
2681
- };
10
+ return createKindeTestkitHandle({ beforeAll, afterAll }, options, "useKindeTestkit");
2682
11
  }
2683
12
  export {
2684
13
  kindeTest,