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/CHANGELOG.md +18 -0
- package/README.md +242 -12
- package/dist/chunk-33AHOLUN.js +183 -0
- package/dist/chunk-33AHOLUN.js.map +1 -0
- package/dist/chunk-GCOZVCZY.js +3430 -0
- package/dist/chunk-GCOZVCZY.js.map +1 -0
- package/dist/chunk-U2D47SCY.js +72 -0
- package/dist/chunk-U2D47SCY.js.map +1 -0
- package/dist/cli.js +178 -2849
- package/dist/cli.js.map +1 -0
- package/dist/cypress-support.js +119 -0
- package/dist/cypress-support.js.map +1 -0
- package/dist/cypress.cjs +4251 -0
- package/dist/cypress.d.cts +24 -0
- package/dist/cypress.d.ts +25 -0
- package/dist/cypress.js +23 -0
- package/dist/cypress.js.map +1 -0
- package/dist/handle-BERQZCyH.d.cts +32 -0
- package/dist/handle-Dh0UpIzG.d.ts +33 -0
- package/dist/index.cjs +2046 -101
- package/dist/index.d.cts +38 -463
- package/dist/index.d.ts +39 -463
- package/dist/index.js +90 -2822
- package/dist/index.js.map +1 -1
- package/dist/jest.cjs +4320 -0
- package/dist/jest.d.cts +17 -0
- package/dist/jest.d.ts +18 -0
- package/dist/jest.js +23 -0
- package/dist/jest.js.map +1 -0
- package/dist/playwright.d.ts +2 -54
- package/dist/server-BiODgeoB.d.ts +185 -0
- package/dist/server-ciWIscoQ.d.cts +579 -0
- package/dist/vitest.d.ts +7 -403
- package/dist/vitest.js +6 -2677
- package/dist/vitest.js.map +1 -1
- package/dist/webhooks-DJyCsbdF.d.ts +397 -0
- package/package.json +36 -4
- package/dist/index.cjs.map +0 -1
|
@@ -0,0 +1,3430 @@
|
|
|
1
|
+
// src/ids.ts
|
|
2
|
+
import { createHash } from "crypto";
|
|
3
|
+
var counters = /* @__PURE__ */ new Map();
|
|
4
|
+
function stableId(prefix, seed) {
|
|
5
|
+
return `${prefix}_${createHash("sha256").update(seed).digest("hex").slice(0, 16)}`;
|
|
6
|
+
}
|
|
7
|
+
function nextSequence(prefix) {
|
|
8
|
+
const next = (counters.get(prefix) ?? 0) + 1;
|
|
9
|
+
counters.set(prefix, next);
|
|
10
|
+
return next;
|
|
11
|
+
}
|
|
12
|
+
function resetSequences() {
|
|
13
|
+
counters.clear();
|
|
14
|
+
}
|
|
15
|
+
function slug(value) {
|
|
16
|
+
return value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
17
|
+
}
|
|
18
|
+
function titleCase(value) {
|
|
19
|
+
return value.replace(/^org_/, "").split(/[_\-\s]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/factories.ts
|
|
23
|
+
function createKindeUser(options = {}) {
|
|
24
|
+
const email = options.email === void 0 ? `user-${nextSequence("user")}@example.test` : options.email;
|
|
25
|
+
const id = options.id ?? (email ? stableId("kp", email) : `kp_test_${nextSequence("kp")}`);
|
|
26
|
+
return {
|
|
27
|
+
id,
|
|
28
|
+
email,
|
|
29
|
+
emailVerified: options.emailVerified ?? email !== null,
|
|
30
|
+
givenName: options.givenName === void 0 ? null : options.givenName,
|
|
31
|
+
familyName: options.familyName === void 0 ? null : options.familyName,
|
|
32
|
+
picture: options.picture === void 0 ? null : options.picture,
|
|
33
|
+
claims: { ...options.claims ?? {} }
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function createKindeOrganization(options = {}) {
|
|
37
|
+
const code = options.code ?? (options.name ? `org_${slug(options.name)}` : `org_test_${nextSequence("org")}`);
|
|
38
|
+
return {
|
|
39
|
+
code,
|
|
40
|
+
name: options.name ?? titleCase(code),
|
|
41
|
+
metadata: { ...options.metadata ?? {} }
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function createMembership(options) {
|
|
45
|
+
return {
|
|
46
|
+
userId: options.userId,
|
|
47
|
+
organizationCode: options.organizationCode,
|
|
48
|
+
roles: unique(options.roles ?? []),
|
|
49
|
+
permissions: unique(options.permissions ?? [])
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function toKindeRole(role) {
|
|
53
|
+
if (typeof role !== "string") return role;
|
|
54
|
+
return { id: stableId("role", role), key: role, name: titleCase(role) };
|
|
55
|
+
}
|
|
56
|
+
function resetFactories() {
|
|
57
|
+
resetSequences();
|
|
58
|
+
}
|
|
59
|
+
function unique(values) {
|
|
60
|
+
return [...new Set(values)];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/errors.ts
|
|
64
|
+
var TestkitError = class extends Error {
|
|
65
|
+
code;
|
|
66
|
+
details;
|
|
67
|
+
/** The message without the details list. */
|
|
68
|
+
summary;
|
|
69
|
+
constructor(code, message, details = []) {
|
|
70
|
+
super(details.length > 0 ? `${message}
|
|
71
|
+
|
|
72
|
+
${details.map((d) => ` - ${d}`).join("\n")}` : message);
|
|
73
|
+
this.name = "TestkitError";
|
|
74
|
+
this.code = code;
|
|
75
|
+
this.details = details;
|
|
76
|
+
this.summary = message;
|
|
77
|
+
}
|
|
78
|
+
toString() {
|
|
79
|
+
return `${this.code}
|
|
80
|
+
|
|
81
|
+
${this.message}`;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// src/testkit.ts
|
|
86
|
+
import { randomUUID } from "crypto";
|
|
87
|
+
import {
|
|
88
|
+
SignJWT,
|
|
89
|
+
base64url,
|
|
90
|
+
calculateJwkThumbprint,
|
|
91
|
+
exportJWK,
|
|
92
|
+
generateKeyPair,
|
|
93
|
+
jwtVerify
|
|
94
|
+
} from "jose";
|
|
95
|
+
|
|
96
|
+
// src/duration.ts
|
|
97
|
+
var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
|
|
98
|
+
function toSeconds(value) {
|
|
99
|
+
if (typeof value === "number") {
|
|
100
|
+
if (!Number.isFinite(value) || value < 0) throw invalid(String(value));
|
|
101
|
+
return Math.floor(value);
|
|
102
|
+
}
|
|
103
|
+
const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
|
|
104
|
+
if (!match) {
|
|
105
|
+
if (/^\d+$/.test(value.trim())) return Number(value.trim());
|
|
106
|
+
throw invalid(value);
|
|
107
|
+
}
|
|
108
|
+
return Number(match[1]) * UNITS[match[2]];
|
|
109
|
+
}
|
|
110
|
+
function invalid(value) {
|
|
111
|
+
return new TestkitError(
|
|
112
|
+
"INVALID_DURATION",
|
|
113
|
+
`"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// src/testkit.ts
|
|
118
|
+
var DEFAULT_ISSUER = "http://localhost:4400";
|
|
119
|
+
var DEFAULT_CLIENT_ID = "kinde_testkit_client";
|
|
120
|
+
var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
|
|
121
|
+
var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
|
|
122
|
+
var DEFAULT_AUTH_METHODS = ["email"];
|
|
123
|
+
var INVALID_TOKEN_KINDS = [
|
|
124
|
+
"expired",
|
|
125
|
+
"wrong-issuer",
|
|
126
|
+
"wrong-audience",
|
|
127
|
+
"missing-subject",
|
|
128
|
+
"missing-organization",
|
|
129
|
+
"missing-permissions",
|
|
130
|
+
"future-iat",
|
|
131
|
+
"bad-signature",
|
|
132
|
+
"unknown-key",
|
|
133
|
+
"unsigned"
|
|
134
|
+
];
|
|
135
|
+
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
136
|
+
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
137
|
+
var KindeTestkit = class _KindeTestkit {
|
|
138
|
+
observers = [];
|
|
139
|
+
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
140
|
+
observe(observer) {
|
|
141
|
+
this.observers.push(observer);
|
|
142
|
+
return () => {
|
|
143
|
+
this.observers = this.observers.filter((o) => o !== observer);
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
async signAccess(payload, invalid2, now) {
|
|
147
|
+
const final = applyInvalidClaims(payload, invalid2, now);
|
|
148
|
+
const token = await this.sign(final, invalid2);
|
|
149
|
+
for (const observer of this.observers) observer.accessToken?.(final, invalid2, token);
|
|
150
|
+
return token;
|
|
151
|
+
}
|
|
152
|
+
issuer;
|
|
153
|
+
audience;
|
|
154
|
+
clientId;
|
|
155
|
+
accessTokenExpiresIn;
|
|
156
|
+
idTokenExpiresIn;
|
|
157
|
+
clock;
|
|
158
|
+
signingKey;
|
|
159
|
+
strangerKey = null;
|
|
160
|
+
static async create(options = {}) {
|
|
161
|
+
return new _KindeTestkit(options, await createSigningKey("kinde-testkit"));
|
|
162
|
+
}
|
|
163
|
+
constructor(options, signingKey) {
|
|
164
|
+
this.issuer = trimSlash(options.issuer ?? DEFAULT_ISSUER);
|
|
165
|
+
this.audience = toArray(options.audience);
|
|
166
|
+
this.clientId = options.clientId ?? DEFAULT_CLIENT_ID;
|
|
167
|
+
this.accessTokenExpiresIn = options.accessTokenExpiresIn ?? "24h";
|
|
168
|
+
this.idTokenExpiresIn = options.idTokenExpiresIn ?? "1h";
|
|
169
|
+
this.clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
170
|
+
this.signingKey = signingKey;
|
|
171
|
+
warnIfRealKindeDomain(this.issuer);
|
|
172
|
+
}
|
|
173
|
+
get jwksUri() {
|
|
174
|
+
return `${this.issuer}/.well-known/jwks`;
|
|
175
|
+
}
|
|
176
|
+
get keyId() {
|
|
177
|
+
return this.signingKey.kid;
|
|
178
|
+
}
|
|
179
|
+
get accessTokenLifetime() {
|
|
180
|
+
return toSeconds(this.accessTokenExpiresIn);
|
|
181
|
+
}
|
|
182
|
+
async verify(token) {
|
|
183
|
+
const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
|
|
184
|
+
issuer: this.issuer,
|
|
185
|
+
algorithms: ["RS256"]
|
|
186
|
+
});
|
|
187
|
+
return payload;
|
|
188
|
+
}
|
|
189
|
+
jwks() {
|
|
190
|
+
return { keys: [{ ...this.signingKey.publicJwk }] };
|
|
191
|
+
}
|
|
192
|
+
async token(options = {}) {
|
|
193
|
+
const now = this.clock();
|
|
194
|
+
const payload = {
|
|
195
|
+
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
196
|
+
aud: [...options.audience ?? this.audience],
|
|
197
|
+
auth_time: options.authTime ?? now,
|
|
198
|
+
azp: options.clientId ?? this.clientId,
|
|
199
|
+
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
200
|
+
iat: now,
|
|
201
|
+
iss: this.issuer,
|
|
202
|
+
jti: randomUUID(),
|
|
203
|
+
scp: [...options.scopes ?? DEFAULT_SCOPES],
|
|
204
|
+
sub: options.subject ?? stableId("kp", "default-test-user")
|
|
205
|
+
};
|
|
206
|
+
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
207
|
+
if (options.roles !== void 0) payload.roles = options.roles.map(toKindeRole);
|
|
208
|
+
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
209
|
+
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
210
|
+
Object.assign(payload, options.claims ?? {});
|
|
211
|
+
return this.signAccess(payload, options.invalid, now);
|
|
212
|
+
}
|
|
213
|
+
async m2mToken(options = {}) {
|
|
214
|
+
const now = this.clock();
|
|
215
|
+
const requested = [...options.scopes ?? []];
|
|
216
|
+
const granted = [...options.grantedScopes ?? requested];
|
|
217
|
+
const payload = {
|
|
218
|
+
aud: [...options.audience ?? this.audience],
|
|
219
|
+
azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
|
|
220
|
+
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
221
|
+
gty: ["client_credentials"],
|
|
222
|
+
iat: now,
|
|
223
|
+
iss: this.issuer,
|
|
224
|
+
jti: randomUUID(),
|
|
225
|
+
scope: granted.join(" "),
|
|
226
|
+
scp: requested,
|
|
227
|
+
v: "2"
|
|
228
|
+
};
|
|
229
|
+
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
230
|
+
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
231
|
+
Object.assign(payload, options.claims ?? {});
|
|
232
|
+
return this.signAccess(payload, options.invalid, now);
|
|
233
|
+
}
|
|
234
|
+
async tokenFor(scenario, overrides = {}) {
|
|
235
|
+
if (scenario.kind === "unauthenticated") {
|
|
236
|
+
for (const observer of this.observers) observer.anonymous?.();
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
return this.token({
|
|
240
|
+
subject: scenario.user.id,
|
|
241
|
+
organizationCode: scenario.organization?.code ?? null,
|
|
242
|
+
roles: scenario.roles.length > 0 ? scenario.roles : void 0,
|
|
243
|
+
permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
|
|
244
|
+
...overrides,
|
|
245
|
+
claims: { ...scenario.claims, ...overrides.claims ?? {} }
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
async idTokenFor(scenario, options = {}) {
|
|
249
|
+
if (scenario.kind === "unauthenticated") return null;
|
|
250
|
+
const { user, organization } = scenario;
|
|
251
|
+
const now = this.clock();
|
|
252
|
+
const authTime = options.authTime ?? now;
|
|
253
|
+
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
254
|
+
const clientId = options.clientId ?? this.clientId;
|
|
255
|
+
const payload = {
|
|
256
|
+
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
257
|
+
aud: [clientId],
|
|
258
|
+
auth_time: authTime,
|
|
259
|
+
azp: clientId,
|
|
260
|
+
email: user.email,
|
|
261
|
+
email_verified: user.emailVerified,
|
|
262
|
+
exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
|
|
263
|
+
family_name: user.familyName,
|
|
264
|
+
given_name: user.givenName,
|
|
265
|
+
iat: now,
|
|
266
|
+
iss: this.issuer,
|
|
267
|
+
jti: randomUUID(),
|
|
268
|
+
name: name || null,
|
|
269
|
+
nonce: options.nonce,
|
|
270
|
+
org_codes: organization ? [organization.code] : void 0,
|
|
271
|
+
picture: user.picture,
|
|
272
|
+
rat: authTime,
|
|
273
|
+
sub: user.id,
|
|
274
|
+
updated_at: now,
|
|
275
|
+
...user.claims
|
|
276
|
+
};
|
|
277
|
+
for (const key of Object.keys(payload)) {
|
|
278
|
+
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
279
|
+
}
|
|
280
|
+
const token = await this.sign(payload);
|
|
281
|
+
for (const observer of this.observers) observer.idToken?.(payload, token);
|
|
282
|
+
return token;
|
|
283
|
+
}
|
|
284
|
+
async headersFor(scenario, overrides = {}) {
|
|
285
|
+
const token = await this.tokenFor(scenario, overrides);
|
|
286
|
+
return token ? { authorization: `Bearer ${token}` } : {};
|
|
287
|
+
}
|
|
288
|
+
principalFor(scenario) {
|
|
289
|
+
if (scenario.kind === "unauthenticated") return null;
|
|
290
|
+
return scenarioPrincipal(scenario, this.issuer);
|
|
291
|
+
}
|
|
292
|
+
async signPayload(payload, invalid2) {
|
|
293
|
+
return this.sign(payload, invalid2);
|
|
294
|
+
}
|
|
295
|
+
async sign(payload, invalid2) {
|
|
296
|
+
if (invalid2 === "unsigned") {
|
|
297
|
+
const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
298
|
+
return `${header}.${base64url.encode(JSON.stringify(payload))}.`;
|
|
299
|
+
}
|
|
300
|
+
const key = invalid2 === "unknown-key" ? await this.stranger() : this.signingKey;
|
|
301
|
+
const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
|
|
302
|
+
return invalid2 === "bad-signature" ? tamperSignature(jwt) : jwt;
|
|
303
|
+
}
|
|
304
|
+
stranger() {
|
|
305
|
+
this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
|
|
306
|
+
return this.strangerKey;
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
function principalFromClaims(claims) {
|
|
310
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map(
|
|
311
|
+
(role) => typeof role === "string" ? role : String(role.key ?? "")
|
|
312
|
+
) : [];
|
|
313
|
+
const permissions = Array.isArray(claims.permissions) ? claims.permissions.map(String) : [];
|
|
314
|
+
const machine = Array.isArray(claims.gty) && claims.gty.includes("client_credentials");
|
|
315
|
+
return {
|
|
316
|
+
type: machine ? "machine" : "user",
|
|
317
|
+
subject: String((machine ? claims.azp : claims.sub) ?? ""),
|
|
318
|
+
issuer: String(claims.iss ?? ""),
|
|
319
|
+
organization: typeof claims.org_code === "string" ? { code: claims.org_code } : null,
|
|
320
|
+
roles: roles.filter(Boolean),
|
|
321
|
+
permissions,
|
|
322
|
+
claims: { ...claims }
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
function scenarioPrincipal(scenario, issuer) {
|
|
326
|
+
return {
|
|
327
|
+
type: "user",
|
|
328
|
+
subject: scenario.user.id,
|
|
329
|
+
issuer,
|
|
330
|
+
organization: scenario.organization ? { code: scenario.organization.code } : null,
|
|
331
|
+
roles: [...scenario.roles],
|
|
332
|
+
permissions: [...scenario.permissions],
|
|
333
|
+
claims: { ...scenario.claims }
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
function applyInvalidClaims(payload, invalid2, now) {
|
|
337
|
+
const next = { ...payload };
|
|
338
|
+
switch (invalid2) {
|
|
339
|
+
case "expired":
|
|
340
|
+
next.iat = now - 7200;
|
|
341
|
+
next.exp = now - 3600;
|
|
342
|
+
break;
|
|
343
|
+
case "future-iat":
|
|
344
|
+
next.iat = now + 3600;
|
|
345
|
+
next.exp = now + 7200;
|
|
346
|
+
break;
|
|
347
|
+
case "wrong-issuer":
|
|
348
|
+
next.iss = WRONG_ISSUER;
|
|
349
|
+
break;
|
|
350
|
+
case "wrong-audience":
|
|
351
|
+
next.aud = [WRONG_AUDIENCE];
|
|
352
|
+
break;
|
|
353
|
+
case "missing-subject":
|
|
354
|
+
delete next.sub;
|
|
355
|
+
break;
|
|
356
|
+
case "missing-organization":
|
|
357
|
+
delete next.org_code;
|
|
358
|
+
break;
|
|
359
|
+
case "missing-permissions":
|
|
360
|
+
next.permissions = [];
|
|
361
|
+
break;
|
|
362
|
+
default:
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
return next;
|
|
366
|
+
}
|
|
367
|
+
async function createSigningKey(prefix) {
|
|
368
|
+
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
|
369
|
+
const jwk = await exportJWK(publicKey);
|
|
370
|
+
const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
|
|
371
|
+
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
372
|
+
}
|
|
373
|
+
function tamperSignature(jwt) {
|
|
374
|
+
const [header, payload, signature] = jwt.split(".");
|
|
375
|
+
const bytes = base64url.decode(signature);
|
|
376
|
+
bytes[0] = (bytes[0] ?? 0) ^ 255;
|
|
377
|
+
return `${header}.${payload}.${base64url.encode(bytes)}`;
|
|
378
|
+
}
|
|
379
|
+
function toArray(value) {
|
|
380
|
+
if (value === void 0) return [];
|
|
381
|
+
return Array.isArray(value) ? [...value] : [value];
|
|
382
|
+
}
|
|
383
|
+
function trimSlash(value) {
|
|
384
|
+
return value.replace(/\/+$/, "");
|
|
385
|
+
}
|
|
386
|
+
function warnIfRealKindeDomain(issuer) {
|
|
387
|
+
if (/^https:\/\/[^/]+\.kinde\.com$/i.test(issuer)) {
|
|
388
|
+
process.emitWarning(
|
|
389
|
+
`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.`,
|
|
390
|
+
{ code: "KINDE_TESTKIT_REAL_ISSUER" }
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
var defaultTestkit = null;
|
|
395
|
+
function getDefaultTestkit() {
|
|
396
|
+
defaultTestkit ??= KindeTestkit.create({
|
|
397
|
+
issuer: process.env.KINDE_TESTKIT_ISSUER ?? DEFAULT_ISSUER,
|
|
398
|
+
audience: process.env.KINDE_TESTKIT_AUDIENCE?.split(",").filter(Boolean)
|
|
399
|
+
});
|
|
400
|
+
return defaultTestkit;
|
|
401
|
+
}
|
|
402
|
+
async function createKindeToken(options = {}) {
|
|
403
|
+
return (await getDefaultTestkit()).token(options);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// src/certificate.ts
|
|
407
|
+
import { createHash as createHash2, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
|
|
408
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
409
|
+
import { join, resolve } from "path";
|
|
410
|
+
var CERT_FILE = "localhost-cert.pem";
|
|
411
|
+
var KEY_FILE = "localhost-key.pem";
|
|
412
|
+
var VALID_DAYS = 825;
|
|
413
|
+
function ensureLocalCertificate(directory = ".kinde-testkit") {
|
|
414
|
+
const dir = resolve(directory);
|
|
415
|
+
const certPath = join(dir, CERT_FILE);
|
|
416
|
+
const keyPath = join(dir, KEY_FILE);
|
|
417
|
+
if (existsSync(certPath) && existsSync(keyPath)) {
|
|
418
|
+
const cert2 = readFileSync(certPath, "utf8");
|
|
419
|
+
const key2 = readFileSync(keyPath, "utf8");
|
|
420
|
+
try {
|
|
421
|
+
if (new Date(new X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
|
|
422
|
+
return { cert: cert2, key: key2, certPath, keyPath, created: false };
|
|
423
|
+
}
|
|
424
|
+
} catch {
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const { cert, key } = createLocalCertificate();
|
|
428
|
+
mkdirSync(dir, { recursive: true });
|
|
429
|
+
writeFileSync(certPath, cert);
|
|
430
|
+
writeFileSync(keyPath, key, { mode: 384 });
|
|
431
|
+
writeFileSync(join(dir, ".gitignore"), "*\n");
|
|
432
|
+
return { cert, key, certPath, keyPath, created: true };
|
|
433
|
+
}
|
|
434
|
+
function createLocalCertificate() {
|
|
435
|
+
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
436
|
+
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
437
|
+
const keyId = createHash2("sha1").update(subjectPublicKeyBits(spki)).digest();
|
|
438
|
+
const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
|
|
439
|
+
const now = Date.now();
|
|
440
|
+
const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
|
|
441
|
+
const serial = randomBytes(16);
|
|
442
|
+
serial[0] &= 127;
|
|
443
|
+
const extensions = seq(
|
|
444
|
+
seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
|
|
445
|
+
seq(oid("2.5.29.14"), octets(octets(keyId))),
|
|
446
|
+
seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
|
|
447
|
+
seq(
|
|
448
|
+
oid("2.5.29.17"),
|
|
449
|
+
octets(
|
|
450
|
+
seq(
|
|
451
|
+
tlv(130, Buffer.from("localhost")),
|
|
452
|
+
tlv(135, Buffer.from([127, 0, 0, 1])),
|
|
453
|
+
tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
|
|
454
|
+
)
|
|
455
|
+
)
|
|
456
|
+
)
|
|
457
|
+
);
|
|
458
|
+
const tbs = seq(
|
|
459
|
+
tlv(160, integer(Buffer.from([2]))),
|
|
460
|
+
integer(serial),
|
|
461
|
+
algorithm,
|
|
462
|
+
name,
|
|
463
|
+
seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
|
|
464
|
+
name,
|
|
465
|
+
spki,
|
|
466
|
+
tlv(163, extensions)
|
|
467
|
+
);
|
|
468
|
+
const signature = sign("sha256", tbs, privateKey);
|
|
469
|
+
const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
|
|
470
|
+
return {
|
|
471
|
+
cert: pem("CERTIFICATE", der),
|
|
472
|
+
key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
function subjectPublicKeyBits(spki) {
|
|
476
|
+
const outer = readTlv(spki, 0);
|
|
477
|
+
const algorithm = readTlv(spki, outer.start);
|
|
478
|
+
const bits = readTlv(spki, algorithm.end);
|
|
479
|
+
return spki.subarray(bits.start + 1, bits.end);
|
|
480
|
+
}
|
|
481
|
+
function readTlv(buf, offset) {
|
|
482
|
+
let len = buf[offset + 1];
|
|
483
|
+
let header = 2;
|
|
484
|
+
if (len & 128) {
|
|
485
|
+
const n = len & 127;
|
|
486
|
+
len = 0;
|
|
487
|
+
for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
|
|
488
|
+
header += n;
|
|
489
|
+
}
|
|
490
|
+
return { start: offset + header, end: offset + header + len };
|
|
491
|
+
}
|
|
492
|
+
function tlv(tag, content) {
|
|
493
|
+
return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
|
|
494
|
+
}
|
|
495
|
+
function length(n) {
|
|
496
|
+
if (n < 128) return Buffer.from([n]);
|
|
497
|
+
const bytes = [];
|
|
498
|
+
while (n > 0) {
|
|
499
|
+
bytes.unshift(n & 255);
|
|
500
|
+
n >>= 8;
|
|
501
|
+
}
|
|
502
|
+
return Buffer.from([128 | bytes.length, ...bytes]);
|
|
503
|
+
}
|
|
504
|
+
function seq(...items) {
|
|
505
|
+
return tlv(48, Buffer.concat(items));
|
|
506
|
+
}
|
|
507
|
+
function set(...items) {
|
|
508
|
+
return tlv(49, Buffer.concat(items));
|
|
509
|
+
}
|
|
510
|
+
function octets(content) {
|
|
511
|
+
return tlv(4, content);
|
|
512
|
+
}
|
|
513
|
+
function integer(bytes) {
|
|
514
|
+
return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
|
|
515
|
+
}
|
|
516
|
+
function oid(dotted) {
|
|
517
|
+
const parts = dotted.split(".").map(Number);
|
|
518
|
+
const bytes = [parts[0] * 40 + parts[1]];
|
|
519
|
+
for (const part of parts.slice(2)) {
|
|
520
|
+
const chunk = [part & 127];
|
|
521
|
+
let value = part >> 7;
|
|
522
|
+
while (value > 0) {
|
|
523
|
+
chunk.unshift(value & 127 | 128);
|
|
524
|
+
value >>= 7;
|
|
525
|
+
}
|
|
526
|
+
bytes.push(...chunk);
|
|
527
|
+
}
|
|
528
|
+
return tlv(6, Buffer.from(bytes));
|
|
529
|
+
}
|
|
530
|
+
function utcTime(date) {
|
|
531
|
+
const iso = date.toISOString();
|
|
532
|
+
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`;
|
|
533
|
+
return tlv(23, Buffer.from(value));
|
|
534
|
+
}
|
|
535
|
+
function pem(label, der) {
|
|
536
|
+
const body = der.toString("base64").match(/.{1,64}/g).join("\n");
|
|
537
|
+
return `-----BEGIN ${label}-----
|
|
538
|
+
${body}
|
|
539
|
+
-----END ${label}-----
|
|
540
|
+
`;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// src/seed.ts
|
|
544
|
+
function roleRecord(key, extra = {}) {
|
|
545
|
+
return {
|
|
546
|
+
id: stableId("role", key),
|
|
547
|
+
key,
|
|
548
|
+
name: extra.name ?? titleCase(key),
|
|
549
|
+
description: extra.description ?? null,
|
|
550
|
+
isDefault: extra.isDefault ?? false,
|
|
551
|
+
permissions: [...extra.permissions ?? []]
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
function permissionRecord(key, extra = {}) {
|
|
555
|
+
return {
|
|
556
|
+
id: stableId("perm", key),
|
|
557
|
+
key,
|
|
558
|
+
name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
|
|
559
|
+
description: extra.description ?? null
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
function effectivePermissions(seed, membership) {
|
|
563
|
+
if (!membership) return [];
|
|
564
|
+
const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
|
|
565
|
+
return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
|
|
566
|
+
}
|
|
567
|
+
function resolveSeed(input) {
|
|
568
|
+
const problems = [];
|
|
569
|
+
if (!isRecord(input)) {
|
|
570
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
571
|
+
}
|
|
572
|
+
const rawUsers = listOf(input.users, "users", problems);
|
|
573
|
+
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
574
|
+
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
575
|
+
const rawApplications = listOf(input.applications, "applications", problems);
|
|
576
|
+
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
577
|
+
const rawRoles = listOf(input.roles, "roles", problems);
|
|
578
|
+
const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
|
|
579
|
+
const rawPlans = listOf(input.plans, "plans", problems);
|
|
580
|
+
const rawPermissions = listOf(input.permissions, "permissions", problems);
|
|
581
|
+
const webhooks = [];
|
|
582
|
+
rawWebhooks.forEach((raw, index) => {
|
|
583
|
+
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
584
|
+
problems.push(`webhooks[${index}] needs an http or https "url".`);
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
|
|
588
|
+
problems.push(`webhooks[${index}].events must be a list of event type names.`);
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
webhooks.push({ url: raw.url, events: raw.events });
|
|
592
|
+
});
|
|
593
|
+
const users = [];
|
|
594
|
+
rawUsers.forEach((raw, index) => {
|
|
595
|
+
if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
|
|
596
|
+
problems.push(`users[${index}] needs a string "id".`);
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
if (users.some((user) => user.id === raw.id)) {
|
|
600
|
+
problems.push(`users[${index}] repeats the id "${raw.id}".`);
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
users.push(createKindeUser(raw));
|
|
604
|
+
});
|
|
605
|
+
const organizations = [];
|
|
606
|
+
rawOrganizations.forEach((raw, index) => {
|
|
607
|
+
if (!isRecord(raw) || typeof raw.code !== "string" || raw.code.length === 0) {
|
|
608
|
+
problems.push(`organizations[${index}] needs a string "code".`);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
if (organizations.some((org) => org.code === raw.code)) {
|
|
612
|
+
problems.push(`organizations[${index}] repeats the code "${raw.code}".`);
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
organizations.push(createKindeOrganization(raw));
|
|
616
|
+
});
|
|
617
|
+
const memberships = [];
|
|
618
|
+
rawMemberships.forEach((raw, index) => {
|
|
619
|
+
if (!isRecord(raw) || typeof raw.user !== "string" || typeof raw.organization !== "string") {
|
|
620
|
+
problems.push(`memberships[${index}] needs string "user" and "organization" fields.`);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const user = findUser(users, raw.user);
|
|
624
|
+
if (!user) problems.push(`memberships[${index}] points to an unknown user "${raw.user}".`);
|
|
625
|
+
if (!organizations.some((org) => org.code === raw.organization)) {
|
|
626
|
+
problems.push(`memberships[${index}] points to an unknown organization "${raw.organization}".`);
|
|
627
|
+
}
|
|
628
|
+
for (const field of ["roles", "permissions"]) {
|
|
629
|
+
const value = raw[field];
|
|
630
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
|
|
631
|
+
problems.push(`memberships[${index}].${field} must be a list of strings.`);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
if (!user) return;
|
|
635
|
+
if (memberships.some((m) => m.userId === user.id && m.organizationCode === raw.organization)) {
|
|
636
|
+
problems.push(`memberships[${index}] repeats ${user.id} in ${raw.organization}.`);
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
memberships.push(
|
|
640
|
+
createMembership({
|
|
641
|
+
userId: user.id,
|
|
642
|
+
organizationCode: raw.organization,
|
|
643
|
+
roles: raw.roles,
|
|
644
|
+
permissions: raw.permissions
|
|
645
|
+
})
|
|
646
|
+
);
|
|
647
|
+
});
|
|
648
|
+
const applications = [];
|
|
649
|
+
rawApplications.forEach((raw, index) => {
|
|
650
|
+
if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
|
|
651
|
+
problems.push(`applications[${index}] needs a string "clientId".`);
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
if (applications.some((app) => app.clientId === raw.clientId)) {
|
|
655
|
+
problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
|
|
659
|
+
problems.push(`applications[${index}].clientSecret must be a string.`);
|
|
660
|
+
}
|
|
661
|
+
if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
|
|
662
|
+
problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
|
|
663
|
+
}
|
|
664
|
+
for (const field of ["scopes", "permissions"]) {
|
|
665
|
+
const value = raw[field];
|
|
666
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
|
|
667
|
+
problems.push(`applications[${index}].${field} must be a list of strings.`);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
const audience = raw.audience;
|
|
671
|
+
applications.push({
|
|
672
|
+
clientId: raw.clientId,
|
|
673
|
+
clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
|
|
674
|
+
name: typeof raw.name === "string" ? raw.name : raw.clientId,
|
|
675
|
+
organizationCode: typeof raw.organization === "string" ? raw.organization : null,
|
|
676
|
+
scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
|
|
677
|
+
permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
|
|
678
|
+
audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
|
|
679
|
+
});
|
|
680
|
+
});
|
|
681
|
+
if (problems.length > 0) {
|
|
682
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
683
|
+
}
|
|
684
|
+
const permissions = [];
|
|
685
|
+
rawPermissions.forEach((raw, index) => {
|
|
686
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
687
|
+
problems.push(`permissions[${index}] needs a string "key".`);
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
if (permissions.some((p) => p.key === raw.key)) {
|
|
691
|
+
problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
permissions.push(
|
|
695
|
+
permissionRecord(raw.key, {
|
|
696
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
697
|
+
description: typeof raw.description === "string" ? raw.description : void 0
|
|
698
|
+
})
|
|
699
|
+
);
|
|
700
|
+
});
|
|
701
|
+
const roles = [];
|
|
702
|
+
rawRoles.forEach((raw, index) => {
|
|
703
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
704
|
+
problems.push(`roles[${index}] needs a string "key".`);
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
if (roles.some((r) => r.key === raw.key)) {
|
|
708
|
+
problems.push(`roles[${index}] repeats the key "${raw.key}".`);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
|
|
712
|
+
problems.push(`roles[${index}].permissions must be a list of permission keys.`);
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
roles.push(
|
|
716
|
+
roleRecord(raw.key, {
|
|
717
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
718
|
+
description: typeof raw.description === "string" ? raw.description : void 0,
|
|
719
|
+
isDefault: raw.isDefault === true,
|
|
720
|
+
permissions: raw.permissions ?? []
|
|
721
|
+
})
|
|
722
|
+
);
|
|
723
|
+
});
|
|
724
|
+
if (problems.length > 0) {
|
|
725
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
726
|
+
}
|
|
727
|
+
const featureFlags = [];
|
|
728
|
+
rawFlags.forEach((raw, index) => {
|
|
729
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
|
|
730
|
+
problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
|
|
734
|
+
featureFlags.push({
|
|
735
|
+
id: stableId("flag", raw.key),
|
|
736
|
+
key: raw.key,
|
|
737
|
+
name: typeof raw.name === "string" ? raw.name : raw.key,
|
|
738
|
+
type,
|
|
739
|
+
value: raw.value,
|
|
740
|
+
organizations: isRecord(raw.organizations) ? raw.organizations : {}
|
|
741
|
+
});
|
|
742
|
+
});
|
|
743
|
+
const plans = [];
|
|
744
|
+
rawPlans.forEach((raw, index) => {
|
|
745
|
+
if (!isRecord(raw) || typeof raw.key !== "string") {
|
|
746
|
+
problems.push(`plans[${index}] needs a string "key".`);
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
|
|
750
|
+
plans.push({
|
|
751
|
+
key: raw.key,
|
|
752
|
+
name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
|
|
753
|
+
subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
|
|
754
|
+
subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
755
|
+
entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
|
|
756
|
+
id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
|
|
757
|
+
featureKey: e.featureKey,
|
|
758
|
+
featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
|
|
759
|
+
priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
|
|
760
|
+
fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
|
|
761
|
+
unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
|
|
762
|
+
limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
|
|
763
|
+
limitMin: typeof e.limitMin === "number" ? e.limitMin : null
|
|
764
|
+
}))
|
|
765
|
+
});
|
|
766
|
+
});
|
|
767
|
+
const userProperties = {};
|
|
768
|
+
rawUsers.forEach((raw) => {
|
|
769
|
+
if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
|
|
770
|
+
userProperties[raw.id] = raw.properties;
|
|
771
|
+
}
|
|
772
|
+
});
|
|
773
|
+
if (problems.length > 0) {
|
|
774
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
775
|
+
}
|
|
776
|
+
const usedRoles = new Set(memberships.flatMap((m) => m.roles));
|
|
777
|
+
for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
|
|
778
|
+
const usedPermissions = /* @__PURE__ */ new Set([
|
|
779
|
+
...memberships.flatMap((m) => m.permissions),
|
|
780
|
+
...roles.flatMap((r) => r.permissions),
|
|
781
|
+
...applications.flatMap((a) => a.permissions ?? [])
|
|
782
|
+
]);
|
|
783
|
+
for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
|
|
784
|
+
return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
|
|
785
|
+
}
|
|
786
|
+
function findUser(users, ref) {
|
|
787
|
+
const needle = ref.toLowerCase();
|
|
788
|
+
return users.find((user) => user.id === ref || user.email?.toLowerCase() === needle);
|
|
789
|
+
}
|
|
790
|
+
function seedScenario(seed, ref) {
|
|
791
|
+
const user = findUser(seed.users, ref.user);
|
|
792
|
+
if (!user) {
|
|
793
|
+
throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${ref.user}".`, [
|
|
794
|
+
`Known users: ${seed.users.map((u) => u.email ?? u.id).join(", ") || "none"}`
|
|
795
|
+
]);
|
|
796
|
+
}
|
|
797
|
+
const userMemberships = seed.memberships.filter((m) => m.userId === user.id);
|
|
798
|
+
let membership;
|
|
799
|
+
if (ref.organization) {
|
|
800
|
+
if (!seed.organizations.some((org) => org.code === ref.organization)) {
|
|
801
|
+
throw new TestkitError(
|
|
802
|
+
"SEED_UNKNOWN_ORGANIZATION",
|
|
803
|
+
`No seeded organization has the code "${ref.organization}".`
|
|
804
|
+
);
|
|
805
|
+
}
|
|
806
|
+
membership = userMemberships.find((m) => m.organizationCode === ref.organization);
|
|
807
|
+
if (!membership) {
|
|
808
|
+
throw new TestkitError(
|
|
809
|
+
"SEED_NO_MEMBERSHIP",
|
|
810
|
+
`${user.email ?? user.id} is not a member of ${ref.organization}, so Kinde would not issue a token for that organization.`,
|
|
811
|
+
[`Member of: ${userMemberships.map((m) => m.organizationCode).join(", ") || "no organizations"}`]
|
|
812
|
+
);
|
|
813
|
+
}
|
|
814
|
+
} else if (userMemberships.length === 1) {
|
|
815
|
+
membership = userMemberships[0];
|
|
816
|
+
} else if (userMemberships.length > 1) {
|
|
817
|
+
throw new TestkitError(
|
|
818
|
+
"INVALID_REQUEST",
|
|
819
|
+
`${user.email ?? user.id} belongs to ${userMemberships.length} organizations. Choose the active one.`,
|
|
820
|
+
[`Organizations: ${userMemberships.map((m) => m.organizationCode).join(", ")}`]
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
const organization = membership ? seed.organizations.find((org) => org.code === membership.organizationCode) ?? null : null;
|
|
824
|
+
return {
|
|
825
|
+
kind: "authenticated",
|
|
826
|
+
user,
|
|
827
|
+
organization,
|
|
828
|
+
roles: [...membership?.roles ?? []],
|
|
829
|
+
permissions: effectivePermissions(seed, membership),
|
|
830
|
+
claims: {}
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
function listOf(value, field, problems) {
|
|
834
|
+
if (value === void 0) return [];
|
|
835
|
+
if (!Array.isArray(value)) {
|
|
836
|
+
problems.push(`"${field}" must be a list.`);
|
|
837
|
+
return [];
|
|
838
|
+
}
|
|
839
|
+
return value;
|
|
840
|
+
}
|
|
841
|
+
function isRecord(value) {
|
|
842
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
843
|
+
}
|
|
844
|
+
function featureFlagsFor(seed, organizationCode) {
|
|
845
|
+
if (seed.featureFlags.length === 0) return void 0;
|
|
846
|
+
const claim = {};
|
|
847
|
+
for (const flag of seed.featureFlags) {
|
|
848
|
+
const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
|
|
849
|
+
claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
|
|
850
|
+
}
|
|
851
|
+
return claim;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// src/directory.ts
|
|
855
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
856
|
+
var Directory = class {
|
|
857
|
+
constructor(seed) {
|
|
858
|
+
this.seed = seed;
|
|
859
|
+
this.snapshot = JSON.stringify(seed);
|
|
860
|
+
}
|
|
861
|
+
seed;
|
|
862
|
+
userMeta = /* @__PURE__ */ new Map();
|
|
863
|
+
orgMeta = /* @__PURE__ */ new Map();
|
|
864
|
+
snapshot;
|
|
865
|
+
restore() {
|
|
866
|
+
const original = JSON.parse(this.snapshot);
|
|
867
|
+
for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
|
|
868
|
+
this.seed[key].splice(0, this.seed[key].length, ...original[key]);
|
|
869
|
+
}
|
|
870
|
+
this.userMeta.clear();
|
|
871
|
+
this.orgMeta.clear();
|
|
872
|
+
}
|
|
873
|
+
/** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
|
|
874
|
+
load(next) {
|
|
875
|
+
for (const key of Object.keys(next)) {
|
|
876
|
+
const current = this.seed[key];
|
|
877
|
+
if (Array.isArray(current)) {
|
|
878
|
+
current.splice(0, current.length, ...next[key]);
|
|
879
|
+
} else {
|
|
880
|
+
const record = current;
|
|
881
|
+
for (const name of Object.keys(record)) delete record[name];
|
|
882
|
+
Object.assign(record, next[key]);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
this.snapshot = JSON.stringify(this.seed);
|
|
886
|
+
this.userMeta.clear();
|
|
887
|
+
this.orgMeta.clear();
|
|
888
|
+
}
|
|
889
|
+
user(id) {
|
|
890
|
+
return this.seed.users.find((user) => user.id === id);
|
|
891
|
+
}
|
|
892
|
+
meta(user) {
|
|
893
|
+
let meta = this.userMeta.get(user.id);
|
|
894
|
+
if (!meta) {
|
|
895
|
+
meta = {
|
|
896
|
+
providedId: null,
|
|
897
|
+
isSuspended: false,
|
|
898
|
+
isPasswordResetRequested: false,
|
|
899
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
900
|
+
totalSignIns: 0,
|
|
901
|
+
lastSignedIn: null
|
|
902
|
+
};
|
|
903
|
+
this.userMeta.set(user.id, meta);
|
|
904
|
+
}
|
|
905
|
+
return meta;
|
|
906
|
+
}
|
|
907
|
+
isSuspended(userId) {
|
|
908
|
+
return this.userMeta.get(userId)?.isSuspended ?? false;
|
|
909
|
+
}
|
|
910
|
+
recordSignIn(user, organizationCode) {
|
|
911
|
+
const meta = this.meta(user);
|
|
912
|
+
meta.totalSignIns += 1;
|
|
913
|
+
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
914
|
+
void organizationCode;
|
|
915
|
+
}
|
|
916
|
+
createUser(input) {
|
|
917
|
+
const user = createKindeUser({
|
|
918
|
+
id: `kp_${randomBytes2(16).toString("hex")}`,
|
|
919
|
+
email: input.email ?? null,
|
|
920
|
+
givenName: input.givenName ?? null,
|
|
921
|
+
familyName: input.familyName ?? null,
|
|
922
|
+
picture: input.picture ?? null
|
|
923
|
+
});
|
|
924
|
+
this.seed.users.push(user);
|
|
925
|
+
this.meta(user).providedId = input.providedId ?? null;
|
|
926
|
+
return user;
|
|
927
|
+
}
|
|
928
|
+
deleteUser(id) {
|
|
929
|
+
const index = this.seed.users.findIndex((user) => user.id === id);
|
|
930
|
+
if (index < 0) return false;
|
|
931
|
+
this.seed.users.splice(index, 1);
|
|
932
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
933
|
+
if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
|
|
934
|
+
}
|
|
935
|
+
this.userMeta.delete(id);
|
|
936
|
+
return true;
|
|
937
|
+
}
|
|
938
|
+
organization(code) {
|
|
939
|
+
return this.seed.organizations.find((org) => org.code === code);
|
|
940
|
+
}
|
|
941
|
+
orgInfo(org) {
|
|
942
|
+
let meta = this.orgMeta.get(org.code);
|
|
943
|
+
if (!meta) {
|
|
944
|
+
meta = {
|
|
945
|
+
externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
|
|
946
|
+
handle: slug(org.name),
|
|
947
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
948
|
+
isAllowRegistrations: false
|
|
949
|
+
};
|
|
950
|
+
this.orgMeta.set(org.code, meta);
|
|
951
|
+
}
|
|
952
|
+
return meta;
|
|
953
|
+
}
|
|
954
|
+
createOrganization(input) {
|
|
955
|
+
const org = createKindeOrganization({ code: `org_${randomBytes2(6).toString("hex").slice(0, 11)}`, name: input.name });
|
|
956
|
+
this.seed.organizations.push(org);
|
|
957
|
+
const meta = this.orgInfo(org);
|
|
958
|
+
meta.externalId = input.externalId ?? null;
|
|
959
|
+
if (input.handle) meta.handle = input.handle;
|
|
960
|
+
return org;
|
|
961
|
+
}
|
|
962
|
+
deleteOrganization(code) {
|
|
963
|
+
const index = this.seed.organizations.findIndex((org) => org.code === code);
|
|
964
|
+
if (index < 0) return false;
|
|
965
|
+
this.seed.organizations.splice(index, 1);
|
|
966
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
967
|
+
if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
|
|
968
|
+
}
|
|
969
|
+
this.orgMeta.delete(code);
|
|
970
|
+
return true;
|
|
971
|
+
}
|
|
972
|
+
membership(userId, organizationCode) {
|
|
973
|
+
return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
974
|
+
}
|
|
975
|
+
addMembership(userId, organizationCode, roles = [], permissions = []) {
|
|
976
|
+
const existing = this.membership(userId, organizationCode);
|
|
977
|
+
if (existing) return existing;
|
|
978
|
+
const membership = createMembership({ userId, organizationCode, roles, permissions });
|
|
979
|
+
this.seed.memberships.push(membership);
|
|
980
|
+
for (const key of roles) this.ensureRole(key);
|
|
981
|
+
for (const key of permissions) this.ensurePermission(key);
|
|
982
|
+
return membership;
|
|
983
|
+
}
|
|
984
|
+
removeMembership(userId, organizationCode) {
|
|
985
|
+
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
986
|
+
if (index < 0) return false;
|
|
987
|
+
this.seed.memberships.splice(index, 1);
|
|
988
|
+
return true;
|
|
989
|
+
}
|
|
990
|
+
role(idOrKey) {
|
|
991
|
+
return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
|
|
992
|
+
}
|
|
993
|
+
permission(idOrKey) {
|
|
994
|
+
return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
|
|
995
|
+
}
|
|
996
|
+
ensureRole(key, extra = {}) {
|
|
997
|
+
const existing = this.role(key);
|
|
998
|
+
if (existing) return existing;
|
|
999
|
+
const role = roleRecord(key, extra);
|
|
1000
|
+
this.seed.roles.push(role);
|
|
1001
|
+
return role;
|
|
1002
|
+
}
|
|
1003
|
+
ensurePermission(key, extra = {}) {
|
|
1004
|
+
const existing = this.permission(key);
|
|
1005
|
+
if (existing) return existing;
|
|
1006
|
+
const permission = permissionRecord(key, extra);
|
|
1007
|
+
this.seed.permissions.push(permission);
|
|
1008
|
+
return permission;
|
|
1009
|
+
}
|
|
1010
|
+
deleteRole(id) {
|
|
1011
|
+
const role = this.role(id);
|
|
1012
|
+
if (!role) return void 0;
|
|
1013
|
+
this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
|
|
1014
|
+
for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
|
|
1015
|
+
return role;
|
|
1016
|
+
}
|
|
1017
|
+
deletePermission(id) {
|
|
1018
|
+
const permission = this.permission(id);
|
|
1019
|
+
if (!permission) return void 0;
|
|
1020
|
+
this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
|
|
1021
|
+
for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
|
|
1022
|
+
for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
|
|
1023
|
+
return permission;
|
|
1024
|
+
}
|
|
1025
|
+
};
|
|
1026
|
+
|
|
1027
|
+
// src/failures.ts
|
|
1028
|
+
var MAX_DELAY_MS = 6e4;
|
|
1029
|
+
var FailureInjector = class {
|
|
1030
|
+
rules = [];
|
|
1031
|
+
nextId = 1;
|
|
1032
|
+
add(rule) {
|
|
1033
|
+
const problems = validate(rule);
|
|
1034
|
+
if (problems.length > 0) {
|
|
1035
|
+
throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
|
|
1036
|
+
}
|
|
1037
|
+
const active = {
|
|
1038
|
+
id: `failure_${this.nextId++}`,
|
|
1039
|
+
path: rule.path,
|
|
1040
|
+
method: rule.method ? rule.method.toUpperCase() : null,
|
|
1041
|
+
status: rule.status ?? null,
|
|
1042
|
+
delayMs: rule.delayMs ?? 0,
|
|
1043
|
+
hang: rule.hang ?? false,
|
|
1044
|
+
remaining: rule.times ?? null,
|
|
1045
|
+
retryAfter: rule.retryAfter ?? 1,
|
|
1046
|
+
hits: 0
|
|
1047
|
+
};
|
|
1048
|
+
this.rules.push(active);
|
|
1049
|
+
return { ...active };
|
|
1050
|
+
}
|
|
1051
|
+
remove(id) {
|
|
1052
|
+
const before = this.rules.length;
|
|
1053
|
+
this.rules = this.rules.filter((rule) => rule.id !== id);
|
|
1054
|
+
return this.rules.length < before;
|
|
1055
|
+
}
|
|
1056
|
+
clear() {
|
|
1057
|
+
this.rules = [];
|
|
1058
|
+
}
|
|
1059
|
+
list() {
|
|
1060
|
+
return this.rules.map((rule) => ({ ...rule }));
|
|
1061
|
+
}
|
|
1062
|
+
take(method, path) {
|
|
1063
|
+
const rule = this.rules.find((r) => matches(r, method, path));
|
|
1064
|
+
if (!rule) return null;
|
|
1065
|
+
rule.hits += 1;
|
|
1066
|
+
if (rule.remaining !== null) {
|
|
1067
|
+
rule.remaining -= 1;
|
|
1068
|
+
if (rule.remaining <= 0) this.remove(rule.id);
|
|
1069
|
+
}
|
|
1070
|
+
return { ...rule };
|
|
1071
|
+
}
|
|
1072
|
+
};
|
|
1073
|
+
function failureBody(status) {
|
|
1074
|
+
const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
|
|
1075
|
+
return { error, error_description: `kinde-testkit injected a ${status} response.` };
|
|
1076
|
+
}
|
|
1077
|
+
function matches(rule, method, path) {
|
|
1078
|
+
if (rule.method && rule.method !== method.toUpperCase()) return false;
|
|
1079
|
+
if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
|
|
1080
|
+
return rule.path === path;
|
|
1081
|
+
}
|
|
1082
|
+
function validate(rule) {
|
|
1083
|
+
const problems = [];
|
|
1084
|
+
if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
|
|
1085
|
+
problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
|
|
1086
|
+
} else if (rule.path.startsWith("/testkit/")) {
|
|
1087
|
+
problems.push("Failures cannot target /testkit/ control endpoints.");
|
|
1088
|
+
}
|
|
1089
|
+
if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
|
|
1090
|
+
problems.push('"status" must be an HTTP error status between 400 and 599.');
|
|
1091
|
+
}
|
|
1092
|
+
if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
|
|
1093
|
+
problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
|
|
1094
|
+
}
|
|
1095
|
+
if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
|
|
1096
|
+
problems.push('"times" must be a whole number of 1 or more.');
|
|
1097
|
+
}
|
|
1098
|
+
if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
|
|
1099
|
+
problems.push('"retryAfter" must be a whole number of seconds.');
|
|
1100
|
+
}
|
|
1101
|
+
if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
|
|
1102
|
+
problems.push('Set at least one of "status", "delayMs" or "hang".');
|
|
1103
|
+
}
|
|
1104
|
+
return problems;
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// src/webhooks.ts
|
|
1108
|
+
import { randomBytes as randomBytes3 } from "crypto";
|
|
1109
|
+
var WEBHOOK_EVENT_TYPES = [
|
|
1110
|
+
"user.created",
|
|
1111
|
+
"user.updated",
|
|
1112
|
+
"user.deleted",
|
|
1113
|
+
"user.authenticated",
|
|
1114
|
+
"user.authentication_failed",
|
|
1115
|
+
"organization.created",
|
|
1116
|
+
"organization.updated",
|
|
1117
|
+
"organization.deleted",
|
|
1118
|
+
"role.created",
|
|
1119
|
+
"role.updated",
|
|
1120
|
+
"role.deleted",
|
|
1121
|
+
"permission.created",
|
|
1122
|
+
"permission.updated",
|
|
1123
|
+
"permission.deleted",
|
|
1124
|
+
"subscriber.created",
|
|
1125
|
+
"access_request.created"
|
|
1126
|
+
];
|
|
1127
|
+
var BILLING_EVENT_TYPES = [
|
|
1128
|
+
"customer.agreement_cancelled",
|
|
1129
|
+
"customer.agreement_created",
|
|
1130
|
+
"customer.invoice_overdue",
|
|
1131
|
+
"customer.meter_usage_updated",
|
|
1132
|
+
"customer.payment_failed",
|
|
1133
|
+
"customer.payment_succeeded",
|
|
1134
|
+
"customer.plan_assigned",
|
|
1135
|
+
"customer.plan_changed"
|
|
1136
|
+
];
|
|
1137
|
+
var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
|
|
1138
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
1139
|
+
var MAX_DUPLICATES = 10;
|
|
1140
|
+
var WebhookDispatcher = class {
|
|
1141
|
+
constructor(testkit, seed, endpoints = [], options = {}) {
|
|
1142
|
+
this.testkit = testkit;
|
|
1143
|
+
this.seed = seed;
|
|
1144
|
+
this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
1145
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1146
|
+
for (const endpoint of endpoints) this.addEndpoint(endpoint);
|
|
1147
|
+
this.seededEndpoints = [...this.endpoints];
|
|
1148
|
+
}
|
|
1149
|
+
testkit;
|
|
1150
|
+
seed;
|
|
1151
|
+
endpoints = [];
|
|
1152
|
+
seededEndpoints = [];
|
|
1153
|
+
log = [];
|
|
1154
|
+
nextEndpoint = 1;
|
|
1155
|
+
retryDelaysMs;
|
|
1156
|
+
timeoutMs;
|
|
1157
|
+
/** Set by the server to record coverage. */
|
|
1158
|
+
observe = () => void 0;
|
|
1159
|
+
addEndpoint(input) {
|
|
1160
|
+
if (!isHttpUrl(input.url)) {
|
|
1161
|
+
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
1162
|
+
}
|
|
1163
|
+
if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
|
|
1164
|
+
throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
|
|
1165
|
+
}
|
|
1166
|
+
const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
|
|
1167
|
+
this.endpoints.push(endpoint);
|
|
1168
|
+
return { ...endpoint };
|
|
1169
|
+
}
|
|
1170
|
+
/** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
|
|
1171
|
+
replaceSeededEndpoints(endpoints) {
|
|
1172
|
+
const seeded = new Set(this.seededEndpoints.map((e) => e.id));
|
|
1173
|
+
this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
|
|
1174
|
+
const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
|
|
1175
|
+
const ids = new Set(added.map((e) => e.id));
|
|
1176
|
+
this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
|
|
1177
|
+
}
|
|
1178
|
+
removeEndpoint(id) {
|
|
1179
|
+
const before = this.endpoints.length;
|
|
1180
|
+
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
1181
|
+
return this.endpoints.length < before;
|
|
1182
|
+
}
|
|
1183
|
+
listEndpoints() {
|
|
1184
|
+
return this.endpoints.map((e) => ({ ...e }));
|
|
1185
|
+
}
|
|
1186
|
+
deliveries() {
|
|
1187
|
+
return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
|
|
1188
|
+
}
|
|
1189
|
+
reset() {
|
|
1190
|
+
this.log = [];
|
|
1191
|
+
this.endpoints = [...this.seededEndpoints];
|
|
1192
|
+
}
|
|
1193
|
+
buildEvent(options) {
|
|
1194
|
+
if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
|
|
1195
|
+
throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
|
|
1196
|
+
}
|
|
1197
|
+
const now = /* @__PURE__ */ new Date();
|
|
1198
|
+
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1199
|
+
const event = {
|
|
1200
|
+
data: options.data ?? this.buildData(options),
|
|
1201
|
+
event_id: `event_${randomBytes3(16).toString("hex")}`,
|
|
1202
|
+
event_timestamp: timestamp,
|
|
1203
|
+
source: options.source ?? "admin",
|
|
1204
|
+
timestamp,
|
|
1205
|
+
type: options.type
|
|
1206
|
+
};
|
|
1207
|
+
if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
|
|
1208
|
+
event.ip_address = options.ipAddress ?? "127.0.0.1";
|
|
1209
|
+
}
|
|
1210
|
+
return event;
|
|
1211
|
+
}
|
|
1212
|
+
async send(options) {
|
|
1213
|
+
const event = this.buildEvent(options);
|
|
1214
|
+
const copies = options.duplicate ?? 1;
|
|
1215
|
+
if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
|
|
1216
|
+
throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
|
|
1217
|
+
}
|
|
1218
|
+
const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
|
|
1219
|
+
if (options.to && !isHttpUrl(options.to)) {
|
|
1220
|
+
throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
|
|
1221
|
+
}
|
|
1222
|
+
if (targets.length === 0) {
|
|
1223
|
+
throw new TestkitError(
|
|
1224
|
+
"INVALID_REQUEST",
|
|
1225
|
+
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
if (copies > 1) this.observe("webhook.duplicate");
|
|
1229
|
+
if (options.invalid === "stale") this.observe("webhook.stale");
|
|
1230
|
+
else if (options.invalid) this.observe("webhook.forged");
|
|
1231
|
+
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
1232
|
+
const signed = await this.testkit.signPayload(
|
|
1233
|
+
event,
|
|
1234
|
+
options.invalid === "stale" ? void 0 : options.invalid
|
|
1235
|
+
);
|
|
1236
|
+
const jobs = targets.flatMap((target) => {
|
|
1237
|
+
const webhookId = `wh_${randomBytes3(12).toString("hex")}`;
|
|
1238
|
+
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1239
|
+
});
|
|
1240
|
+
const deliveries = await Promise.all(jobs);
|
|
1241
|
+
if (!options.invalid) {
|
|
1242
|
+
for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
|
|
1243
|
+
}
|
|
1244
|
+
return deliveries;
|
|
1245
|
+
}
|
|
1246
|
+
async deliver(url, webhookId, body, event, copy) {
|
|
1247
|
+
const delivery = {
|
|
1248
|
+
webhookId,
|
|
1249
|
+
eventId: String(event.event_id),
|
|
1250
|
+
type: String(event.type),
|
|
1251
|
+
url,
|
|
1252
|
+
copy,
|
|
1253
|
+
delivered: false,
|
|
1254
|
+
attempts: [],
|
|
1255
|
+
payload: event
|
|
1256
|
+
};
|
|
1257
|
+
this.log.push(delivery);
|
|
1258
|
+
for (const [index, delay] of this.retryDelaysMs.entries()) {
|
|
1259
|
+
if (delay > 0) await sleep(delay);
|
|
1260
|
+
const started = Date.now();
|
|
1261
|
+
try {
|
|
1262
|
+
const response = await fetch(url, {
|
|
1263
|
+
method: "POST",
|
|
1264
|
+
headers: { "content-type": "application/jwt", "webhook-id": webhookId },
|
|
1265
|
+
body,
|
|
1266
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
1267
|
+
});
|
|
1268
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
1269
|
+
delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
|
|
1270
|
+
if (response.status === 200) {
|
|
1271
|
+
delivery.delivered = true;
|
|
1272
|
+
break;
|
|
1273
|
+
}
|
|
1274
|
+
} catch (error) {
|
|
1275
|
+
const name = error.name;
|
|
1276
|
+
delivery.attempts.push({
|
|
1277
|
+
attempt: index + 1,
|
|
1278
|
+
status: null,
|
|
1279
|
+
error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
|
|
1280
|
+
durationMs: Date.now() - started
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
return { ...delivery, attempts: [...delivery.attempts] };
|
|
1285
|
+
}
|
|
1286
|
+
buildData(options) {
|
|
1287
|
+
const [subject] = options.type.split(".");
|
|
1288
|
+
switch (subject) {
|
|
1289
|
+
case "user":
|
|
1290
|
+
return { user: this.userData(options) };
|
|
1291
|
+
case "organization":
|
|
1292
|
+
return { organization: this.organizationData(options) };
|
|
1293
|
+
case "role":
|
|
1294
|
+
return { role: this.namedData(options, "role") };
|
|
1295
|
+
case "permission":
|
|
1296
|
+
return { permission: this.namedData(options, "permission") };
|
|
1297
|
+
case "subscriber": {
|
|
1298
|
+
const user = this.requireUser(options);
|
|
1299
|
+
return {
|
|
1300
|
+
subscriber: {
|
|
1301
|
+
email: user.email,
|
|
1302
|
+
first_name: user.givenName,
|
|
1303
|
+
id: stableId("sub", user.id),
|
|
1304
|
+
last_name: user.familyName,
|
|
1305
|
+
user_id: user.id
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
case "access_request": {
|
|
1310
|
+
const user = this.requireUser(options);
|
|
1311
|
+
return {
|
|
1312
|
+
access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
default:
|
|
1316
|
+
throw new TestkitError(
|
|
1317
|
+
"INVALID_REQUEST",
|
|
1318
|
+
`kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
|
|
1319
|
+
);
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
emit(type, data, source = "api") {
|
|
1323
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1324
|
+
void this.send({ type, data, source }).catch(() => void 0);
|
|
1325
|
+
}
|
|
1326
|
+
userEventData(user) {
|
|
1327
|
+
return this.userPayload(user);
|
|
1328
|
+
}
|
|
1329
|
+
emitForUser(type, user) {
|
|
1330
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1331
|
+
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
1332
|
+
void this.send({ type, data, source: "user" }).catch(() => void 0);
|
|
1333
|
+
}
|
|
1334
|
+
userData(options) {
|
|
1335
|
+
const user = this.requireUser(options);
|
|
1336
|
+
if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
|
|
1337
|
+
return this.userPayload(user);
|
|
1338
|
+
}
|
|
1339
|
+
userPayload(user) {
|
|
1340
|
+
return {
|
|
1341
|
+
email: user.email,
|
|
1342
|
+
first_name: user.givenName,
|
|
1343
|
+
id: user.id,
|
|
1344
|
+
is_password_reset_requested: false,
|
|
1345
|
+
is_suspended: false,
|
|
1346
|
+
last_name: user.familyName,
|
|
1347
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
|
|
1348
|
+
code: m.organizationCode,
|
|
1349
|
+
permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
|
|
1350
|
+
roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
|
|
1351
|
+
})),
|
|
1352
|
+
phone: null,
|
|
1353
|
+
username: typeof user.claims.username === "string" ? user.claims.username : null
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
organizationData(options) {
|
|
1357
|
+
if (!options.organization) {
|
|
1358
|
+
throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
|
|
1359
|
+
}
|
|
1360
|
+
const org = this.seed.organizations.find((o) => o.code === options.organization);
|
|
1361
|
+
if (options.type === "organization.deleted") return { code: options.organization };
|
|
1362
|
+
const name = org?.name ?? titleCase(options.organization);
|
|
1363
|
+
const data = { code: options.organization, external_id: null, handle: slug(name), name };
|
|
1364
|
+
if (options.type === "organization.updated") data.is_allow_registrations = false;
|
|
1365
|
+
return data;
|
|
1366
|
+
}
|
|
1367
|
+
namedData(options, kind) {
|
|
1368
|
+
const key = kind === "role" ? options.role : options.permission;
|
|
1369
|
+
if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
|
|
1370
|
+
const id = stableId(kind === "role" ? "role" : "perm", key);
|
|
1371
|
+
if (options.type.endsWith(".deleted")) return { id };
|
|
1372
|
+
const data = { description: "", id, key, name: titleCase(key) };
|
|
1373
|
+
if (kind === "role") data.is_default_role = false;
|
|
1374
|
+
return data;
|
|
1375
|
+
}
|
|
1376
|
+
requireUser(options) {
|
|
1377
|
+
if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
|
|
1378
|
+
const user = findUser(this.seed.users, options.user);
|
|
1379
|
+
if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
|
|
1380
|
+
return user;
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
function isHttpUrl(value) {
|
|
1384
|
+
if (typeof value !== "string") return false;
|
|
1385
|
+
try {
|
|
1386
|
+
const { protocol } = new URL(value);
|
|
1387
|
+
return protocol === "http:" || protocol === "https:";
|
|
1388
|
+
} catch {
|
|
1389
|
+
return false;
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
function sleep(ms) {
|
|
1393
|
+
return new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
// src/activity.ts
|
|
1397
|
+
var LIMIT = 200;
|
|
1398
|
+
var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
|
|
1399
|
+
var ActivityLog = class {
|
|
1400
|
+
requestLog = [];
|
|
1401
|
+
tokenLog = [];
|
|
1402
|
+
request(entry) {
|
|
1403
|
+
const query = new URLSearchParams(entry.query);
|
|
1404
|
+
for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
|
|
1405
|
+
const search = query.toString();
|
|
1406
|
+
push(this.requestLog, {
|
|
1407
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1408
|
+
method: entry.method,
|
|
1409
|
+
path: search ? `${entry.path}?${search}` : entry.path,
|
|
1410
|
+
status: entry.status,
|
|
1411
|
+
durationMs: entry.durationMs,
|
|
1412
|
+
injected: entry.injected
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
token(kind, claims, invalid2, token) {
|
|
1416
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
1417
|
+
push(this.tokenLog, {
|
|
1418
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1419
|
+
kind,
|
|
1420
|
+
subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
|
|
1421
|
+
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
1422
|
+
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
1423
|
+
roles,
|
|
1424
|
+
invalid: invalid2 ?? null,
|
|
1425
|
+
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
1426
|
+
claims,
|
|
1427
|
+
token
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
requests() {
|
|
1431
|
+
return [...this.requestLog];
|
|
1432
|
+
}
|
|
1433
|
+
tokens() {
|
|
1434
|
+
return [...this.tokenLog];
|
|
1435
|
+
}
|
|
1436
|
+
reset() {
|
|
1437
|
+
this.requestLog = [];
|
|
1438
|
+
this.tokenLog = [];
|
|
1439
|
+
}
|
|
1440
|
+
};
|
|
1441
|
+
function push(list, entry) {
|
|
1442
|
+
list.push(entry);
|
|
1443
|
+
if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// src/coverage.ts
|
|
1447
|
+
import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
1448
|
+
import { join as join2, resolve as resolve2 } from "path";
|
|
1449
|
+
var COVERAGE_GROUPS = [
|
|
1450
|
+
{
|
|
1451
|
+
name: "Identity",
|
|
1452
|
+
items: [
|
|
1453
|
+
{ id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
|
|
1454
|
+
{ id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
|
|
1455
|
+
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
1456
|
+
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
1457
|
+
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
1458
|
+
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
|
|
1459
|
+
]
|
|
1460
|
+
},
|
|
1461
|
+
{
|
|
1462
|
+
name: "Organizations",
|
|
1463
|
+
items: [
|
|
1464
|
+
{ id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
|
|
1465
|
+
{ id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
|
|
1466
|
+
{ id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
|
|
1467
|
+
{ id: "organization.non-member", label: "Non-member refused", hint: "Ask for a token or sign-in for an organization the user does not belong to." },
|
|
1468
|
+
{ id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
|
|
1469
|
+
]
|
|
1470
|
+
},
|
|
1471
|
+
{
|
|
1472
|
+
name: "Permissions",
|
|
1473
|
+
items: [
|
|
1474
|
+
{ id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
|
|
1475
|
+
{ id: "permission.different-sets", label: "Different permissions in one organization", hint: "Mint tokens for two users in one organization with different permissions, such as an admin and a viewer." },
|
|
1476
|
+
{ id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
|
|
1477
|
+
{ id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
|
|
1478
|
+
{ id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
|
|
1479
|
+
]
|
|
1480
|
+
},
|
|
1481
|
+
{
|
|
1482
|
+
name: "Token validation",
|
|
1483
|
+
items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
|
|
1484
|
+
(kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
|
|
1485
|
+
)
|
|
1486
|
+
},
|
|
1487
|
+
{
|
|
1488
|
+
name: "Sessions",
|
|
1489
|
+
items: [
|
|
1490
|
+
{ id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
|
|
1491
|
+
{ id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
|
|
1492
|
+
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
1493
|
+
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
1494
|
+
{ id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
|
|
1495
|
+
]
|
|
1496
|
+
},
|
|
1497
|
+
{
|
|
1498
|
+
name: "Machine-to-machine",
|
|
1499
|
+
items: [
|
|
1500
|
+
{ id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
|
|
1501
|
+
{ id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
|
|
1502
|
+
{ id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
|
|
1503
|
+
{ id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
|
|
1504
|
+
]
|
|
1505
|
+
},
|
|
1506
|
+
{
|
|
1507
|
+
name: "Kinde APIs",
|
|
1508
|
+
items: [
|
|
1509
|
+
{ id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
|
|
1510
|
+
{ id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
|
|
1511
|
+
{ id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
|
|
1512
|
+
{ id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
|
|
1513
|
+
]
|
|
1514
|
+
},
|
|
1515
|
+
{
|
|
1516
|
+
name: "Webhooks",
|
|
1517
|
+
items: [
|
|
1518
|
+
{ id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
|
|
1519
|
+
{ id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
|
|
1520
|
+
{ id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
|
|
1521
|
+
{ id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
|
|
1522
|
+
{ id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
|
|
1523
|
+
]
|
|
1524
|
+
},
|
|
1525
|
+
{
|
|
1526
|
+
name: "Outages",
|
|
1527
|
+
items: [
|
|
1528
|
+
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
1529
|
+
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
1530
|
+
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
1531
|
+
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
|
|
1532
|
+
]
|
|
1533
|
+
}
|
|
1534
|
+
];
|
|
1535
|
+
var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
|
|
1536
|
+
function tokenLabel(kind) {
|
|
1537
|
+
return {
|
|
1538
|
+
expired: "Expired token",
|
|
1539
|
+
"future-iat": "Token issued in the future",
|
|
1540
|
+
"wrong-issuer": "Wrong issuer",
|
|
1541
|
+
"wrong-audience": "Wrong audience",
|
|
1542
|
+
"bad-signature": "Tampered signature",
|
|
1543
|
+
"unknown-key": "Unknown signing key",
|
|
1544
|
+
unsigned: "Unsigned token",
|
|
1545
|
+
"missing-subject": "No subject"
|
|
1546
|
+
}[kind];
|
|
1547
|
+
}
|
|
1548
|
+
var CoverageRecorder = class {
|
|
1549
|
+
hits = /* @__PURE__ */ new Map();
|
|
1550
|
+
userOrganizations = /* @__PURE__ */ new Map();
|
|
1551
|
+
organizationUsers = /* @__PURE__ */ new Map();
|
|
1552
|
+
organizationPermissionSets = /* @__PURE__ */ new Map();
|
|
1553
|
+
hit(id) {
|
|
1554
|
+
if (!ALL_IDS.has(id)) return;
|
|
1555
|
+
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
1556
|
+
}
|
|
1557
|
+
/** Called for every access token the testkit signs. */
|
|
1558
|
+
observeAccessToken(payload, invalid2) {
|
|
1559
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
1560
|
+
this.hit("m2m.token");
|
|
1561
|
+
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
1562
|
+
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
1563
|
+
if (invalid2) this.hit("m2m.invalid");
|
|
1564
|
+
return;
|
|
1565
|
+
}
|
|
1566
|
+
if (invalid2 === "missing-organization") return this.hit("organization.missing");
|
|
1567
|
+
if (invalid2 === "missing-permissions") return this.hit("permission.none");
|
|
1568
|
+
if (invalid2) return this.hit(`token.${invalid2}`);
|
|
1569
|
+
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
1570
|
+
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
1571
|
+
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
1572
|
+
if (subject) this.hit("identity.user");
|
|
1573
|
+
if (!organization) this.hit("identity.no-organization");
|
|
1574
|
+
if (permissions.length > 0) this.hit("permission.granted");
|
|
1575
|
+
else this.hit("permission.none");
|
|
1576
|
+
if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
|
|
1577
|
+
if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
|
|
1578
|
+
if (!organization) return;
|
|
1579
|
+
this.hit("organization.token");
|
|
1580
|
+
if (subject) {
|
|
1581
|
+
const organizations = add(this.userOrganizations, subject, organization);
|
|
1582
|
+
if (organizations.size > 1) this.hit("organization.two-for-one-user");
|
|
1583
|
+
add(this.organizationUsers, organization, subject);
|
|
1584
|
+
const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
|
|
1585
|
+
const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
|
|
1586
|
+
if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
|
|
1587
|
+
}
|
|
1588
|
+
const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
|
|
1589
|
+
if (sets.size > 1) this.hit("permission.different-sets");
|
|
1590
|
+
}
|
|
1591
|
+
report() {
|
|
1592
|
+
return buildReport(Object.fromEntries(this.hits));
|
|
1593
|
+
}
|
|
1594
|
+
snapshot() {
|
|
1595
|
+
return { version: 1, hits: Object.fromEntries(this.hits) };
|
|
1596
|
+
}
|
|
1597
|
+
reset() {
|
|
1598
|
+
this.hits.clear();
|
|
1599
|
+
this.userOrganizations.clear();
|
|
1600
|
+
this.organizationUsers.clear();
|
|
1601
|
+
this.organizationPermissionSets.clear();
|
|
1602
|
+
}
|
|
1603
|
+
/** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
|
|
1604
|
+
write(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
1605
|
+
const folder = resolve2(directory);
|
|
1606
|
+
mkdirSync2(folder, { recursive: true });
|
|
1607
|
+
const file = join2(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
|
|
1608
|
+
writeFileSync2(file, `${JSON.stringify(this.snapshot())}
|
|
1609
|
+
`);
|
|
1610
|
+
return file;
|
|
1611
|
+
}
|
|
1612
|
+
};
|
|
1613
|
+
var DEFAULT_COVERAGE_DIRECTORY = join2(".kinde-testkit", "coverage");
|
|
1614
|
+
function add(map, key, value) {
|
|
1615
|
+
let set2 = map.get(key);
|
|
1616
|
+
if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
|
|
1617
|
+
set2.add(value);
|
|
1618
|
+
return set2;
|
|
1619
|
+
}
|
|
1620
|
+
function buildReport(hits) {
|
|
1621
|
+
const groups = COVERAGE_GROUPS.map((group) => {
|
|
1622
|
+
const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
|
|
1623
|
+
return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
|
|
1624
|
+
});
|
|
1625
|
+
return {
|
|
1626
|
+
covered: groups.reduce((sum, g) => sum + g.covered, 0),
|
|
1627
|
+
total: groups.reduce((sum, g) => sum + g.total, 0),
|
|
1628
|
+
groups
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
function mergeSnapshots(snapshots) {
|
|
1632
|
+
const hits = {};
|
|
1633
|
+
for (const snapshot of snapshots) {
|
|
1634
|
+
for (const [id, count] of Object.entries(snapshot.hits ?? {})) hits[id] = (hits[id] ?? 0) + count;
|
|
1635
|
+
}
|
|
1636
|
+
return hits;
|
|
1637
|
+
}
|
|
1638
|
+
function readCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
1639
|
+
const folder = resolve2(directory);
|
|
1640
|
+
let names = [];
|
|
1641
|
+
try {
|
|
1642
|
+
names = readdirSync(folder).filter((name) => name.endsWith(".json"));
|
|
1643
|
+
} catch {
|
|
1644
|
+
}
|
|
1645
|
+
const snapshots = names.map((name) => JSON.parse(readFileSync2(join2(folder, name), "utf8")));
|
|
1646
|
+
return { files: names.length, report: buildReport(mergeSnapshots(snapshots)) };
|
|
1647
|
+
}
|
|
1648
|
+
function clearCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
1649
|
+
rmSync(resolve2(directory), { recursive: true, force: true });
|
|
1650
|
+
}
|
|
1651
|
+
function formatCoverageReport(report, options = {}) {
|
|
1652
|
+
const width = Math.max(...report.groups.map((g) => g.name.length)) + 3;
|
|
1653
|
+
const lines = ["Kinde authentication coverage", ""];
|
|
1654
|
+
for (const group of report.groups) {
|
|
1655
|
+
lines.push(`${group.name.padEnd(width)}${String(group.covered).padStart(2)}/${group.total}`);
|
|
1656
|
+
}
|
|
1657
|
+
lines.push("", `Overall: ${report.covered}/${report.total}`);
|
|
1658
|
+
if (options.missing !== false) {
|
|
1659
|
+
const missing = report.groups.flatMap((g) => g.items.filter((i) => !i.covered).map((i) => ({ group: g.name, ...i })));
|
|
1660
|
+
if (missing.length > 0) {
|
|
1661
|
+
lines.push("", "Not covered:");
|
|
1662
|
+
for (const item of missing) lines.push(` ${item.group}: ${item.label}. ${item.hint}`);
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
return lines.join("\n");
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
// src/seed-file.ts
|
|
1669
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
1670
|
+
import { extname, resolve as resolve3 } from "path";
|
|
1671
|
+
import { pathToFileURL } from "url";
|
|
1672
|
+
import { parse as parseYaml } from "yaml";
|
|
1673
|
+
var DEFAULT_SEED_FILES = [
|
|
1674
|
+
"kinde-testkit.json",
|
|
1675
|
+
"kinde-testkit.yaml",
|
|
1676
|
+
"kinde-testkit.yml",
|
|
1677
|
+
"kinde-testkit.ts",
|
|
1678
|
+
"kinde-testkit.mts",
|
|
1679
|
+
"kinde-testkit.js",
|
|
1680
|
+
"kinde-testkit.mjs"
|
|
1681
|
+
];
|
|
1682
|
+
function findSeedFile(directory = ".") {
|
|
1683
|
+
return DEFAULT_SEED_FILES.map((name) => resolve3(directory, name)).find((path) => existsSync2(path));
|
|
1684
|
+
}
|
|
1685
|
+
async function loadSeedFile(path) {
|
|
1686
|
+
const file = resolve3(path);
|
|
1687
|
+
const extension = extname(file).toLowerCase();
|
|
1688
|
+
let value;
|
|
1689
|
+
try {
|
|
1690
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
1691
|
+
value = parseYaml(readFileSync3(file, "utf8"));
|
|
1692
|
+
} else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
|
|
1693
|
+
const module = await import(pathToFileURL(file).href);
|
|
1694
|
+
value = module.seed ?? module.default;
|
|
1695
|
+
if (value && typeof value === "object" && "default" in value && !("users" in value)) {
|
|
1696
|
+
value = value.default;
|
|
1697
|
+
}
|
|
1698
|
+
} else {
|
|
1699
|
+
value = JSON.parse(readFileSync3(file, "utf8"));
|
|
1700
|
+
}
|
|
1701
|
+
} catch (error) {
|
|
1702
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1703
|
+
const details = [message];
|
|
1704
|
+
if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message)) {
|
|
1705
|
+
details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
|
|
1706
|
+
}
|
|
1707
|
+
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
|
|
1708
|
+
}
|
|
1709
|
+
if (value === null || value === void 0) value = {};
|
|
1710
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
1711
|
+
throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
|
|
1712
|
+
}
|
|
1713
|
+
return value;
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
// src/server.ts
|
|
1717
|
+
import { createServer } from "http";
|
|
1718
|
+
import { createServer as createHttpsServer } from "https";
|
|
1719
|
+
|
|
1720
|
+
// src/login-page.ts
|
|
1721
|
+
var STYLE = `
|
|
1722
|
+
: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}
|
|
1723
|
+
@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}}
|
|
1724
|
+
*{box-sizing:border-box}
|
|
1725
|
+
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}
|
|
1726
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
1727
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
1728
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
1729
|
+
p{margin:0;color:var(--muted)}
|
|
1730
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
1731
|
+
form{margin:0}
|
|
1732
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
1733
|
+
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}
|
|
1734
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
1735
|
+
.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}
|
|
1736
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
1737
|
+
.list{display:grid;gap:8px}
|
|
1738
|
+
.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}
|
|
1739
|
+
.option:hover{border-color:var(--muted)}
|
|
1740
|
+
.option strong{display:block;font-weight:500}
|
|
1741
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
1742
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
1743
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
1744
|
+
`;
|
|
1745
|
+
function escapeHtml(value) {
|
|
1746
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1747
|
+
}
|
|
1748
|
+
function layout(title, body) {
|
|
1749
|
+
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>`;
|
|
1750
|
+
}
|
|
1751
|
+
function displayName(user) {
|
|
1752
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
1753
|
+
}
|
|
1754
|
+
function renderSignIn(options) {
|
|
1755
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
1756
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
1757
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
1758
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
1759
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
1760
|
+
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>`;
|
|
1761
|
+
}).join("");
|
|
1762
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
1763
|
+
return layout(
|
|
1764
|
+
"Sign in",
|
|
1765
|
+
`<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>`
|
|
1766
|
+
);
|
|
1767
|
+
}
|
|
1768
|
+
function renderOrganizationPicker(options) {
|
|
1769
|
+
const choices = options.organizations.map(
|
|
1770
|
+
(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>`
|
|
1771
|
+
).join("");
|
|
1772
|
+
return layout(
|
|
1773
|
+
"Choose an organization",
|
|
1774
|
+
`<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>`
|
|
1775
|
+
);
|
|
1776
|
+
}
|
|
1777
|
+
function renderMessage(title, message) {
|
|
1778
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
// src/oauth.ts
|
|
1782
|
+
import { createHash as createHash3, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
|
|
1783
|
+
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
1784
|
+
var OAuthError = class extends Error {
|
|
1785
|
+
constructor(status, error, description) {
|
|
1786
|
+
super(description);
|
|
1787
|
+
this.status = status;
|
|
1788
|
+
this.error = error;
|
|
1789
|
+
}
|
|
1790
|
+
status;
|
|
1791
|
+
error;
|
|
1792
|
+
};
|
|
1793
|
+
var AuthorizationServer = class {
|
|
1794
|
+
constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
|
|
1795
|
+
this.testkit = testkit;
|
|
1796
|
+
this.seed = seed;
|
|
1797
|
+
this.emit = emit;
|
|
1798
|
+
this.directory = directory;
|
|
1799
|
+
this.observe = observe;
|
|
1800
|
+
}
|
|
1801
|
+
testkit;
|
|
1802
|
+
seed;
|
|
1803
|
+
emit;
|
|
1804
|
+
directory;
|
|
1805
|
+
observe;
|
|
1806
|
+
codes = /* @__PURE__ */ new Map();
|
|
1807
|
+
refreshTokens = /* @__PURE__ */ new Map();
|
|
1808
|
+
signedUpUsers = /* @__PURE__ */ new Map();
|
|
1809
|
+
async handle(req, res, url, readBody) {
|
|
1810
|
+
const method = req.method ?? "GET";
|
|
1811
|
+
switch (`${method} ${url.pathname}`) {
|
|
1812
|
+
case "GET /oauth2/auth":
|
|
1813
|
+
this.authorize(res, url.searchParams);
|
|
1814
|
+
return true;
|
|
1815
|
+
case "POST /oauth2/auth/login":
|
|
1816
|
+
this.login(res, await readBody());
|
|
1817
|
+
return true;
|
|
1818
|
+
case "POST /oauth2/token":
|
|
1819
|
+
await this.token(req, res, await readBody());
|
|
1820
|
+
return true;
|
|
1821
|
+
case "GET /oauth2/v2/user_profile":
|
|
1822
|
+
await this.profile(req, res);
|
|
1823
|
+
return true;
|
|
1824
|
+
case "POST /oauth2/revoke":
|
|
1825
|
+
this.revoke(res, await readBody());
|
|
1826
|
+
return true;
|
|
1827
|
+
case "GET /logout":
|
|
1828
|
+
this.logout(res, url.searchParams);
|
|
1829
|
+
return true;
|
|
1830
|
+
default:
|
|
1831
|
+
return false;
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
authorize(res, params) {
|
|
1835
|
+
let request;
|
|
1836
|
+
try {
|
|
1837
|
+
request = parseAuthorizeRequest(params);
|
|
1838
|
+
} catch (error) {
|
|
1839
|
+
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
1840
|
+
}
|
|
1841
|
+
if (params.get("prompt") === "none") {
|
|
1842
|
+
this.observe("session.silent");
|
|
1843
|
+
return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
1844
|
+
}
|
|
1845
|
+
sendHtml(
|
|
1846
|
+
res,
|
|
1847
|
+
200,
|
|
1848
|
+
renderSignIn({
|
|
1849
|
+
request: encodeRequest(request),
|
|
1850
|
+
users: this.loginPageUsers(),
|
|
1851
|
+
loginHint: request.loginHint ?? void 0,
|
|
1852
|
+
requiredOrganization: request.orgCode ?? void 0
|
|
1853
|
+
})
|
|
1854
|
+
);
|
|
1855
|
+
}
|
|
1856
|
+
login(res, form2) {
|
|
1857
|
+
let request;
|
|
1858
|
+
try {
|
|
1859
|
+
request = decodeRequest(form2.request ?? "");
|
|
1860
|
+
} catch {
|
|
1861
|
+
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
1862
|
+
}
|
|
1863
|
+
const encoded = encodeRequest(request);
|
|
1864
|
+
const ref = (form2.user || form2.email || "").trim();
|
|
1865
|
+
if (!ref) {
|
|
1866
|
+
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." }));
|
|
1867
|
+
}
|
|
1868
|
+
const user = this.resolveUser(ref);
|
|
1869
|
+
if (!user) {
|
|
1870
|
+
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
1871
|
+
}
|
|
1872
|
+
if (this.directory?.isSuspended(user.id)) {
|
|
1873
|
+
this.observe("identity.suspended");
|
|
1874
|
+
return sendHtml(
|
|
1875
|
+
res,
|
|
1876
|
+
403,
|
|
1877
|
+
renderSignIn({
|
|
1878
|
+
request: encoded,
|
|
1879
|
+
users: this.loginPageUsers(),
|
|
1880
|
+
requiredOrganization: request.orgCode ?? void 0,
|
|
1881
|
+
error: `${user.email ?? user.id} is suspended and cannot sign in.`
|
|
1882
|
+
})
|
|
1883
|
+
);
|
|
1884
|
+
}
|
|
1885
|
+
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
1886
|
+
const wanted = request.orgCode ?? form2.org ?? null;
|
|
1887
|
+
let organizationCode = null;
|
|
1888
|
+
if (wanted) {
|
|
1889
|
+
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
1890
|
+
this.observe("organization.non-member");
|
|
1891
|
+
return sendHtml(
|
|
1892
|
+
res,
|
|
1893
|
+
403,
|
|
1894
|
+
renderSignIn({
|
|
1895
|
+
request: encoded,
|
|
1896
|
+
users: this.loginPageUsers(),
|
|
1897
|
+
requiredOrganization: request.orgCode ?? void 0,
|
|
1898
|
+
error: `${user.email ?? user.id} is not a member of ${wanted}.`
|
|
1899
|
+
})
|
|
1900
|
+
);
|
|
1901
|
+
}
|
|
1902
|
+
organizationCode = wanted;
|
|
1903
|
+
} else if (memberships.length === 1) {
|
|
1904
|
+
organizationCode = memberships[0].organizationCode;
|
|
1905
|
+
} else if (memberships.length > 1) {
|
|
1906
|
+
return sendHtml(
|
|
1907
|
+
res,
|
|
1908
|
+
200,
|
|
1909
|
+
renderOrganizationPicker({
|
|
1910
|
+
request: encoded,
|
|
1911
|
+
user,
|
|
1912
|
+
organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
1913
|
+
})
|
|
1914
|
+
);
|
|
1915
|
+
}
|
|
1916
|
+
const membership = memberships.find((m) => m.organizationCode === organizationCode);
|
|
1917
|
+
const scenario = {
|
|
1918
|
+
kind: "authenticated",
|
|
1919
|
+
user,
|
|
1920
|
+
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
1921
|
+
roles: [...membership?.roles ?? []],
|
|
1922
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
1923
|
+
claims: {}
|
|
1924
|
+
};
|
|
1925
|
+
const code = randomToken();
|
|
1926
|
+
this.codes.set(code, {
|
|
1927
|
+
clientId: request.clientId,
|
|
1928
|
+
redirectUri: request.redirectUri,
|
|
1929
|
+
scenario,
|
|
1930
|
+
scope: request.scope,
|
|
1931
|
+
audience: request.audience,
|
|
1932
|
+
nonce: request.nonce,
|
|
1933
|
+
authTime: Math.floor(Date.now() / 1e3),
|
|
1934
|
+
codeChallenge: request.codeChallenge,
|
|
1935
|
+
codeChallengeMethod: request.codeChallengeMethod,
|
|
1936
|
+
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
1937
|
+
});
|
|
1938
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
1939
|
+
this.emit("user.authenticated", user);
|
|
1940
|
+
const target = new URL(request.redirectUri);
|
|
1941
|
+
target.searchParams.set("code", code);
|
|
1942
|
+
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
1943
|
+
redirect(res, target.toString());
|
|
1944
|
+
}
|
|
1945
|
+
async token(req, res, form2) {
|
|
1946
|
+
try {
|
|
1947
|
+
const clientId = clientIdFrom(req, form2);
|
|
1948
|
+
const grantType = form2.grant_type;
|
|
1949
|
+
if (grantType === "client_credentials") {
|
|
1950
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
|
|
1951
|
+
}
|
|
1952
|
+
let grant;
|
|
1953
|
+
if (grantType === "authorization_code") {
|
|
1954
|
+
grant = this.redeemCode(form2, clientId);
|
|
1955
|
+
this.observe("session.sign-in");
|
|
1956
|
+
} else if (grantType === "refresh_token") {
|
|
1957
|
+
grant = this.redeemRefreshToken(form2, clientId);
|
|
1958
|
+
this.observe("session.refresh");
|
|
1959
|
+
} else {
|
|
1960
|
+
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
1961
|
+
}
|
|
1962
|
+
sendJson(res, 200, await this.issueTokens(grant));
|
|
1963
|
+
} catch (error) {
|
|
1964
|
+
if (error instanceof OAuthError) {
|
|
1965
|
+
return sendJson(res, error.status, { error: error.error, error_description: error.message });
|
|
1966
|
+
}
|
|
1967
|
+
throw error;
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
async clientCredentials(clientId, clientSecret, form2) {
|
|
1971
|
+
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
1972
|
+
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
1973
|
+
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
1974
|
+
}
|
|
1975
|
+
const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
|
|
1976
|
+
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1977
|
+
const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
|
|
1978
|
+
return {
|
|
1979
|
+
access_token: await this.testkit.m2mToken({
|
|
1980
|
+
clientId,
|
|
1981
|
+
organizationCode: app?.organizationCode ?? null,
|
|
1982
|
+
scopes: requested,
|
|
1983
|
+
grantedScopes: granted,
|
|
1984
|
+
audience: audience.length > 0 ? audience : app?.audience ?? void 0,
|
|
1985
|
+
permissions: app?.permissions ?? void 0
|
|
1986
|
+
}),
|
|
1987
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
1988
|
+
scope: granted.join(" "),
|
|
1989
|
+
token_type: "bearer"
|
|
1990
|
+
};
|
|
1991
|
+
}
|
|
1992
|
+
reset() {
|
|
1993
|
+
this.codes.clear();
|
|
1994
|
+
this.refreshTokens.clear();
|
|
1995
|
+
this.signedUpUsers.clear();
|
|
1996
|
+
}
|
|
1997
|
+
redeemCode(form2, clientId) {
|
|
1998
|
+
const code = form2.code ?? "";
|
|
1999
|
+
const pending = this.codes.get(code);
|
|
2000
|
+
this.codes.delete(code);
|
|
2001
|
+
if (!pending || pending.expiresAt < Date.now()) {
|
|
2002
|
+
throw new OAuthError(400, "invalid_grant", "The authorization code is unknown, expired or already used.");
|
|
2003
|
+
}
|
|
2004
|
+
if (pending.clientId !== clientId) {
|
|
2005
|
+
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
2006
|
+
}
|
|
2007
|
+
if (form2.redirect_uri !== pending.redirectUri) {
|
|
2008
|
+
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
2009
|
+
}
|
|
2010
|
+
if (pending.codeChallenge) {
|
|
2011
|
+
const verifier = form2.code_verifier ?? "";
|
|
2012
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
2013
|
+
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
2014
|
+
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
return pending;
|
|
2018
|
+
}
|
|
2019
|
+
redeemRefreshToken(form2, clientId) {
|
|
2020
|
+
const token = form2.refresh_token ?? "";
|
|
2021
|
+
const grant = this.refreshTokens.get(token);
|
|
2022
|
+
this.refreshTokens.delete(token);
|
|
2023
|
+
if (!grant) {
|
|
2024
|
+
throw new OAuthError(400, "invalid_grant", "The refresh token is unknown, revoked or already used.");
|
|
2025
|
+
}
|
|
2026
|
+
if (grant.clientId !== clientId) {
|
|
2027
|
+
throw new OAuthError(400, "invalid_grant", "The refresh token was issued to a different client.");
|
|
2028
|
+
}
|
|
2029
|
+
return grant;
|
|
2030
|
+
}
|
|
2031
|
+
async issueTokens(grant) {
|
|
2032
|
+
const { scenario } = grant;
|
|
2033
|
+
const body = {
|
|
2034
|
+
access_token: await this.testkit.token({
|
|
2035
|
+
subject: scenario.user.id,
|
|
2036
|
+
organizationCode: scenario.organization?.code ?? null,
|
|
2037
|
+
roles: scenario.roles.length > 0 ? scenario.roles : void 0,
|
|
2038
|
+
permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
|
|
2039
|
+
scopes: grant.scope,
|
|
2040
|
+
clientId: grant.clientId,
|
|
2041
|
+
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
2042
|
+
authTime: grant.authTime,
|
|
2043
|
+
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
2044
|
+
}),
|
|
2045
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
2046
|
+
scope: grant.scope.join(" "),
|
|
2047
|
+
token_type: "bearer"
|
|
2048
|
+
};
|
|
2049
|
+
if (grant.scope.includes("openid")) {
|
|
2050
|
+
body.id_token = await this.testkit.idTokenFor(scenario, {
|
|
2051
|
+
clientId: grant.clientId,
|
|
2052
|
+
nonce: grant.nonce ?? void 0,
|
|
2053
|
+
authTime: grant.authTime
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
if (grant.scope.includes("offline")) {
|
|
2057
|
+
const refreshToken = randomToken();
|
|
2058
|
+
this.refreshTokens.set(refreshToken, { ...grant, nonce: null });
|
|
2059
|
+
body.refresh_token = refreshToken;
|
|
2060
|
+
}
|
|
2061
|
+
return body;
|
|
2062
|
+
}
|
|
2063
|
+
async profile(req, res) {
|
|
2064
|
+
const header = req.headers.authorization ?? "";
|
|
2065
|
+
if (!header.startsWith("Bearer ")) {
|
|
2066
|
+
return sendJson(res, 401, { error: "invalid_token", error_description: "Send the access token as a Bearer token." });
|
|
2067
|
+
}
|
|
2068
|
+
let sub;
|
|
2069
|
+
try {
|
|
2070
|
+
sub = String((await this.testkit.verify(header.slice(7))).sub ?? "");
|
|
2071
|
+
} catch {
|
|
2072
|
+
return sendJson(res, 401, { error: "invalid_token", error_description: "The access token is not valid for this issuer." });
|
|
2073
|
+
}
|
|
2074
|
+
const user = this.seed.users.find((u) => u.id === sub) ?? this.signedUpUsers.get(sub);
|
|
2075
|
+
if (!user) {
|
|
2076
|
+
return sendJson(res, 404, { error: "not_found", error_description: `No user has the id ${sub}.` });
|
|
2077
|
+
}
|
|
2078
|
+
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
2079
|
+
sendJson(res, 200, {
|
|
2080
|
+
id: user.id,
|
|
2081
|
+
sub: user.id,
|
|
2082
|
+
provided_id: null,
|
|
2083
|
+
name: name || null,
|
|
2084
|
+
given_name: user.givenName,
|
|
2085
|
+
family_name: user.familyName,
|
|
2086
|
+
updated_at: Math.floor(Date.now() / 1e3),
|
|
2087
|
+
email: user.email,
|
|
2088
|
+
email_verified: user.emailVerified,
|
|
2089
|
+
picture: user.picture,
|
|
2090
|
+
preferred_username: null,
|
|
2091
|
+
phone: null
|
|
2092
|
+
});
|
|
2093
|
+
}
|
|
2094
|
+
revoke(res, form2) {
|
|
2095
|
+
if (form2.token) this.refreshTokens.delete(form2.token);
|
|
2096
|
+
this.observe("session.revoke");
|
|
2097
|
+
sendJson(res, 200, {});
|
|
2098
|
+
}
|
|
2099
|
+
logout(res, params) {
|
|
2100
|
+
this.observe("session.sign-out");
|
|
2101
|
+
const target = params.get("redirect");
|
|
2102
|
+
if (target && isHttpUrl2(target)) return redirect(res, target);
|
|
2103
|
+
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
2104
|
+
}
|
|
2105
|
+
resolveUser(ref) {
|
|
2106
|
+
const seeded = findUser(this.seed.users, ref);
|
|
2107
|
+
if (seeded) return seeded;
|
|
2108
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
2109
|
+
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
2110
|
+
if (!this.signedUpUsers.has(user.id)) {
|
|
2111
|
+
this.signedUpUsers.set(user.id, user);
|
|
2112
|
+
this.observe("identity.unseeded");
|
|
2113
|
+
if (this.directory) this.seed.users.push(user);
|
|
2114
|
+
this.emit("user.created", user);
|
|
2115
|
+
}
|
|
2116
|
+
return this.signedUpUsers.get(user.id);
|
|
2117
|
+
}
|
|
2118
|
+
organization(code) {
|
|
2119
|
+
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
2120
|
+
}
|
|
2121
|
+
loginPageUsers() {
|
|
2122
|
+
return this.seed.users.map((user) => ({
|
|
2123
|
+
user,
|
|
2124
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
2125
|
+
}));
|
|
2126
|
+
}
|
|
2127
|
+
};
|
|
2128
|
+
function parseAuthorizeRequest(params) {
|
|
2129
|
+
const clientId = params.get("client_id");
|
|
2130
|
+
const redirectUri = params.get("redirect_uri");
|
|
2131
|
+
if (!clientId) throw new Error("client_id is missing.");
|
|
2132
|
+
if (!redirectUri || !isHttpUrl2(redirectUri)) {
|
|
2133
|
+
throw new Error("redirect_uri must be an absolute http or https URL.");
|
|
2134
|
+
}
|
|
2135
|
+
if (params.get("response_type") !== "code") {
|
|
2136
|
+
throw new Error('response_type must be "code".');
|
|
2137
|
+
}
|
|
2138
|
+
const method = params.get("code_challenge_method");
|
|
2139
|
+
const challenge = params.get("code_challenge");
|
|
2140
|
+
if (challenge && method && method !== "S256" && method !== "plain") {
|
|
2141
|
+
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
2142
|
+
}
|
|
2143
|
+
return {
|
|
2144
|
+
clientId,
|
|
2145
|
+
redirectUri,
|
|
2146
|
+
state: params.get("state"),
|
|
2147
|
+
scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
|
|
2148
|
+
nonce: params.get("nonce"),
|
|
2149
|
+
audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
|
|
2150
|
+
orgCode: params.get("org_code"),
|
|
2151
|
+
loginHint: params.get("login_hint"),
|
|
2152
|
+
codeChallenge: challenge,
|
|
2153
|
+
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
2154
|
+
};
|
|
2155
|
+
}
|
|
2156
|
+
function encodeRequest(request) {
|
|
2157
|
+
return Buffer.from(JSON.stringify(request)).toString("base64url");
|
|
2158
|
+
}
|
|
2159
|
+
function decodeRequest(value) {
|
|
2160
|
+
const request = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
2161
|
+
if (!request.clientId || !request.redirectUri || !isHttpUrl2(request.redirectUri)) {
|
|
2162
|
+
throw new Error("invalid request");
|
|
2163
|
+
}
|
|
2164
|
+
return request;
|
|
2165
|
+
}
|
|
2166
|
+
function clientIdFrom(req, form2) {
|
|
2167
|
+
const header = req.headers.authorization ?? "";
|
|
2168
|
+
if (header.startsWith("Basic ")) {
|
|
2169
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
2170
|
+
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
2171
|
+
if (id) return id;
|
|
2172
|
+
}
|
|
2173
|
+
if (form2.client_id) return form2.client_id;
|
|
2174
|
+
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
2175
|
+
}
|
|
2176
|
+
function clientSecretFrom(req, form2) {
|
|
2177
|
+
const header = req.headers.authorization ?? "";
|
|
2178
|
+
if (header.startsWith("Basic ")) {
|
|
2179
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
2180
|
+
const index = decoded.indexOf(":");
|
|
2181
|
+
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
2182
|
+
}
|
|
2183
|
+
return form2.client_secret ?? null;
|
|
2184
|
+
}
|
|
2185
|
+
function redirectWithError(res, request, error, description) {
|
|
2186
|
+
const target = new URL(request.redirectUri);
|
|
2187
|
+
target.searchParams.set("error", error);
|
|
2188
|
+
target.searchParams.set("error_description", description);
|
|
2189
|
+
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
2190
|
+
redirect(res, target.toString());
|
|
2191
|
+
}
|
|
2192
|
+
function isHttpUrl2(value) {
|
|
2193
|
+
try {
|
|
2194
|
+
const { protocol } = new URL(value);
|
|
2195
|
+
return protocol === "http:" || protocol === "https:";
|
|
2196
|
+
} catch {
|
|
2197
|
+
return false;
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
function randomToken() {
|
|
2201
|
+
return randomBytes4(32).toString("base64url");
|
|
2202
|
+
}
|
|
2203
|
+
function safeEqual(a, b) {
|
|
2204
|
+
const left = Buffer.from(a);
|
|
2205
|
+
const right = Buffer.from(b);
|
|
2206
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
2207
|
+
}
|
|
2208
|
+
function redirect(res, location) {
|
|
2209
|
+
res.writeHead(303, { location, "cache-control": "no-store" });
|
|
2210
|
+
res.end();
|
|
2211
|
+
}
|
|
2212
|
+
function sendHtml(res, status, html) {
|
|
2213
|
+
res.writeHead(status, {
|
|
2214
|
+
"content-type": "text/html; charset=utf-8",
|
|
2215
|
+
"cache-control": "no-store",
|
|
2216
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
2217
|
+
});
|
|
2218
|
+
res.end(html);
|
|
2219
|
+
}
|
|
2220
|
+
function sendJson(res, status, body) {
|
|
2221
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
2222
|
+
res.end(JSON.stringify(body));
|
|
2223
|
+
}
|
|
2224
|
+
|
|
2225
|
+
// src/account.ts
|
|
2226
|
+
var DEFAULT_PAGE_SIZE = 10;
|
|
2227
|
+
var AccountApi = class {
|
|
2228
|
+
constructor(testkit, directory) {
|
|
2229
|
+
this.testkit = testkit;
|
|
2230
|
+
this.directory = directory;
|
|
2231
|
+
}
|
|
2232
|
+
testkit;
|
|
2233
|
+
directory;
|
|
2234
|
+
async handle(req, res, url) {
|
|
2235
|
+
if (!url.pathname.startsWith("/account_api/v1/")) return false;
|
|
2236
|
+
if ((req.method ?? "GET") !== "GET") {
|
|
2237
|
+
sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
|
|
2238
|
+
return true;
|
|
2239
|
+
}
|
|
2240
|
+
const header = req.headers.authorization ?? "";
|
|
2241
|
+
let token;
|
|
2242
|
+
try {
|
|
2243
|
+
if (!header.startsWith("Bearer ")) throw new Error("missing");
|
|
2244
|
+
token = await this.testkit.verify(header.slice(7));
|
|
2245
|
+
} catch {
|
|
2246
|
+
sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
|
|
2247
|
+
return true;
|
|
2248
|
+
}
|
|
2249
|
+
if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
|
|
2250
|
+
sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
|
|
2251
|
+
return true;
|
|
2252
|
+
}
|
|
2253
|
+
const userId = token.sub;
|
|
2254
|
+
const orgCode = typeof token.org_code === "string" ? token.org_code : null;
|
|
2255
|
+
const path = url.pathname.slice("/account_api/v1/".length);
|
|
2256
|
+
const d = this.directory;
|
|
2257
|
+
const membership = orgCode ? d.membership(userId, orgCode) : void 0;
|
|
2258
|
+
if (path === "permissions") {
|
|
2259
|
+
const items = effectivePermissions(d.seed, membership).map((key) => {
|
|
2260
|
+
const p = d.ensurePermission(key);
|
|
2261
|
+
return { id: p.id, name: p.name, key: p.key };
|
|
2262
|
+
});
|
|
2263
|
+
sendPage(res, url, "permissions", items, { org_code: orgCode });
|
|
2264
|
+
return true;
|
|
2265
|
+
}
|
|
2266
|
+
if (path.startsWith("permission/")) {
|
|
2267
|
+
const key = decodeURIComponent(path.slice("permission/".length));
|
|
2268
|
+
sendJson2(res, 200, {
|
|
2269
|
+
data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
|
|
2270
|
+
});
|
|
2271
|
+
return true;
|
|
2272
|
+
}
|
|
2273
|
+
if (path === "roles") {
|
|
2274
|
+
const items = (membership?.roles ?? []).map((key) => {
|
|
2275
|
+
const r = d.ensureRole(key);
|
|
2276
|
+
return { id: r.id, name: r.name, key: r.key };
|
|
2277
|
+
});
|
|
2278
|
+
sendPage(res, url, "roles", items, { org_code: orgCode });
|
|
2279
|
+
return true;
|
|
2280
|
+
}
|
|
2281
|
+
if (path === "feature_flags") {
|
|
2282
|
+
const items = d.seed.featureFlags.map((flag) => ({
|
|
2283
|
+
id: flag.id,
|
|
2284
|
+
name: flag.name,
|
|
2285
|
+
key: flag.key,
|
|
2286
|
+
type: flag.type,
|
|
2287
|
+
value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
|
|
2288
|
+
}));
|
|
2289
|
+
sendPage(res, url, "feature_flags", items, {});
|
|
2290
|
+
return true;
|
|
2291
|
+
}
|
|
2292
|
+
if (path === "properties") {
|
|
2293
|
+
const values = d.seed.userProperties[userId] ?? {};
|
|
2294
|
+
const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
|
|
2295
|
+
sendPage(res, url, "properties", items, {});
|
|
2296
|
+
return true;
|
|
2297
|
+
}
|
|
2298
|
+
if (path === "entitlements" || path.startsWith("entitlement")) {
|
|
2299
|
+
const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
|
|
2300
|
+
const entitlements = (plan?.entitlements ?? []).map((e) => ({
|
|
2301
|
+
id: e.id,
|
|
2302
|
+
fixed_charge: e.fixedCharge,
|
|
2303
|
+
price_name: e.priceName,
|
|
2304
|
+
unit_amount: e.unitAmount,
|
|
2305
|
+
feature_key: e.featureKey,
|
|
2306
|
+
feature_name: e.featureName,
|
|
2307
|
+
entitlement_limit_max: e.limitMax,
|
|
2308
|
+
entitlement_limit_min: e.limitMin
|
|
2309
|
+
}));
|
|
2310
|
+
if (path === "entitlements") {
|
|
2311
|
+
const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
|
|
2312
|
+
sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
|
|
2313
|
+
return true;
|
|
2314
|
+
}
|
|
2315
|
+
const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
|
|
2316
|
+
const entitlement = entitlements.find((e) => e.feature_key === key);
|
|
2317
|
+
if (!entitlement) {
|
|
2318
|
+
sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
|
|
2319
|
+
} else {
|
|
2320
|
+
sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
|
|
2321
|
+
}
|
|
2322
|
+
return true;
|
|
2323
|
+
}
|
|
2324
|
+
if (path === "portal_link") {
|
|
2325
|
+
sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
|
|
2326
|
+
return true;
|
|
2327
|
+
}
|
|
2328
|
+
sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
|
|
2329
|
+
return true;
|
|
2330
|
+
}
|
|
2331
|
+
};
|
|
2332
|
+
function sendPage(res, url, field, items, extra) {
|
|
2333
|
+
const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
|
|
2334
|
+
const after = url.searchParams.get("starting_after");
|
|
2335
|
+
const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
|
|
2336
|
+
const page = items.slice(start, start + size);
|
|
2337
|
+
const hasMore = start + size < items.length;
|
|
2338
|
+
sendJson2(res, 200, {
|
|
2339
|
+
data: { ...extra, [field]: page },
|
|
2340
|
+
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
2341
|
+
});
|
|
2342
|
+
}
|
|
2343
|
+
function errors(code, message) {
|
|
2344
|
+
return { errors: [{ code, message }] };
|
|
2345
|
+
}
|
|
2346
|
+
function sendJson2(res, status, body) {
|
|
2347
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
2348
|
+
res.end(JSON.stringify(body));
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
// src/management.ts
|
|
2352
|
+
var OK = { code: "OK", message: "Success" };
|
|
2353
|
+
var DEFAULT_PAGE_SIZE2 = 10;
|
|
2354
|
+
var MAX_PAGE_SIZE = 500;
|
|
2355
|
+
var ManagementApi = class {
|
|
2356
|
+
constructor(testkit, directory, webhooks) {
|
|
2357
|
+
this.testkit = testkit;
|
|
2358
|
+
this.directory = directory;
|
|
2359
|
+
this.webhooks = webhooks;
|
|
2360
|
+
this.register();
|
|
2361
|
+
}
|
|
2362
|
+
testkit;
|
|
2363
|
+
directory;
|
|
2364
|
+
webhooks;
|
|
2365
|
+
routes = [];
|
|
2366
|
+
async handle(req, res, url, readBody) {
|
|
2367
|
+
if (!url.pathname.startsWith("/api/v1/")) return false;
|
|
2368
|
+
const method = req.method ?? "GET";
|
|
2369
|
+
const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
2370
|
+
if (!route) {
|
|
2371
|
+
sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
|
|
2372
|
+
return true;
|
|
2373
|
+
}
|
|
2374
|
+
const token = await this.authenticate(req.headers.authorization);
|
|
2375
|
+
if ("error" in token) {
|
|
2376
|
+
sendJson3(res, 403, errors2(token.code, token.error));
|
|
2377
|
+
return true;
|
|
2378
|
+
}
|
|
2379
|
+
const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
|
|
2380
|
+
if (granted.length > 0 && !granted.includes(route.scope)) {
|
|
2381
|
+
sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
|
|
2382
|
+
return true;
|
|
2383
|
+
}
|
|
2384
|
+
const match = route.pattern.exec(url.pathname);
|
|
2385
|
+
const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
|
|
2386
|
+
const body = method === "GET" || method === "DELETE" ? {} : await readBody();
|
|
2387
|
+
const [status, payload] = await route.handler({ params, query: url.searchParams, body });
|
|
2388
|
+
sendJson3(res, status, payload);
|
|
2389
|
+
return true;
|
|
2390
|
+
}
|
|
2391
|
+
async authenticate(header) {
|
|
2392
|
+
if (!header?.startsWith("Bearer ")) {
|
|
2393
|
+
return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
|
|
2394
|
+
}
|
|
2395
|
+
let payload;
|
|
2396
|
+
try {
|
|
2397
|
+
payload = await this.testkit.verify(header.slice(7));
|
|
2398
|
+
} catch {
|
|
2399
|
+
return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
|
|
2400
|
+
}
|
|
2401
|
+
const audience = `${this.testkit.issuer}/api`;
|
|
2402
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
2403
|
+
if (!aud.includes(audience)) {
|
|
2404
|
+
return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
|
|
2405
|
+
}
|
|
2406
|
+
if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
|
|
2407
|
+
return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
|
|
2408
|
+
}
|
|
2409
|
+
return { payload };
|
|
2410
|
+
}
|
|
2411
|
+
route(method, path, scope, handler) {
|
|
2412
|
+
const keys = [];
|
|
2413
|
+
const pattern = new RegExp(
|
|
2414
|
+
`^${path.replace(/\{(\w+)\}/g, (_, key) => {
|
|
2415
|
+
keys.push(key);
|
|
2416
|
+
return "([^/]+)";
|
|
2417
|
+
})}$`
|
|
2418
|
+
);
|
|
2419
|
+
this.routes.push({ method, pattern, keys, scope, handler });
|
|
2420
|
+
}
|
|
2421
|
+
register() {
|
|
2422
|
+
const d = this.directory;
|
|
2423
|
+
this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
|
|
2424
|
+
let users = [...d.seed.users];
|
|
2425
|
+
const userId = query.get("user_id");
|
|
2426
|
+
const email = query.get("email")?.toLowerCase();
|
|
2427
|
+
if (userId) users = users.filter((u) => u.id === userId);
|
|
2428
|
+
if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
|
|
2429
|
+
const page = paginate(users, query);
|
|
2430
|
+
return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
|
|
2431
|
+
});
|
|
2432
|
+
this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
|
|
2433
|
+
const user = d.user(query.get("id") ?? "");
|
|
2434
|
+
return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
|
|
2435
|
+
});
|
|
2436
|
+
this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
|
|
2437
|
+
const profile = body.profile ?? {};
|
|
2438
|
+
const identities = Array.isArray(body.identities) ? body.identities : [];
|
|
2439
|
+
const emailIdentity = identities.find((i) => i.type === "email");
|
|
2440
|
+
const email = (emailIdentity?.details ?? {}).email;
|
|
2441
|
+
if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
|
|
2442
|
+
return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
|
|
2443
|
+
}
|
|
2444
|
+
const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
|
|
2445
|
+
if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
|
|
2446
|
+
const user = d.createUser({
|
|
2447
|
+
email: typeof email === "string" ? email : null,
|
|
2448
|
+
givenName: str(profile.given_name),
|
|
2449
|
+
familyName: str(profile.family_name),
|
|
2450
|
+
picture: str(profile.picture),
|
|
2451
|
+
providedId: str(body.provided_id)
|
|
2452
|
+
});
|
|
2453
|
+
if (orgCode) d.addMembership(user.id, orgCode);
|
|
2454
|
+
this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
|
|
2455
|
+
return [
|
|
2456
|
+
200,
|
|
2457
|
+
{ id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
|
|
2458
|
+
];
|
|
2459
|
+
});
|
|
2460
|
+
this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
|
|
2461
|
+
const user = d.user(query.get("id") ?? "");
|
|
2462
|
+
if (!user) return notFound("USER_INVALID", "No user has that id.");
|
|
2463
|
+
if (typeof body.given_name === "string") user.givenName = body.given_name;
|
|
2464
|
+
if (typeof body.family_name === "string") user.familyName = body.family_name;
|
|
2465
|
+
if (typeof body.picture === "string") user.picture = body.picture;
|
|
2466
|
+
const meta = d.meta(user);
|
|
2467
|
+
if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
|
|
2468
|
+
if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
|
|
2469
|
+
if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
|
|
2470
|
+
this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
|
|
2471
|
+
return [
|
|
2472
|
+
200,
|
|
2473
|
+
{
|
|
2474
|
+
id: user.id,
|
|
2475
|
+
given_name: user.givenName,
|
|
2476
|
+
family_name: user.familyName,
|
|
2477
|
+
email: user.email,
|
|
2478
|
+
is_suspended: meta.isSuspended,
|
|
2479
|
+
is_password_reset_requested: meta.isPasswordResetRequested,
|
|
2480
|
+
picture: user.picture
|
|
2481
|
+
}
|
|
2482
|
+
];
|
|
2483
|
+
});
|
|
2484
|
+
this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
|
|
2485
|
+
const id = query.get("id") ?? "";
|
|
2486
|
+
if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
|
|
2487
|
+
this.webhooks.emit("user.deleted", { user: { id } });
|
|
2488
|
+
return [200, OK];
|
|
2489
|
+
});
|
|
2490
|
+
this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
|
|
2491
|
+
const page = paginate(d.seed.organizations, query);
|
|
2492
|
+
return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
|
|
2493
|
+
});
|
|
2494
|
+
this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
|
|
2495
|
+
const org = d.organization(query.get("code") ?? "");
|
|
2496
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
2497
|
+
const meta = d.orgInfo(org);
|
|
2498
|
+
return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
|
|
2499
|
+
});
|
|
2500
|
+
this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
|
|
2501
|
+
if (typeof body.name !== "string" || body.name.trim() === "") {
|
|
2502
|
+
return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
|
|
2503
|
+
}
|
|
2504
|
+
const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
|
|
2505
|
+
if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
|
|
2506
|
+
this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
|
|
2507
|
+
return [200, { ...OK, organization: { code: org.code } }];
|
|
2508
|
+
});
|
|
2509
|
+
this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
|
|
2510
|
+
const org = d.organization(params.org_code);
|
|
2511
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
2512
|
+
const meta = d.orgInfo(org);
|
|
2513
|
+
if (typeof body.name === "string") org.name = body.name;
|
|
2514
|
+
if (typeof body.external_id === "string") meta.externalId = body.external_id;
|
|
2515
|
+
if (typeof body.handle === "string") meta.handle = body.handle;
|
|
2516
|
+
if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
|
|
2517
|
+
this.webhooks.emit("organization.updated", {
|
|
2518
|
+
organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
|
|
2519
|
+
});
|
|
2520
|
+
return [200, OK];
|
|
2521
|
+
});
|
|
2522
|
+
this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
|
|
2523
|
+
if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
2524
|
+
this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
|
|
2525
|
+
return [200, OK];
|
|
2526
|
+
});
|
|
2527
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
|
|
2528
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
2529
|
+
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);
|
|
2530
|
+
const page = paginate(members, query);
|
|
2531
|
+
return [
|
|
2532
|
+
200,
|
|
2533
|
+
{
|
|
2534
|
+
...OK,
|
|
2535
|
+
organization_users: page.items.map(({ membership, user }) => ({
|
|
2536
|
+
id: user.id,
|
|
2537
|
+
email: user.email,
|
|
2538
|
+
full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
|
|
2539
|
+
last_name: user.familyName,
|
|
2540
|
+
first_name: user.givenName,
|
|
2541
|
+
picture: user.picture,
|
|
2542
|
+
joined_on: d.meta(user).createdOn,
|
|
2543
|
+
last_accessed_on: d.meta(user).lastSignedIn,
|
|
2544
|
+
is_suspended: d.meta(user).isSuspended,
|
|
2545
|
+
roles: [...membership.roles]
|
|
2546
|
+
})),
|
|
2547
|
+
next_token: page.nextToken
|
|
2548
|
+
}
|
|
2549
|
+
];
|
|
2550
|
+
});
|
|
2551
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
|
|
2552
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
2553
|
+
const users = Array.isArray(body.users) ? body.users : [];
|
|
2554
|
+
const added = [];
|
|
2555
|
+
const blocked = [];
|
|
2556
|
+
for (const entry of users) {
|
|
2557
|
+
const id = typeof entry.id === "string" ? entry.id : "";
|
|
2558
|
+
if (!d.user(id)) {
|
|
2559
|
+
blocked.push(id);
|
|
2560
|
+
continue;
|
|
2561
|
+
}
|
|
2562
|
+
d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
|
|
2563
|
+
added.push(id);
|
|
2564
|
+
}
|
|
2565
|
+
return [200, { ...OK, users_added: added, users_blocked: blocked }];
|
|
2566
|
+
});
|
|
2567
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
|
|
2568
|
+
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}.`);
|
|
2569
|
+
});
|
|
2570
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
|
|
2571
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
2572
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
2573
|
+
const roles = membership.roles.map((key) => d.ensureRole(key));
|
|
2574
|
+
return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
|
|
2575
|
+
});
|
|
2576
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
|
|
2577
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
2578
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
2579
|
+
const role = d.role(str(body.role_id) ?? "");
|
|
2580
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
2581
|
+
if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
|
|
2582
|
+
return [200, OK];
|
|
2583
|
+
});
|
|
2584
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
|
|
2585
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
2586
|
+
const role = d.role(params.role_id);
|
|
2587
|
+
if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
|
|
2588
|
+
membership.roles = membership.roles.filter((key) => key !== role.key);
|
|
2589
|
+
return [200, OK];
|
|
2590
|
+
});
|
|
2591
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
|
|
2592
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
2593
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
2594
|
+
const permissions = effectivePermissions(d.seed, membership).map((key) => {
|
|
2595
|
+
const permission = d.ensurePermission(key);
|
|
2596
|
+
const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
|
|
2597
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
|
|
2598
|
+
});
|
|
2599
|
+
return [200, { ...OK, permissions }];
|
|
2600
|
+
});
|
|
2601
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
|
|
2602
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
2603
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
2604
|
+
const permission = d.permission(str(body.permission_id) ?? "");
|
|
2605
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
2606
|
+
if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
|
|
2607
|
+
return [200, OK];
|
|
2608
|
+
});
|
|
2609
|
+
this.route(
|
|
2610
|
+
"DELETE",
|
|
2611
|
+
"/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
|
|
2612
|
+
"delete:organization_user_permissions",
|
|
2613
|
+
({ params }) => {
|
|
2614
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
2615
|
+
const permission = d.permission(params.permission_id);
|
|
2616
|
+
if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
|
|
2617
|
+
membership.permissions = membership.permissions.filter((key) => key !== permission.key);
|
|
2618
|
+
return [200, OK];
|
|
2619
|
+
}
|
|
2620
|
+
);
|
|
2621
|
+
this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
|
|
2622
|
+
const page = paginate(d.seed.roles, query);
|
|
2623
|
+
return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
|
|
2624
|
+
});
|
|
2625
|
+
this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
|
|
2626
|
+
const key = str(body.key);
|
|
2627
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
|
|
2628
|
+
if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
|
|
2629
|
+
const role = d.ensureRole(key, {
|
|
2630
|
+
name: str(body.name) ?? void 0,
|
|
2631
|
+
description: str(body.description) ?? void 0,
|
|
2632
|
+
isDefault: body.is_default_role === true
|
|
2633
|
+
});
|
|
2634
|
+
this.webhooks.emit("role.created", {
|
|
2635
|
+
role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
|
|
2636
|
+
});
|
|
2637
|
+
return [201, { ...OK, role: { id: role.id } }];
|
|
2638
|
+
});
|
|
2639
|
+
this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
|
|
2640
|
+
const role = d.role(params.role_id);
|
|
2641
|
+
return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
|
|
2642
|
+
});
|
|
2643
|
+
this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
|
|
2644
|
+
const role = d.deleteRole(params.role_id);
|
|
2645
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
2646
|
+
this.webhooks.emit("role.deleted", { role: { id: role.id } });
|
|
2647
|
+
return [200, OK];
|
|
2648
|
+
});
|
|
2649
|
+
this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
|
|
2650
|
+
const role = d.role(params.role_id);
|
|
2651
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
2652
|
+
return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
|
|
2653
|
+
});
|
|
2654
|
+
this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
|
|
2655
|
+
const page = paginate(d.seed.permissions, query);
|
|
2656
|
+
return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
|
|
2657
|
+
});
|
|
2658
|
+
this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
|
|
2659
|
+
const key = str(body.key);
|
|
2660
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
|
|
2661
|
+
if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
|
|
2662
|
+
const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
|
|
2663
|
+
this.webhooks.emit("permission.created", {
|
|
2664
|
+
permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
|
|
2665
|
+
});
|
|
2666
|
+
return [201, OK];
|
|
2667
|
+
});
|
|
2668
|
+
this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
|
|
2669
|
+
const permission = d.deletePermission(params.permission_id);
|
|
2670
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
2671
|
+
this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
|
|
2672
|
+
return [200, OK];
|
|
2673
|
+
});
|
|
2674
|
+
}
|
|
2675
|
+
userListItem(user) {
|
|
2676
|
+
const meta = this.directory.meta(user);
|
|
2677
|
+
return {
|
|
2678
|
+
id: user.id,
|
|
2679
|
+
provided_id: meta.providedId,
|
|
2680
|
+
email: user.email,
|
|
2681
|
+
phone: null,
|
|
2682
|
+
username: null,
|
|
2683
|
+
last_name: user.familyName,
|
|
2684
|
+
first_name: user.givenName,
|
|
2685
|
+
is_suspended: meta.isSuspended,
|
|
2686
|
+
picture: user.picture,
|
|
2687
|
+
total_sign_ins: meta.totalSignIns,
|
|
2688
|
+
failed_sign_ins: 0,
|
|
2689
|
+
last_signed_in: meta.lastSignedIn,
|
|
2690
|
+
created_on: meta.createdOn,
|
|
2691
|
+
organizations: this.organizationsOf(user),
|
|
2692
|
+
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
2693
|
+
};
|
|
2694
|
+
}
|
|
2695
|
+
userDetail(user) {
|
|
2696
|
+
const { email, ...rest } = this.userListItem(user);
|
|
2697
|
+
return { ...rest, preferred_email: email };
|
|
2698
|
+
}
|
|
2699
|
+
organizationsOf(user) {
|
|
2700
|
+
return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
|
|
2701
|
+
}
|
|
2702
|
+
organizationItem(org) {
|
|
2703
|
+
const meta = this.directory.orgInfo(org);
|
|
2704
|
+
return {
|
|
2705
|
+
code: org.code,
|
|
2706
|
+
name: org.name,
|
|
2707
|
+
handle: meta.handle,
|
|
2708
|
+
is_default: false,
|
|
2709
|
+
external_id: meta.externalId,
|
|
2710
|
+
is_auto_membership_enabled: false
|
|
2711
|
+
};
|
|
2712
|
+
}
|
|
2713
|
+
organizationEvent(org) {
|
|
2714
|
+
const meta = this.directory.orgInfo(org);
|
|
2715
|
+
return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
|
|
2716
|
+
}
|
|
2717
|
+
roleItem(role) {
|
|
2718
|
+
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
2719
|
+
}
|
|
2720
|
+
permissionItem(permission) {
|
|
2721
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
2722
|
+
}
|
|
2723
|
+
};
|
|
2724
|
+
function paginate(items, query) {
|
|
2725
|
+
const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
|
|
2726
|
+
const token = query.get("next_token");
|
|
2727
|
+
const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
|
|
2728
|
+
const page = items.slice(offset, offset + size);
|
|
2729
|
+
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
2730
|
+
return { items: page, nextToken: next };
|
|
2731
|
+
}
|
|
2732
|
+
function errors2(code, message) {
|
|
2733
|
+
return { errors: [{ code, message }] };
|
|
2734
|
+
}
|
|
2735
|
+
function notFound(code, message) {
|
|
2736
|
+
return [404, errors2(code, message)];
|
|
2737
|
+
}
|
|
2738
|
+
function str(value) {
|
|
2739
|
+
return typeof value === "string" ? value : null;
|
|
2740
|
+
}
|
|
2741
|
+
function strings(value) {
|
|
2742
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
2743
|
+
}
|
|
2744
|
+
function sendJson3(res, status, body) {
|
|
2745
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
2746
|
+
res.end(JSON.stringify(body));
|
|
2747
|
+
}
|
|
2748
|
+
|
|
2749
|
+
// src/dashboard.ts
|
|
2750
|
+
var STYLE2 = `
|
|
2751
|
+
:root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--ok:#1d7a46;--bad:#b42318;--soft:#f0f0ec}
|
|
2752
|
+
@media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--ok:#5cc78a;--bad:#f0817a;--soft:#232327}}
|
|
2753
|
+
*{box-sizing:border-box}
|
|
2754
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
2755
|
+
header{position:sticky;top:0;z-index:1;display:flex;flex-wrap:wrap;gap:16px;align-items:center;justify-content:space-between;padding:14px 28px;background:var(--card);border-bottom:1px solid var(--line)}
|
|
2756
|
+
header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
|
|
2757
|
+
header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2758
|
+
nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
|
|
2759
|
+
nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
|
|
2760
|
+
main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
|
|
2761
|
+
section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
|
|
2762
|
+
h2{margin:0 0 4px;font-size:16px;font-weight:600}
|
|
2763
|
+
.sub{margin:0 0 14px;color:var(--muted);font-size:13px}
|
|
2764
|
+
table{width:100%;border-collapse:collapse;font-size:13px}
|
|
2765
|
+
th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
|
|
2766
|
+
td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
|
|
2767
|
+
tr:last-child td{border-bottom:0}
|
|
2768
|
+
code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2769
|
+
.chips{display:flex;flex-wrap:wrap;gap:4px}
|
|
2770
|
+
.chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
|
|
2771
|
+
.ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
|
|
2772
|
+
.empty{color:var(--muted);font-size:13px;margin:0}
|
|
2773
|
+
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
|
|
2774
|
+
label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
|
|
2775
|
+
input,select{height:32px;padding:0 8px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:13px ui-sans-serif,system-ui,sans-serif}
|
|
2776
|
+
input[type=checkbox]{height:auto}
|
|
2777
|
+
button{height:32px;padding:0 12px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:500 13px ui-sans-serif,system-ui,sans-serif;cursor:pointer}
|
|
2778
|
+
button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
|
|
2779
|
+
button:hover{border-color:var(--muted)}
|
|
2780
|
+
details summary{cursor:pointer;color:var(--muted)}
|
|
2781
|
+
pre{margin:8px 0 0;padding:10px;background:var(--soft);border-radius:6px;overflow:auto;max-height:320px;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-all}
|
|
2782
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
|
|
2783
|
+
.group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
|
|
2784
|
+
.group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
|
|
2785
|
+
.notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
|
|
2786
|
+
.split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
|
|
2787
|
+
`;
|
|
2788
|
+
function renderDashboard(data) {
|
|
2789
|
+
const e = escapeHtml;
|
|
2790
|
+
const { seed } = data;
|
|
2791
|
+
const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
|
|
2792
|
+
const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
|
|
2793
|
+
const users = seed.users.length ? table(
|
|
2794
|
+
["User", "ID", "Organizations", "Sign-ins", "Status"],
|
|
2795
|
+
seed.users.map((user) => [
|
|
2796
|
+
e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
|
|
2797
|
+
`<code>${e(user.id)}</code>`,
|
|
2798
|
+
chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
|
|
2799
|
+
String(data.signIns(user.id)),
|
|
2800
|
+
data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
|
|
2801
|
+
])
|
|
2802
|
+
) : empty("No users yet. Seed some, or sign in with any email.");
|
|
2803
|
+
const organizations = seed.organizations.length ? table(
|
|
2804
|
+
["Organization", "Code", "Members"],
|
|
2805
|
+
seed.organizations.map((org) => [
|
|
2806
|
+
e(org.name),
|
|
2807
|
+
`<code>${e(org.code)}</code>`,
|
|
2808
|
+
String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
|
|
2809
|
+
])
|
|
2810
|
+
) : empty("No organizations.");
|
|
2811
|
+
const memberships = seed.memberships.length ? table(
|
|
2812
|
+
["User", "Organization", "Roles", "Permissions in the token"],
|
|
2813
|
+
seed.memberships.map((m) => [
|
|
2814
|
+
e(userLabel(m.userId)),
|
|
2815
|
+
e(orgName(m.organizationCode)),
|
|
2816
|
+
chips(m.roles),
|
|
2817
|
+
chips(effectivePermissions(seed, m))
|
|
2818
|
+
])
|
|
2819
|
+
) : empty("No memberships.");
|
|
2820
|
+
const applications = seed.applications.length ? table(
|
|
2821
|
+
["Client ID", "Organization", "Scopes"],
|
|
2822
|
+
seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
|
|
2823
|
+
) : "";
|
|
2824
|
+
const tokens = data.tokens.length ? table(
|
|
2825
|
+
["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
|
|
2826
|
+
[...data.tokens].reverse().slice(0, 50).map((t) => [
|
|
2827
|
+
time(t.at),
|
|
2828
|
+
t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
|
|
2829
|
+
`<code>${e(t.subject ?? "none")}</code>`,
|
|
2830
|
+
e(t.organization ?? "none"),
|
|
2831
|
+
chips(t.permissions),
|
|
2832
|
+
`<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
|
|
2833
|
+
])
|
|
2834
|
+
) : empty("No tokens issued yet.");
|
|
2835
|
+
const requests = data.requests.length ? table(
|
|
2836
|
+
["Time", "Request", "Status", "Time taken"],
|
|
2837
|
+
[...data.requests].reverse().slice(0, 100).map((r) => [
|
|
2838
|
+
time(r.at),
|
|
2839
|
+
`<code>${e(r.method)} ${e(r.path)}</code>`,
|
|
2840
|
+
`<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
|
|
2841
|
+
`${r.durationMs} ms`
|
|
2842
|
+
])
|
|
2843
|
+
) : empty("No requests yet.");
|
|
2844
|
+
const deliveries = data.deliveries.length ? table(
|
|
2845
|
+
["Event", "Endpoint", "Copy", "Result"],
|
|
2846
|
+
[...data.deliveries].reverse().slice(0, 50).map((d) => [
|
|
2847
|
+
`<code>${e(d.type)}</code>`,
|
|
2848
|
+
`<code>${e(d.url)}</code>`,
|
|
2849
|
+
String(d.copy),
|
|
2850
|
+
d.delivered ? `<span class="ok">Delivered</span>` : `<span class="bad">${e(d.attempts.map((a) => a.status === null ? a.error ?? "error" : String(a.status)).join(", ") || "Not sent")}</span>`
|
|
2851
|
+
])
|
|
2852
|
+
) : empty("No webhooks sent yet.");
|
|
2853
|
+
const endpoints = data.endpoints.length ? `<p class="sub">Endpoints: ${data.endpoints.map((x) => `<code>${e(x.url)}</code>`).join(", ")}</p>` : `<p class="sub">No webhook endpoints. Add one in the seed, with <code>start --webhook</code> or <code>addEndpoint()</code>.</p>`;
|
|
2854
|
+
const webhookForm = data.endpoints.length ? form(
|
|
2855
|
+
"/dashboard/webhooks",
|
|
2856
|
+
`<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
|
|
2857
|
+
<label>User<select name="user"><option value="">First seeded user</option>${seed.users.map((u) => `<option value="${e(u.id)}">${e(u.email ?? u.id)}</option>`).join("")}</select></label>
|
|
2858
|
+
<label>Variant<select name="invalid"><option value="">Valid</option><option>bad-signature</option><option>unknown-key</option><option>unsigned</option><option>stale</option></select></label>
|
|
2859
|
+
<label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
|
|
2860
|
+
<button class="primary">Send</button>`
|
|
2861
|
+
) : "";
|
|
2862
|
+
const failures = data.failures.length ? table(
|
|
2863
|
+
["Path", "Method", "Effect", "Remaining", "Hits", ""],
|
|
2864
|
+
data.failures.map((f) => [
|
|
2865
|
+
`<code>${e(f.path)}</code>`,
|
|
2866
|
+
e(f.method ?? "any"),
|
|
2867
|
+
e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
|
|
2868
|
+
f.remaining === null ? "Until removed" : String(f.remaining),
|
|
2869
|
+
String(f.hits),
|
|
2870
|
+
form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
|
|
2871
|
+
])
|
|
2872
|
+
) : empty("No failure rules.");
|
|
2873
|
+
const coverage = `<div class="grid">${data.coverage.groups.map(
|
|
2874
|
+
(g) => `<div><div class="group"><span>${e(g.name)}</span><span class="${g.covered === g.total ? "ok" : "muted"}">${g.covered}/${g.total}</span></div><ul>${g.items.map((i) => `<li title="${e(i.hint)}"><span class="${i.covered ? "ok" : "muted"}">${i.covered ? "\u2713" : "\u25CB"}</span> ${e(i.label)}</li>`).join("")}</ul></div>`
|
|
2875
|
+
).join("")}</div>`;
|
|
2876
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2877
|
+
${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
|
|
2878
|
+
<title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
|
|
2879
|
+
<header>
|
|
2880
|
+
<div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
|
|
2881
|
+
<nav><a href="#users">Users</a><a href="#tokens">Tokens</a><a href="#requests">Requests</a><a href="#webhooks">Webhooks</a><a href="#failures">Failures</a><a href="#coverage">Coverage</a></nav>
|
|
2882
|
+
<div class="row">
|
|
2883
|
+
<a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
|
|
2884
|
+
${form("/dashboard/reset", `<button>Reset state</button>`)}
|
|
2885
|
+
</div>
|
|
2886
|
+
</header>
|
|
2887
|
+
<main>
|
|
2888
|
+
${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
|
|
2889
|
+
<section id="users"><h2>Users</h2><p class="sub">Seeded users, users created through the Management API, and emails that signed in.</p>${users}</section>
|
|
2890
|
+
<div class="split">
|
|
2891
|
+
<section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
|
|
2892
|
+
<section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
|
|
2893
|
+
</div>
|
|
2894
|
+
${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
|
|
2895
|
+
<section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
|
|
2896
|
+
<section id="requests"><h2>Requests</h2><p class="sub">The latest 100 requests your app and tests made. Codes, secrets and refresh tokens are hidden.</p>${requests}</section>
|
|
2897
|
+
<section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
|
|
2898
|
+
<section id="failures"><h2>Failures</h2><p class="sub">Make an endpoint fail, slow down or hang. Applies to Kinde endpoints, not <code>/testkit</code> or this page.</p>
|
|
2899
|
+
${form(
|
|
2900
|
+
"/dashboard/failures",
|
|
2901
|
+
`<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
|
|
2902
|
+
<label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
|
|
2903
|
+
<label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
|
|
2904
|
+
<label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
|
|
2905
|
+
<label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
|
|
2906
|
+
<label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
|
|
2907
|
+
<button class="primary">Add rule</button>`
|
|
2908
|
+
)}
|
|
2909
|
+
<div style="margin-top:14px">${failures}</div>
|
|
2910
|
+
${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
|
|
2911
|
+
</section>
|
|
2912
|
+
<section id="coverage"><h2>Coverage: ${data.coverage.covered}/${data.coverage.total}</h2><p class="sub">Authentication scenarios the testkit produced since it started or was reset. Hover an item to see how to cover it.</p>${coverage}
|
|
2913
|
+
<div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
|
|
2914
|
+
</main></body></html>`;
|
|
2915
|
+
}
|
|
2916
|
+
function table(headers, rows) {
|
|
2917
|
+
return `<table><thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
|
|
2918
|
+
}
|
|
2919
|
+
function chips(values) {
|
|
2920
|
+
if (values.length === 0) return `<span class="muted">none</span>`;
|
|
2921
|
+
return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
|
|
2922
|
+
}
|
|
2923
|
+
function empty(text) {
|
|
2924
|
+
return `<p class="empty">${escapeHtml(text)}</p>`;
|
|
2925
|
+
}
|
|
2926
|
+
function time(iso) {
|
|
2927
|
+
return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
|
|
2928
|
+
}
|
|
2929
|
+
function form(action, body) {
|
|
2930
|
+
return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
|
|
2931
|
+
}
|
|
2932
|
+
|
|
2933
|
+
// src/server.ts
|
|
2934
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
2935
|
+
var MAX_BODY_BYTES = 64 * 1024;
|
|
2936
|
+
var JWKS_PATHS = /* @__PURE__ */ new Set(["/.well-known/jwks", "/.well-known/jwks.json"]);
|
|
2937
|
+
async function startKindeTestkit(options = {}) {
|
|
2938
|
+
const host = options.host ?? "127.0.0.1";
|
|
2939
|
+
if (!LOOPBACK_HOSTS.has(host) && !options.allowPublic) {
|
|
2940
|
+
throw new TestkitError(
|
|
2941
|
+
"PUBLIC_BIND_REFUSED",
|
|
2942
|
+
`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).`
|
|
2943
|
+
);
|
|
2944
|
+
}
|
|
2945
|
+
const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
|
|
2946
|
+
const seed = resolveSeed(seedInput);
|
|
2947
|
+
const failures = new FailureInjector();
|
|
2948
|
+
let ready;
|
|
2949
|
+
const testkitReady = new Promise((resolve4) => ready = resolve4);
|
|
2950
|
+
const listener = (req, res) => {
|
|
2951
|
+
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
2952
|
+
};
|
|
2953
|
+
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
2954
|
+
const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
|
|
2955
|
+
await new Promise((resolve4, reject) => {
|
|
2956
|
+
server.once("error", reject);
|
|
2957
|
+
server.listen(options.port ?? 4400, host, () => resolve4());
|
|
2958
|
+
});
|
|
2959
|
+
const { port } = server.address();
|
|
2960
|
+
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
2961
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
2962
|
+
const testkit = await KindeTestkit.create({
|
|
2963
|
+
issuer: options.issuer ?? seedInput.issuer ?? url,
|
|
2964
|
+
audience: options.audience ?? seedInput.audience,
|
|
2965
|
+
clientId: options.clientId ?? seedInput.clientId
|
|
2966
|
+
});
|
|
2967
|
+
const coverage = new CoverageRecorder();
|
|
2968
|
+
const activity = new ActivityLog();
|
|
2969
|
+
testkit.observe({
|
|
2970
|
+
accessToken(payload, invalid2, token) {
|
|
2971
|
+
coverage.observeAccessToken(payload, invalid2);
|
|
2972
|
+
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
2973
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid2, token);
|
|
2974
|
+
},
|
|
2975
|
+
idToken(payload, token) {
|
|
2976
|
+
coverage.hit("identity.id-token");
|
|
2977
|
+
activity.token("id", payload, void 0, token);
|
|
2978
|
+
},
|
|
2979
|
+
anonymous() {
|
|
2980
|
+
coverage.hit("identity.anonymous");
|
|
2981
|
+
}
|
|
2982
|
+
});
|
|
2983
|
+
const observe = (id) => coverage.hit(id);
|
|
2984
|
+
const directory = new Directory(seed);
|
|
2985
|
+
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
2986
|
+
webhooks.observe = observe;
|
|
2987
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
|
|
2988
|
+
const management = new ManagementApi(testkit, directory, webhooks);
|
|
2989
|
+
const account = new AccountApi(testkit, directory);
|
|
2990
|
+
const reset = () => {
|
|
2991
|
+
auth.reset();
|
|
2992
|
+
failures.clear();
|
|
2993
|
+
webhooks.reset();
|
|
2994
|
+
directory.restore();
|
|
2995
|
+
};
|
|
2996
|
+
const loadSeed = (input) => {
|
|
2997
|
+
const next = resolveSeed(input);
|
|
2998
|
+
directory.load(next);
|
|
2999
|
+
webhooks.replaceSeededEndpoints(next.webhooks);
|
|
3000
|
+
reset();
|
|
3001
|
+
};
|
|
3002
|
+
let closed = false;
|
|
3003
|
+
const close = () => new Promise((resolve4, reject) => {
|
|
3004
|
+
if (closed) return resolve4();
|
|
3005
|
+
closed = true;
|
|
3006
|
+
if (options.coverage) {
|
|
3007
|
+
coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
|
|
3008
|
+
}
|
|
3009
|
+
server.closeAllConnections();
|
|
3010
|
+
server.close((error) => error ? reject(error) : resolve4());
|
|
3011
|
+
});
|
|
3012
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
|
|
3013
|
+
return {
|
|
3014
|
+
url,
|
|
3015
|
+
issuer: testkit.issuer,
|
|
3016
|
+
discoveryUrl: `${url}/.well-known/openid-configuration`,
|
|
3017
|
+
jwksUri: `${url}/.well-known/jwks`,
|
|
3018
|
+
testkit,
|
|
3019
|
+
seed,
|
|
3020
|
+
failures,
|
|
3021
|
+
webhooks,
|
|
3022
|
+
directory,
|
|
3023
|
+
certificatePath: certificate?.certPath ?? null,
|
|
3024
|
+
coverage,
|
|
3025
|
+
activity,
|
|
3026
|
+
loadSeed,
|
|
3027
|
+
reset,
|
|
3028
|
+
close
|
|
3029
|
+
};
|
|
3030
|
+
}
|
|
3031
|
+
async function handle(req, res, context) {
|
|
3032
|
+
const { testkit, auth, seed, failures, webhooks, coverage } = context;
|
|
3033
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
3034
|
+
const { pathname } = url;
|
|
3035
|
+
const method = req.method ?? "GET";
|
|
3036
|
+
const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
|
|
3037
|
+
let injected = false;
|
|
3038
|
+
if (!internal && pathname !== "/favicon.ico") {
|
|
3039
|
+
const started = Date.now();
|
|
3040
|
+
res.once("close", () => {
|
|
3041
|
+
context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
|
|
3042
|
+
});
|
|
3043
|
+
}
|
|
3044
|
+
if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
|
|
3045
|
+
if (!internal) {
|
|
3046
|
+
const failure = failures.take(method, pathname);
|
|
3047
|
+
if (failure) {
|
|
3048
|
+
injected = true;
|
|
3049
|
+
if (failure.hang) coverage.hit("outage.timeout");
|
|
3050
|
+
else if (failure.status === 429) coverage.hit("outage.rate-limit");
|
|
3051
|
+
else if (failure.status !== null) coverage.hit("outage.error");
|
|
3052
|
+
if (failure.delayMs > 0) coverage.hit("outage.slow");
|
|
3053
|
+
if (failure.hang) return;
|
|
3054
|
+
if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
|
|
3055
|
+
if (failure.status !== null) {
|
|
3056
|
+
const headers = {};
|
|
3057
|
+
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
3058
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
3063
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) {
|
|
3064
|
+
if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
|
|
3065
|
+
else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
|
|
3066
|
+
return;
|
|
3067
|
+
}
|
|
3068
|
+
if (await context.account.handle(req, res, url)) {
|
|
3069
|
+
if (res.statusCode < 400) coverage.hit("api.account");
|
|
3070
|
+
return;
|
|
3071
|
+
}
|
|
3072
|
+
if (method === "GET" && pathname === "/testkit/portal") {
|
|
3073
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
3074
|
+
res.end(
|
|
3075
|
+
`<!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>`
|
|
3076
|
+
);
|
|
3077
|
+
return;
|
|
3078
|
+
}
|
|
3079
|
+
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
3080
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
3081
|
+
}
|
|
3082
|
+
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
3083
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
3084
|
+
}
|
|
3085
|
+
if (method === "GET" && pathname === "/testkit/health") {
|
|
3086
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
3087
|
+
}
|
|
3088
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
3089
|
+
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
3090
|
+
return sendJson4(res, 200, seed.organizations);
|
|
3091
|
+
}
|
|
3092
|
+
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
3093
|
+
return sendJson4(res, 200, seed.memberships);
|
|
3094
|
+
}
|
|
3095
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
3096
|
+
if (method === "POST" && pathname === "/testkit/failures") {
|
|
3097
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
3098
|
+
}
|
|
3099
|
+
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
3100
|
+
failures.clear();
|
|
3101
|
+
return sendJson4(res, 200, { ok: true });
|
|
3102
|
+
}
|
|
3103
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
3104
|
+
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
3105
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
3106
|
+
}
|
|
3107
|
+
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
3108
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
3109
|
+
}
|
|
3110
|
+
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
3111
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
3112
|
+
}
|
|
3113
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
|
|
3114
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
|
|
3115
|
+
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
3116
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
3117
|
+
}
|
|
3118
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
3119
|
+
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
3120
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
3121
|
+
}
|
|
3122
|
+
if (method === "POST" && pathname === "/testkit/reset") {
|
|
3123
|
+
context.reset();
|
|
3124
|
+
return sendJson4(res, 200, { ok: true });
|
|
3125
|
+
}
|
|
3126
|
+
if (method === "POST" && pathname === "/testkit/token") {
|
|
3127
|
+
const body = await readJson(req);
|
|
3128
|
+
let accessToken;
|
|
3129
|
+
try {
|
|
3130
|
+
accessToken = await issueToken(testkit, seed, body);
|
|
3131
|
+
} catch (error) {
|
|
3132
|
+
if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
|
|
3133
|
+
throw error;
|
|
3134
|
+
}
|
|
3135
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
3136
|
+
}
|
|
3137
|
+
if (method === "GET" && pathname === "/testkit/coverage") {
|
|
3138
|
+
return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
|
|
3139
|
+
}
|
|
3140
|
+
if (method === "DELETE" && pathname === "/testkit/coverage") {
|
|
3141
|
+
coverage.reset();
|
|
3142
|
+
return sendJson4(res, 200, { ok: true });
|
|
3143
|
+
}
|
|
3144
|
+
if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
|
|
3145
|
+
if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
|
|
3146
|
+
if (method === "POST" && pathname === "/testkit/seed") {
|
|
3147
|
+
const body = await readJson(req);
|
|
3148
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
3149
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
3150
|
+
}
|
|
3151
|
+
context.loadSeed(body);
|
|
3152
|
+
return sendJson4(res, 200, {
|
|
3153
|
+
ok: true,
|
|
3154
|
+
users: seed.users.length,
|
|
3155
|
+
organizations: seed.organizations.length,
|
|
3156
|
+
memberships: seed.memberships.length
|
|
3157
|
+
});
|
|
3158
|
+
}
|
|
3159
|
+
if (method === "POST" && pathname === "/testkit/stop") {
|
|
3160
|
+
sendJson4(res, 200, { ok: true });
|
|
3161
|
+
res.once("finish", () => void context.close().catch(() => void 0));
|
|
3162
|
+
return;
|
|
3163
|
+
}
|
|
3164
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3165
|
+
}
|
|
3166
|
+
async function dashboard(req, res, url, context) {
|
|
3167
|
+
const method = req.method ?? "GET";
|
|
3168
|
+
const { pathname } = url;
|
|
3169
|
+
if (method === "GET" && pathname === "/dashboard") {
|
|
3170
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
3171
|
+
res.end(
|
|
3172
|
+
renderDashboard({
|
|
3173
|
+
issuer: context.testkit.issuer,
|
|
3174
|
+
seed: context.seed,
|
|
3175
|
+
suspended: (id) => context.directory.isSuspended(id),
|
|
3176
|
+
signIns: (id) => {
|
|
3177
|
+
const user = context.directory.user(id);
|
|
3178
|
+
return user ? context.directory.meta(user).totalSignIns : 0;
|
|
3179
|
+
},
|
|
3180
|
+
tokens: context.activity.tokens(),
|
|
3181
|
+
requests: context.activity.requests(),
|
|
3182
|
+
deliveries: context.webhooks.deliveries(),
|
|
3183
|
+
endpoints: context.webhooks.listEndpoints(),
|
|
3184
|
+
failures: context.failures.list(),
|
|
3185
|
+
coverage: context.coverage.report(),
|
|
3186
|
+
webhookTypes: WEBHOOK_EVENT_TYPES,
|
|
3187
|
+
live: url.searchParams.has("live"),
|
|
3188
|
+
notice: url.searchParams.get("notice")
|
|
3189
|
+
})
|
|
3190
|
+
);
|
|
3191
|
+
return;
|
|
3192
|
+
}
|
|
3193
|
+
if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3194
|
+
const origin = req.headers.origin;
|
|
3195
|
+
if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
|
|
3196
|
+
return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
|
|
3197
|
+
}
|
|
3198
|
+
const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
|
|
3199
|
+
let notice = "Done.";
|
|
3200
|
+
try {
|
|
3201
|
+
if (pathname === "/dashboard/reset") {
|
|
3202
|
+
context.reset();
|
|
3203
|
+
notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
|
|
3204
|
+
} else if (pathname === "/dashboard/coverage/reset") {
|
|
3205
|
+
context.coverage.reset();
|
|
3206
|
+
notice = "Cleared coverage.";
|
|
3207
|
+
} else if (pathname === "/dashboard/failures/clear") {
|
|
3208
|
+
context.failures.clear();
|
|
3209
|
+
notice = "Removed every failure rule.";
|
|
3210
|
+
} else if (pathname === "/dashboard/failures") {
|
|
3211
|
+
const rule = { path: form2.path ?? "" };
|
|
3212
|
+
if (form2.method) rule.method = form2.method;
|
|
3213
|
+
if (form2.status) rule.status = Number(form2.status);
|
|
3214
|
+
if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
|
|
3215
|
+
if (form2.times) rule.times = Number(form2.times);
|
|
3216
|
+
if (form2.hang) rule.hang = true;
|
|
3217
|
+
const added = context.failures.add(rule);
|
|
3218
|
+
notice = `Added ${added.id} for ${added.path}.`;
|
|
3219
|
+
} else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
|
|
3220
|
+
const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
|
|
3221
|
+
notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
|
|
3222
|
+
} else if (pathname === "/dashboard/webhooks") {
|
|
3223
|
+
const deliveries = await context.webhooks.send({
|
|
3224
|
+
type: form2.type ?? "",
|
|
3225
|
+
user: form2.user || void 0,
|
|
3226
|
+
invalid: form2.invalid || void 0,
|
|
3227
|
+
duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
|
|
3228
|
+
});
|
|
3229
|
+
const delivered = deliveries.filter((d) => d.delivered).length;
|
|
3230
|
+
notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
|
|
3231
|
+
} else {
|
|
3232
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
|
|
3233
|
+
}
|
|
3234
|
+
} catch (error) {
|
|
3235
|
+
notice = error.message.replace(/\s+/g, " ").trim();
|
|
3236
|
+
}
|
|
3237
|
+
const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
|
|
3238
|
+
res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
|
|
3239
|
+
res.end();
|
|
3240
|
+
}
|
|
3241
|
+
function discovery(testkit) {
|
|
3242
|
+
const base = testkit.issuer;
|
|
3243
|
+
return {
|
|
3244
|
+
issuer: base,
|
|
3245
|
+
authorization_endpoint: `${base}/oauth2/auth`,
|
|
3246
|
+
token_endpoint: `${base}/oauth2/token`,
|
|
3247
|
+
userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
|
|
3248
|
+
end_session_endpoint: `${base}/logout`,
|
|
3249
|
+
revocation_endpoint: `${base}/oauth2/revoke`,
|
|
3250
|
+
jwks_uri: `${base}/.well-known/jwks`,
|
|
3251
|
+
response_types_supported: ["code"],
|
|
3252
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
3253
|
+
code_challenge_methods_supported: ["S256", "plain"],
|
|
3254
|
+
subject_types_supported: ["public"],
|
|
3255
|
+
id_token_signing_alg_values_supported: ["RS256"],
|
|
3256
|
+
scopes_supported: ["openid", "profile", "email", "offline"],
|
|
3257
|
+
token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic", "none"],
|
|
3258
|
+
claims_supported: ["aud", "exp", "iat", "iss", "sub", "org_code", "permissions", "roles", "scp"]
|
|
3259
|
+
};
|
|
3260
|
+
}
|
|
3261
|
+
async function issueToken(testkit, seed, body) {
|
|
3262
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
3263
|
+
throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
|
|
3264
|
+
}
|
|
3265
|
+
const input = body;
|
|
3266
|
+
const invalid2 = optionalString(input, "invalid");
|
|
3267
|
+
if (invalid2 !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid2)) {
|
|
3268
|
+
throw new TestkitError("INVALID_REQUEST", `"${invalid2}" is not a known invalid token kind.`, [
|
|
3269
|
+
`Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
|
|
3270
|
+
]);
|
|
3271
|
+
}
|
|
3272
|
+
const expiresIn = input.expiresIn;
|
|
3273
|
+
if (input.m2m === true) {
|
|
3274
|
+
const clientId = optionalString(input, "clientId");
|
|
3275
|
+
const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
|
|
3276
|
+
const scopes = optionalStrings(input, "scopes") ?? [];
|
|
3277
|
+
return testkit.m2mToken({
|
|
3278
|
+
clientId,
|
|
3279
|
+
organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
|
|
3280
|
+
scopes,
|
|
3281
|
+
grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
|
|
3282
|
+
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
3283
|
+
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
3284
|
+
expiresIn,
|
|
3285
|
+
invalid: invalid2
|
|
3286
|
+
});
|
|
3287
|
+
}
|
|
3288
|
+
const permissions = optionalStrings(input, "permissions");
|
|
3289
|
+
const roles = optionalStrings(input, "roles");
|
|
3290
|
+
const userRef = optionalString(input, "user");
|
|
3291
|
+
if (userRef) {
|
|
3292
|
+
const scenario = seedScenario(seed, {
|
|
3293
|
+
user: userRef,
|
|
3294
|
+
organization: optionalString(input, "organization") ?? null
|
|
3295
|
+
});
|
|
3296
|
+
if (permissions) scenario.permissions = permissions;
|
|
3297
|
+
if (roles) scenario.roles = roles;
|
|
3298
|
+
return await testkit.tokenFor(scenario, {
|
|
3299
|
+
expiresIn,
|
|
3300
|
+
invalid: invalid2,
|
|
3301
|
+
featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
|
|
3302
|
+
});
|
|
3303
|
+
}
|
|
3304
|
+
const options = {
|
|
3305
|
+
subject: optionalString(input, "subject"),
|
|
3306
|
+
organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? null,
|
|
3307
|
+
permissions,
|
|
3308
|
+
roles,
|
|
3309
|
+
scopes: optionalStrings(input, "scopes"),
|
|
3310
|
+
expiresIn,
|
|
3311
|
+
invalid: invalid2
|
|
3312
|
+
};
|
|
3313
|
+
if (typeof input.claims === "object" && input.claims !== null) {
|
|
3314
|
+
options.claims = input.claims;
|
|
3315
|
+
}
|
|
3316
|
+
return testkit.token(options);
|
|
3317
|
+
}
|
|
3318
|
+
function optionalString(input, field) {
|
|
3319
|
+
const value = input[field];
|
|
3320
|
+
if (value === void 0 || value === null) return void 0;
|
|
3321
|
+
if (typeof value !== "string") {
|
|
3322
|
+
throw new TestkitError("INVALID_REQUEST", `"${field}" must be a string.`);
|
|
3323
|
+
}
|
|
3324
|
+
return value;
|
|
3325
|
+
}
|
|
3326
|
+
function optionalStrings(input, field) {
|
|
3327
|
+
const value = input[field];
|
|
3328
|
+
if (value === void 0) return void 0;
|
|
3329
|
+
if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
|
|
3330
|
+
throw new TestkitError("INVALID_REQUEST", `"${field}" must be a list of strings.`);
|
|
3331
|
+
}
|
|
3332
|
+
return value;
|
|
3333
|
+
}
|
|
3334
|
+
async function readForm(req) {
|
|
3335
|
+
const text = await readText(req);
|
|
3336
|
+
if ((req.headers["content-type"] ?? "").includes("application/json")) {
|
|
3337
|
+
try {
|
|
3338
|
+
const parsed = JSON.parse(text || "{}");
|
|
3339
|
+
return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));
|
|
3340
|
+
} catch {
|
|
3341
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
3342
|
+
}
|
|
3343
|
+
}
|
|
3344
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
3345
|
+
}
|
|
3346
|
+
async function readJson(req) {
|
|
3347
|
+
const text = await readText(req);
|
|
3348
|
+
if (text.length === 0) return {};
|
|
3349
|
+
try {
|
|
3350
|
+
return JSON.parse(text);
|
|
3351
|
+
} catch {
|
|
3352
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
3353
|
+
}
|
|
3354
|
+
}
|
|
3355
|
+
async function readText(req) {
|
|
3356
|
+
const chunks = [];
|
|
3357
|
+
let size = 0;
|
|
3358
|
+
for await (const chunk of req) {
|
|
3359
|
+
size += chunk.length;
|
|
3360
|
+
if (size > MAX_BODY_BYTES) {
|
|
3361
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is larger than 64 KB.");
|
|
3362
|
+
}
|
|
3363
|
+
chunks.push(chunk);
|
|
3364
|
+
}
|
|
3365
|
+
return Buffer.concat(chunks).toString("utf8").trim();
|
|
3366
|
+
}
|
|
3367
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
3368
|
+
res.writeHead(status, {
|
|
3369
|
+
"content-type": "application/json; charset=utf-8",
|
|
3370
|
+
"cache-control": "no-store",
|
|
3371
|
+
...headers
|
|
3372
|
+
});
|
|
3373
|
+
res.end(JSON.stringify(body));
|
|
3374
|
+
}
|
|
3375
|
+
function sendError(res, error) {
|
|
3376
|
+
if (res.headersSent) {
|
|
3377
|
+
res.end();
|
|
3378
|
+
return;
|
|
3379
|
+
}
|
|
3380
|
+
if (error instanceof TestkitError) {
|
|
3381
|
+
sendJson4(res, 400, { error: error.code, error_description: error.summary, details: error.details });
|
|
3382
|
+
return;
|
|
3383
|
+
}
|
|
3384
|
+
sendJson4(res, 500, {
|
|
3385
|
+
error: "server_error",
|
|
3386
|
+
error_description: error instanceof Error ? error.message : String(error)
|
|
3387
|
+
});
|
|
3388
|
+
}
|
|
3389
|
+
|
|
3390
|
+
export {
|
|
3391
|
+
createKindeUser,
|
|
3392
|
+
createKindeOrganization,
|
|
3393
|
+
createMembership,
|
|
3394
|
+
toKindeRole,
|
|
3395
|
+
resetFactories,
|
|
3396
|
+
TestkitError,
|
|
3397
|
+
DEFAULT_ISSUER,
|
|
3398
|
+
DEFAULT_CLIENT_ID,
|
|
3399
|
+
DEFAULT_M2M_CLIENT_ID,
|
|
3400
|
+
DEFAULT_SCOPES,
|
|
3401
|
+
DEFAULT_AUTH_METHODS,
|
|
3402
|
+
INVALID_TOKEN_KINDS,
|
|
3403
|
+
KindeTestkit,
|
|
3404
|
+
principalFromClaims,
|
|
3405
|
+
getDefaultTestkit,
|
|
3406
|
+
createKindeToken,
|
|
3407
|
+
ensureLocalCertificate,
|
|
3408
|
+
createLocalCertificate,
|
|
3409
|
+
resolveSeed,
|
|
3410
|
+
seedScenario,
|
|
3411
|
+
Directory,
|
|
3412
|
+
FailureInjector,
|
|
3413
|
+
WEBHOOK_EVENT_TYPES,
|
|
3414
|
+
BILLING_EVENT_TYPES,
|
|
3415
|
+
WebhookDispatcher,
|
|
3416
|
+
ActivityLog,
|
|
3417
|
+
COVERAGE_GROUPS,
|
|
3418
|
+
CoverageRecorder,
|
|
3419
|
+
DEFAULT_COVERAGE_DIRECTORY,
|
|
3420
|
+
buildReport,
|
|
3421
|
+
mergeSnapshots,
|
|
3422
|
+
readCoverageDirectory,
|
|
3423
|
+
clearCoverageDirectory,
|
|
3424
|
+
formatCoverageReport,
|
|
3425
|
+
DEFAULT_SEED_FILES,
|
|
3426
|
+
findSeedFile,
|
|
3427
|
+
loadSeedFile,
|
|
3428
|
+
startKindeTestkit
|
|
3429
|
+
};
|
|
3430
|
+
//# sourceMappingURL=chunk-GCOZVCZY.js.map
|