kinde-testkit 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +189 -11
- package/dist/cli.js +957 -117
- package/dist/cypress-support.d.ts +98 -0
- package/dist/cypress-support.js +119 -0
- package/dist/cypress-support.js.map +1 -0
- package/dist/cypress.cjs +4249 -0
- package/dist/cypress.cjs.map +1 -0
- package/dist/cypress.d.cts +118 -0
- package/dist/cypress.d.ts +118 -0
- package/dist/cypress.js +3324 -0
- package/dist/cypress.js.map +1 -0
- package/dist/index.cjs +2042 -99
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +178 -3
- package/dist/index.d.ts +178 -3
- package/dist/index.js +846 -52
- package/dist/index.js.map +1 -1
- package/dist/jest.cjs +4318 -0
- package/dist/jest.cjs.map +1 -0
- package/dist/jest.d.cts +567 -0
- package/dist/jest.d.ts +567 -0
- package/dist/jest.js +3392 -0
- package/dist/jest.js.map +1 -0
- package/dist/vitest.d.ts +154 -1
- package/dist/vitest.js +757 -57
- package/dist/vitest.js.map +1 -1
- package/package.json +34 -3
package/dist/index.js
CHANGED
|
@@ -189,6 +189,20 @@ var INVALID_TOKEN_KINDS = [
|
|
|
189
189
|
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
190
190
|
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
191
191
|
var KindeTestkit = class _KindeTestkit {
|
|
192
|
+
observers = [];
|
|
193
|
+
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
194
|
+
observe(observer) {
|
|
195
|
+
this.observers.push(observer);
|
|
196
|
+
return () => {
|
|
197
|
+
this.observers = this.observers.filter((o) => o !== observer);
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
async signAccess(payload, invalid2, now) {
|
|
201
|
+
const final = applyInvalidClaims(payload, invalid2, now);
|
|
202
|
+
const token = await this.sign(final, invalid2);
|
|
203
|
+
for (const observer of this.observers) observer.accessToken?.(final, invalid2, token);
|
|
204
|
+
return token;
|
|
205
|
+
}
|
|
192
206
|
issuer;
|
|
193
207
|
audience;
|
|
194
208
|
clientId;
|
|
@@ -248,7 +262,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
248
262
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
249
263
|
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
250
264
|
Object.assign(payload, options.claims ?? {});
|
|
251
|
-
return this.
|
|
265
|
+
return this.signAccess(payload, options.invalid, now);
|
|
252
266
|
}
|
|
253
267
|
async m2mToken(options = {}) {
|
|
254
268
|
const now = this.clock();
|
|
@@ -269,10 +283,13 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
269
283
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
270
284
|
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
271
285
|
Object.assign(payload, options.claims ?? {});
|
|
272
|
-
return this.
|
|
286
|
+
return this.signAccess(payload, options.invalid, now);
|
|
273
287
|
}
|
|
274
288
|
async tokenFor(scenario2, overrides = {}) {
|
|
275
|
-
if (scenario2.kind === "unauthenticated")
|
|
289
|
+
if (scenario2.kind === "unauthenticated") {
|
|
290
|
+
for (const observer of this.observers) observer.anonymous?.();
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
276
293
|
return this.token({
|
|
277
294
|
subject: scenario2.user.id,
|
|
278
295
|
organizationCode: scenario2.organization?.code ?? null,
|
|
@@ -314,7 +331,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
314
331
|
for (const key of Object.keys(payload)) {
|
|
315
332
|
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
316
333
|
}
|
|
317
|
-
|
|
334
|
+
const token = await this.sign(payload);
|
|
335
|
+
for (const observer of this.observers) observer.idToken?.(payload, token);
|
|
336
|
+
return token;
|
|
318
337
|
}
|
|
319
338
|
async headersFor(scenario2, overrides = {}) {
|
|
320
339
|
const token = await this.tokenFor(scenario2, overrides);
|
|
@@ -964,16 +983,18 @@ var OAuthError = class extends Error {
|
|
|
964
983
|
error;
|
|
965
984
|
};
|
|
966
985
|
var AuthorizationServer = class {
|
|
967
|
-
constructor(testkit, seed, emit = () => void 0, directory) {
|
|
986
|
+
constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
|
|
968
987
|
this.testkit = testkit;
|
|
969
988
|
this.seed = seed;
|
|
970
989
|
this.emit = emit;
|
|
971
990
|
this.directory = directory;
|
|
991
|
+
this.observe = observe;
|
|
972
992
|
}
|
|
973
993
|
testkit;
|
|
974
994
|
seed;
|
|
975
995
|
emit;
|
|
976
996
|
directory;
|
|
997
|
+
observe;
|
|
977
998
|
codes = /* @__PURE__ */ new Map();
|
|
978
999
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
979
1000
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -1010,6 +1031,7 @@ var AuthorizationServer = class {
|
|
|
1010
1031
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
1011
1032
|
}
|
|
1012
1033
|
if (params.get("prompt") === "none") {
|
|
1034
|
+
this.observe("session.silent");
|
|
1013
1035
|
return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
1014
1036
|
}
|
|
1015
1037
|
sendHtml(
|
|
@@ -1023,15 +1045,15 @@ var AuthorizationServer = class {
|
|
|
1023
1045
|
})
|
|
1024
1046
|
);
|
|
1025
1047
|
}
|
|
1026
|
-
login(res,
|
|
1048
|
+
login(res, form2) {
|
|
1027
1049
|
let request;
|
|
1028
1050
|
try {
|
|
1029
|
-
request = decodeRequest(
|
|
1051
|
+
request = decodeRequest(form2.request ?? "");
|
|
1030
1052
|
} catch {
|
|
1031
1053
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
1032
1054
|
}
|
|
1033
1055
|
const encoded = encodeRequest(request);
|
|
1034
|
-
const ref = (
|
|
1056
|
+
const ref = (form2.user || form2.email || "").trim();
|
|
1035
1057
|
if (!ref) {
|
|
1036
1058
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
|
|
1037
1059
|
}
|
|
@@ -1040,6 +1062,7 @@ var AuthorizationServer = class {
|
|
|
1040
1062
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
1041
1063
|
}
|
|
1042
1064
|
if (this.directory?.isSuspended(user.id)) {
|
|
1065
|
+
this.observe("identity.suspended");
|
|
1043
1066
|
return sendHtml(
|
|
1044
1067
|
res,
|
|
1045
1068
|
403,
|
|
@@ -1052,10 +1075,11 @@ var AuthorizationServer = class {
|
|
|
1052
1075
|
);
|
|
1053
1076
|
}
|
|
1054
1077
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
1055
|
-
const wanted = request.orgCode ??
|
|
1078
|
+
const wanted = request.orgCode ?? form2.org ?? null;
|
|
1056
1079
|
let organizationCode = null;
|
|
1057
1080
|
if (wanted) {
|
|
1058
1081
|
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
1082
|
+
this.observe("organization.non-member");
|
|
1059
1083
|
return sendHtml(
|
|
1060
1084
|
res,
|
|
1061
1085
|
403,
|
|
@@ -1110,18 +1134,20 @@ var AuthorizationServer = class {
|
|
|
1110
1134
|
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
1111
1135
|
redirect(res, target.toString());
|
|
1112
1136
|
}
|
|
1113
|
-
async token(req, res,
|
|
1137
|
+
async token(req, res, form2) {
|
|
1114
1138
|
try {
|
|
1115
|
-
const clientId = clientIdFrom(req,
|
|
1116
|
-
const grantType =
|
|
1139
|
+
const clientId = clientIdFrom(req, form2);
|
|
1140
|
+
const grantType = form2.grant_type;
|
|
1117
1141
|
if (grantType === "client_credentials") {
|
|
1118
|
-
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req,
|
|
1142
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
|
|
1119
1143
|
}
|
|
1120
1144
|
let grant;
|
|
1121
1145
|
if (grantType === "authorization_code") {
|
|
1122
|
-
grant = this.redeemCode(
|
|
1146
|
+
grant = this.redeemCode(form2, clientId);
|
|
1147
|
+
this.observe("session.sign-in");
|
|
1123
1148
|
} else if (grantType === "refresh_token") {
|
|
1124
|
-
grant = this.redeemRefreshToken(
|
|
1149
|
+
grant = this.redeemRefreshToken(form2, clientId);
|
|
1150
|
+
this.observe("session.refresh");
|
|
1125
1151
|
} else {
|
|
1126
1152
|
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
1127
1153
|
}
|
|
@@ -1133,14 +1159,14 @@ var AuthorizationServer = class {
|
|
|
1133
1159
|
throw error;
|
|
1134
1160
|
}
|
|
1135
1161
|
}
|
|
1136
|
-
async clientCredentials(clientId, clientSecret,
|
|
1162
|
+
async clientCredentials(clientId, clientSecret, form2) {
|
|
1137
1163
|
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
1138
1164
|
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
1139
1165
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
1140
1166
|
}
|
|
1141
|
-
const requested = (
|
|
1167
|
+
const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
|
|
1142
1168
|
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1143
|
-
const audience = (
|
|
1169
|
+
const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
|
|
1144
1170
|
return {
|
|
1145
1171
|
access_token: await this.testkit.m2mToken({
|
|
1146
1172
|
clientId,
|
|
@@ -1160,8 +1186,8 @@ var AuthorizationServer = class {
|
|
|
1160
1186
|
this.refreshTokens.clear();
|
|
1161
1187
|
this.signedUpUsers.clear();
|
|
1162
1188
|
}
|
|
1163
|
-
redeemCode(
|
|
1164
|
-
const code =
|
|
1189
|
+
redeemCode(form2, clientId) {
|
|
1190
|
+
const code = form2.code ?? "";
|
|
1165
1191
|
const pending = this.codes.get(code);
|
|
1166
1192
|
this.codes.delete(code);
|
|
1167
1193
|
if (!pending || pending.expiresAt < Date.now()) {
|
|
@@ -1170,11 +1196,11 @@ var AuthorizationServer = class {
|
|
|
1170
1196
|
if (pending.clientId !== clientId) {
|
|
1171
1197
|
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
1172
1198
|
}
|
|
1173
|
-
if (
|
|
1199
|
+
if (form2.redirect_uri !== pending.redirectUri) {
|
|
1174
1200
|
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
1175
1201
|
}
|
|
1176
1202
|
if (pending.codeChallenge) {
|
|
1177
|
-
const verifier =
|
|
1203
|
+
const verifier = form2.code_verifier ?? "";
|
|
1178
1204
|
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
1179
1205
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
1180
1206
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
@@ -1182,8 +1208,8 @@ var AuthorizationServer = class {
|
|
|
1182
1208
|
}
|
|
1183
1209
|
return pending;
|
|
1184
1210
|
}
|
|
1185
|
-
redeemRefreshToken(
|
|
1186
|
-
const token =
|
|
1211
|
+
redeemRefreshToken(form2, clientId) {
|
|
1212
|
+
const token = form2.refresh_token ?? "";
|
|
1187
1213
|
const grant = this.refreshTokens.get(token);
|
|
1188
1214
|
this.refreshTokens.delete(token);
|
|
1189
1215
|
if (!grant) {
|
|
@@ -1257,11 +1283,13 @@ var AuthorizationServer = class {
|
|
|
1257
1283
|
phone: null
|
|
1258
1284
|
});
|
|
1259
1285
|
}
|
|
1260
|
-
revoke(res,
|
|
1261
|
-
if (
|
|
1286
|
+
revoke(res, form2) {
|
|
1287
|
+
if (form2.token) this.refreshTokens.delete(form2.token);
|
|
1288
|
+
this.observe("session.revoke");
|
|
1262
1289
|
sendJson(res, 200, {});
|
|
1263
1290
|
}
|
|
1264
1291
|
logout(res, params) {
|
|
1292
|
+
this.observe("session.sign-out");
|
|
1265
1293
|
const target = params.get("redirect");
|
|
1266
1294
|
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
1267
1295
|
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
@@ -1273,6 +1301,7 @@ var AuthorizationServer = class {
|
|
|
1273
1301
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
1274
1302
|
if (!this.signedUpUsers.has(user.id)) {
|
|
1275
1303
|
this.signedUpUsers.set(user.id, user);
|
|
1304
|
+
this.observe("identity.unseeded");
|
|
1276
1305
|
if (this.directory) this.seed.users.push(user);
|
|
1277
1306
|
this.emit("user.created", user);
|
|
1278
1307
|
}
|
|
@@ -1326,24 +1355,24 @@ function decodeRequest(value) {
|
|
|
1326
1355
|
}
|
|
1327
1356
|
return request;
|
|
1328
1357
|
}
|
|
1329
|
-
function clientIdFrom(req,
|
|
1358
|
+
function clientIdFrom(req, form2) {
|
|
1330
1359
|
const header = req.headers.authorization ?? "";
|
|
1331
1360
|
if (header.startsWith("Basic ")) {
|
|
1332
1361
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1333
1362
|
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
1334
1363
|
if (id) return id;
|
|
1335
1364
|
}
|
|
1336
|
-
if (
|
|
1365
|
+
if (form2.client_id) return form2.client_id;
|
|
1337
1366
|
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
1338
1367
|
}
|
|
1339
|
-
function clientSecretFrom(req,
|
|
1368
|
+
function clientSecretFrom(req, form2) {
|
|
1340
1369
|
const header = req.headers.authorization ?? "";
|
|
1341
1370
|
if (header.startsWith("Basic ")) {
|
|
1342
1371
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1343
1372
|
const index = decoded.indexOf(":");
|
|
1344
1373
|
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1345
1374
|
}
|
|
1346
|
-
return
|
|
1375
|
+
return form2.client_secret ?? null;
|
|
1347
1376
|
}
|
|
1348
1377
|
function redirectWithError(res, request, error, description) {
|
|
1349
1378
|
const target = new URL(request.redirectUri);
|
|
@@ -1530,6 +1559,22 @@ var Directory = class {
|
|
|
1530
1559
|
this.userMeta.clear();
|
|
1531
1560
|
this.orgMeta.clear();
|
|
1532
1561
|
}
|
|
1562
|
+
/** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
|
|
1563
|
+
load(next) {
|
|
1564
|
+
for (const key of Object.keys(next)) {
|
|
1565
|
+
const current = this.seed[key];
|
|
1566
|
+
if (Array.isArray(current)) {
|
|
1567
|
+
current.splice(0, current.length, ...next[key]);
|
|
1568
|
+
} else {
|
|
1569
|
+
const record = current;
|
|
1570
|
+
for (const name of Object.keys(record)) delete record[name];
|
|
1571
|
+
Object.assign(record, next[key]);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
this.snapshot = JSON.stringify(this.seed);
|
|
1575
|
+
this.userMeta.clear();
|
|
1576
|
+
this.orgMeta.clear();
|
|
1577
|
+
}
|
|
1533
1578
|
user(id) {
|
|
1534
1579
|
return this.seed.users.find((user) => user.id === id);
|
|
1535
1580
|
}
|
|
@@ -2196,6 +2241,8 @@ var WebhookDispatcher = class {
|
|
|
2196
2241
|
nextEndpoint = 1;
|
|
2197
2242
|
retryDelaysMs;
|
|
2198
2243
|
timeoutMs;
|
|
2244
|
+
/** Set by the server to record coverage. */
|
|
2245
|
+
observe = () => void 0;
|
|
2199
2246
|
addEndpoint(input) {
|
|
2200
2247
|
if (!isHttpUrl2(input.url)) {
|
|
2201
2248
|
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
@@ -2207,6 +2254,14 @@ var WebhookDispatcher = class {
|
|
|
2207
2254
|
this.endpoints.push(endpoint);
|
|
2208
2255
|
return { ...endpoint };
|
|
2209
2256
|
}
|
|
2257
|
+
/** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
|
|
2258
|
+
replaceSeededEndpoints(endpoints) {
|
|
2259
|
+
const seeded = new Set(this.seededEndpoints.map((e) => e.id));
|
|
2260
|
+
this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
|
|
2261
|
+
const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
|
|
2262
|
+
const ids = new Set(added.map((e) => e.id));
|
|
2263
|
+
this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
|
|
2264
|
+
}
|
|
2210
2265
|
removeEndpoint(id) {
|
|
2211
2266
|
const before = this.endpoints.length;
|
|
2212
2267
|
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
@@ -2257,6 +2312,9 @@ var WebhookDispatcher = class {
|
|
|
2257
2312
|
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
2258
2313
|
);
|
|
2259
2314
|
}
|
|
2315
|
+
if (copies > 1) this.observe("webhook.duplicate");
|
|
2316
|
+
if (options.invalid === "stale") this.observe("webhook.stale");
|
|
2317
|
+
else if (options.invalid) this.observe("webhook.forged");
|
|
2260
2318
|
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
2261
2319
|
const signed = await this.testkit.signPayload(
|
|
2262
2320
|
event,
|
|
@@ -2266,7 +2324,11 @@ var WebhookDispatcher = class {
|
|
|
2266
2324
|
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
2267
2325
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
2268
2326
|
});
|
|
2269
|
-
|
|
2327
|
+
const deliveries = await Promise.all(jobs);
|
|
2328
|
+
if (!options.invalid) {
|
|
2329
|
+
for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
|
|
2330
|
+
}
|
|
2331
|
+
return deliveries;
|
|
2270
2332
|
}
|
|
2271
2333
|
async deliver(url, webhookId, body, event, copy) {
|
|
2272
2334
|
const delivery = {
|
|
@@ -2415,7 +2477,511 @@ function isHttpUrl2(value) {
|
|
|
2415
2477
|
}
|
|
2416
2478
|
}
|
|
2417
2479
|
function sleep(ms) {
|
|
2418
|
-
return new Promise((
|
|
2480
|
+
return new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
2481
|
+
}
|
|
2482
|
+
|
|
2483
|
+
// src/activity.ts
|
|
2484
|
+
var LIMIT = 200;
|
|
2485
|
+
var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
|
|
2486
|
+
var ActivityLog = class {
|
|
2487
|
+
requestLog = [];
|
|
2488
|
+
tokenLog = [];
|
|
2489
|
+
request(entry) {
|
|
2490
|
+
const query = new URLSearchParams(entry.query);
|
|
2491
|
+
for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
|
|
2492
|
+
const search = query.toString();
|
|
2493
|
+
push(this.requestLog, {
|
|
2494
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2495
|
+
method: entry.method,
|
|
2496
|
+
path: search ? `${entry.path}?${search}` : entry.path,
|
|
2497
|
+
status: entry.status,
|
|
2498
|
+
durationMs: entry.durationMs,
|
|
2499
|
+
injected: entry.injected
|
|
2500
|
+
});
|
|
2501
|
+
}
|
|
2502
|
+
token(kind, claims, invalid2, token) {
|
|
2503
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
2504
|
+
push(this.tokenLog, {
|
|
2505
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2506
|
+
kind,
|
|
2507
|
+
subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
|
|
2508
|
+
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
2509
|
+
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
2510
|
+
roles,
|
|
2511
|
+
invalid: invalid2 ?? null,
|
|
2512
|
+
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
2513
|
+
claims,
|
|
2514
|
+
token
|
|
2515
|
+
});
|
|
2516
|
+
}
|
|
2517
|
+
requests() {
|
|
2518
|
+
return [...this.requestLog];
|
|
2519
|
+
}
|
|
2520
|
+
tokens() {
|
|
2521
|
+
return [...this.tokenLog];
|
|
2522
|
+
}
|
|
2523
|
+
reset() {
|
|
2524
|
+
this.requestLog = [];
|
|
2525
|
+
this.tokenLog = [];
|
|
2526
|
+
}
|
|
2527
|
+
};
|
|
2528
|
+
function push(list, entry) {
|
|
2529
|
+
list.push(entry);
|
|
2530
|
+
if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
|
|
2531
|
+
}
|
|
2532
|
+
|
|
2533
|
+
// src/coverage.ts
|
|
2534
|
+
import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
2535
|
+
import { join as join2, resolve as resolve2 } from "path";
|
|
2536
|
+
var COVERAGE_GROUPS = [
|
|
2537
|
+
{
|
|
2538
|
+
name: "Identity",
|
|
2539
|
+
items: [
|
|
2540
|
+
{ id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
|
|
2541
|
+
{ id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
|
|
2542
|
+
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
2543
|
+
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
2544
|
+
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
2545
|
+
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
|
|
2546
|
+
]
|
|
2547
|
+
},
|
|
2548
|
+
{
|
|
2549
|
+
name: "Organizations",
|
|
2550
|
+
items: [
|
|
2551
|
+
{ id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
|
|
2552
|
+
{ id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
|
|
2553
|
+
{ id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
|
|
2554
|
+
{ id: "organization.non-member", label: "Non-member refused", hint: "Ask for a token or sign-in for an organization the user does not belong to." },
|
|
2555
|
+
{ id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
|
|
2556
|
+
]
|
|
2557
|
+
},
|
|
2558
|
+
{
|
|
2559
|
+
name: "Permissions",
|
|
2560
|
+
items: [
|
|
2561
|
+
{ id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
|
|
2562
|
+
{ id: "permission.different-sets", label: "Different permissions in one organization", hint: "Mint tokens for two users in one organization with different permissions, such as an admin and a viewer." },
|
|
2563
|
+
{ id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
|
|
2564
|
+
{ id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
|
|
2565
|
+
{ id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
|
|
2566
|
+
]
|
|
2567
|
+
},
|
|
2568
|
+
{
|
|
2569
|
+
name: "Token validation",
|
|
2570
|
+
items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
|
|
2571
|
+
(kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
|
|
2572
|
+
)
|
|
2573
|
+
},
|
|
2574
|
+
{
|
|
2575
|
+
name: "Sessions",
|
|
2576
|
+
items: [
|
|
2577
|
+
{ id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
|
|
2578
|
+
{ id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
|
|
2579
|
+
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
2580
|
+
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
2581
|
+
{ id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
|
|
2582
|
+
]
|
|
2583
|
+
},
|
|
2584
|
+
{
|
|
2585
|
+
name: "Machine-to-machine",
|
|
2586
|
+
items: [
|
|
2587
|
+
{ id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
|
|
2588
|
+
{ id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
|
|
2589
|
+
{ id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
|
|
2590
|
+
{ id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
|
|
2591
|
+
]
|
|
2592
|
+
},
|
|
2593
|
+
{
|
|
2594
|
+
name: "Kinde APIs",
|
|
2595
|
+
items: [
|
|
2596
|
+
{ id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
|
|
2597
|
+
{ id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
|
|
2598
|
+
{ id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
|
|
2599
|
+
{ id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
|
|
2600
|
+
]
|
|
2601
|
+
},
|
|
2602
|
+
{
|
|
2603
|
+
name: "Webhooks",
|
|
2604
|
+
items: [
|
|
2605
|
+
{ id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
|
|
2606
|
+
{ id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
|
|
2607
|
+
{ id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
|
|
2608
|
+
{ id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
|
|
2609
|
+
{ id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
|
|
2610
|
+
]
|
|
2611
|
+
},
|
|
2612
|
+
{
|
|
2613
|
+
name: "Outages",
|
|
2614
|
+
items: [
|
|
2615
|
+
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
2616
|
+
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
2617
|
+
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
2618
|
+
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
|
|
2619
|
+
]
|
|
2620
|
+
}
|
|
2621
|
+
];
|
|
2622
|
+
var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
|
|
2623
|
+
function tokenLabel(kind) {
|
|
2624
|
+
return {
|
|
2625
|
+
expired: "Expired token",
|
|
2626
|
+
"future-iat": "Token issued in the future",
|
|
2627
|
+
"wrong-issuer": "Wrong issuer",
|
|
2628
|
+
"wrong-audience": "Wrong audience",
|
|
2629
|
+
"bad-signature": "Tampered signature",
|
|
2630
|
+
"unknown-key": "Unknown signing key",
|
|
2631
|
+
unsigned: "Unsigned token",
|
|
2632
|
+
"missing-subject": "No subject"
|
|
2633
|
+
}[kind];
|
|
2634
|
+
}
|
|
2635
|
+
var CoverageRecorder = class {
|
|
2636
|
+
hits = /* @__PURE__ */ new Map();
|
|
2637
|
+
userOrganizations = /* @__PURE__ */ new Map();
|
|
2638
|
+
organizationUsers = /* @__PURE__ */ new Map();
|
|
2639
|
+
organizationPermissionSets = /* @__PURE__ */ new Map();
|
|
2640
|
+
hit(id) {
|
|
2641
|
+
if (!ALL_IDS.has(id)) return;
|
|
2642
|
+
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
2643
|
+
}
|
|
2644
|
+
/** Called for every access token the testkit signs. */
|
|
2645
|
+
observeAccessToken(payload, invalid2) {
|
|
2646
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
2647
|
+
this.hit("m2m.token");
|
|
2648
|
+
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
2649
|
+
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
2650
|
+
if (invalid2) this.hit("m2m.invalid");
|
|
2651
|
+
return;
|
|
2652
|
+
}
|
|
2653
|
+
if (invalid2 === "missing-organization") return this.hit("organization.missing");
|
|
2654
|
+
if (invalid2 === "missing-permissions") return this.hit("permission.none");
|
|
2655
|
+
if (invalid2) return this.hit(`token.${invalid2}`);
|
|
2656
|
+
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
2657
|
+
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
2658
|
+
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
2659
|
+
if (subject) this.hit("identity.user");
|
|
2660
|
+
if (!organization) this.hit("identity.no-organization");
|
|
2661
|
+
if (permissions.length > 0) this.hit("permission.granted");
|
|
2662
|
+
else this.hit("permission.none");
|
|
2663
|
+
if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
|
|
2664
|
+
if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
|
|
2665
|
+
if (!organization) return;
|
|
2666
|
+
this.hit("organization.token");
|
|
2667
|
+
if (subject) {
|
|
2668
|
+
const organizations = add(this.userOrganizations, subject, organization);
|
|
2669
|
+
if (organizations.size > 1) this.hit("organization.two-for-one-user");
|
|
2670
|
+
add(this.organizationUsers, organization, subject);
|
|
2671
|
+
const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
|
|
2672
|
+
const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
|
|
2673
|
+
if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
|
|
2674
|
+
}
|
|
2675
|
+
const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
|
|
2676
|
+
if (sets.size > 1) this.hit("permission.different-sets");
|
|
2677
|
+
}
|
|
2678
|
+
report() {
|
|
2679
|
+
return buildReport(Object.fromEntries(this.hits));
|
|
2680
|
+
}
|
|
2681
|
+
snapshot() {
|
|
2682
|
+
return { version: 1, hits: Object.fromEntries(this.hits) };
|
|
2683
|
+
}
|
|
2684
|
+
reset() {
|
|
2685
|
+
this.hits.clear();
|
|
2686
|
+
this.userOrganizations.clear();
|
|
2687
|
+
this.organizationUsers.clear();
|
|
2688
|
+
this.organizationPermissionSets.clear();
|
|
2689
|
+
}
|
|
2690
|
+
/** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
|
|
2691
|
+
write(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2692
|
+
const folder = resolve2(directory);
|
|
2693
|
+
mkdirSync2(folder, { recursive: true });
|
|
2694
|
+
const file = join2(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
|
|
2695
|
+
writeFileSync2(file, `${JSON.stringify(this.snapshot())}
|
|
2696
|
+
`);
|
|
2697
|
+
return file;
|
|
2698
|
+
}
|
|
2699
|
+
};
|
|
2700
|
+
var DEFAULT_COVERAGE_DIRECTORY = join2(".kinde-testkit", "coverage");
|
|
2701
|
+
function add(map, key, value) {
|
|
2702
|
+
let set2 = map.get(key);
|
|
2703
|
+
if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
|
|
2704
|
+
set2.add(value);
|
|
2705
|
+
return set2;
|
|
2706
|
+
}
|
|
2707
|
+
function buildReport(hits) {
|
|
2708
|
+
const groups = COVERAGE_GROUPS.map((group) => {
|
|
2709
|
+
const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
|
|
2710
|
+
return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
|
|
2711
|
+
});
|
|
2712
|
+
return {
|
|
2713
|
+
covered: groups.reduce((sum, g) => sum + g.covered, 0),
|
|
2714
|
+
total: groups.reduce((sum, g) => sum + g.total, 0),
|
|
2715
|
+
groups
|
|
2716
|
+
};
|
|
2717
|
+
}
|
|
2718
|
+
function mergeSnapshots(snapshots) {
|
|
2719
|
+
const hits = {};
|
|
2720
|
+
for (const snapshot of snapshots) {
|
|
2721
|
+
for (const [id, count] of Object.entries(snapshot.hits ?? {})) hits[id] = (hits[id] ?? 0) + count;
|
|
2722
|
+
}
|
|
2723
|
+
return hits;
|
|
2724
|
+
}
|
|
2725
|
+
function readCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2726
|
+
const folder = resolve2(directory);
|
|
2727
|
+
let names = [];
|
|
2728
|
+
try {
|
|
2729
|
+
names = readdirSync(folder).filter((name) => name.endsWith(".json"));
|
|
2730
|
+
} catch {
|
|
2731
|
+
}
|
|
2732
|
+
const snapshots = names.map((name) => JSON.parse(readFileSync2(join2(folder, name), "utf8")));
|
|
2733
|
+
return { files: names.length, report: buildReport(mergeSnapshots(snapshots)) };
|
|
2734
|
+
}
|
|
2735
|
+
function clearCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
2736
|
+
rmSync(resolve2(directory), { recursive: true, force: true });
|
|
2737
|
+
}
|
|
2738
|
+
function formatCoverageReport(report, options = {}) {
|
|
2739
|
+
const width = Math.max(...report.groups.map((g) => g.name.length)) + 3;
|
|
2740
|
+
const lines = ["Kinde authentication coverage", ""];
|
|
2741
|
+
for (const group of report.groups) {
|
|
2742
|
+
lines.push(`${group.name.padEnd(width)}${String(group.covered).padStart(2)}/${group.total}`);
|
|
2743
|
+
}
|
|
2744
|
+
lines.push("", `Overall: ${report.covered}/${report.total}`);
|
|
2745
|
+
if (options.missing !== false) {
|
|
2746
|
+
const missing = report.groups.flatMap((g) => g.items.filter((i) => !i.covered).map((i) => ({ group: g.name, ...i })));
|
|
2747
|
+
if (missing.length > 0) {
|
|
2748
|
+
lines.push("", "Not covered:");
|
|
2749
|
+
for (const item of missing) lines.push(` ${item.group}: ${item.label}. ${item.hint}`);
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
return lines.join("\n");
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
// src/dashboard.ts
|
|
2756
|
+
var STYLE2 = `
|
|
2757
|
+
:root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--ok:#1d7a46;--bad:#b42318;--soft:#f0f0ec}
|
|
2758
|
+
@media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--ok:#5cc78a;--bad:#f0817a;--soft:#232327}}
|
|
2759
|
+
*{box-sizing:border-box}
|
|
2760
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
2761
|
+
header{position:sticky;top:0;z-index:1;display:flex;flex-wrap:wrap;gap:16px;align-items:center;justify-content:space-between;padding:14px 28px;background:var(--card);border-bottom:1px solid var(--line)}
|
|
2762
|
+
header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
|
|
2763
|
+
header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2764
|
+
nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
|
|
2765
|
+
nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
|
|
2766
|
+
main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
|
|
2767
|
+
section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
|
|
2768
|
+
h2{margin:0 0 4px;font-size:16px;font-weight:600}
|
|
2769
|
+
.sub{margin:0 0 14px;color:var(--muted);font-size:13px}
|
|
2770
|
+
table{width:100%;border-collapse:collapse;font-size:13px}
|
|
2771
|
+
th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
|
|
2772
|
+
td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
|
|
2773
|
+
tr:last-child td{border-bottom:0}
|
|
2774
|
+
code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
2775
|
+
.chips{display:flex;flex-wrap:wrap;gap:4px}
|
|
2776
|
+
.chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
|
|
2777
|
+
.ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
|
|
2778
|
+
.empty{color:var(--muted);font-size:13px;margin:0}
|
|
2779
|
+
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
|
|
2780
|
+
label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
|
|
2781
|
+
input,select{height:32px;padding:0 8px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:13px ui-sans-serif,system-ui,sans-serif}
|
|
2782
|
+
input[type=checkbox]{height:auto}
|
|
2783
|
+
button{height:32px;padding:0 12px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:500 13px ui-sans-serif,system-ui,sans-serif;cursor:pointer}
|
|
2784
|
+
button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
|
|
2785
|
+
button:hover{border-color:var(--muted)}
|
|
2786
|
+
details summary{cursor:pointer;color:var(--muted)}
|
|
2787
|
+
pre{margin:8px 0 0;padding:10px;background:var(--soft);border-radius:6px;overflow:auto;max-height:320px;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-all}
|
|
2788
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
|
|
2789
|
+
.group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
|
|
2790
|
+
.group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
|
|
2791
|
+
.notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
|
|
2792
|
+
.split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
|
|
2793
|
+
`;
|
|
2794
|
+
function renderDashboard(data) {
|
|
2795
|
+
const e = escapeHtml;
|
|
2796
|
+
const { seed } = data;
|
|
2797
|
+
const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
|
|
2798
|
+
const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
|
|
2799
|
+
const users = seed.users.length ? table(
|
|
2800
|
+
["User", "ID", "Organizations", "Sign-ins", "Status"],
|
|
2801
|
+
seed.users.map((user) => [
|
|
2802
|
+
e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
|
|
2803
|
+
`<code>${e(user.id)}</code>`,
|
|
2804
|
+
chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
|
|
2805
|
+
String(data.signIns(user.id)),
|
|
2806
|
+
data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
|
|
2807
|
+
])
|
|
2808
|
+
) : empty("No users yet. Seed some, or sign in with any email.");
|
|
2809
|
+
const organizations = seed.organizations.length ? table(
|
|
2810
|
+
["Organization", "Code", "Members"],
|
|
2811
|
+
seed.organizations.map((org) => [
|
|
2812
|
+
e(org.name),
|
|
2813
|
+
`<code>${e(org.code)}</code>`,
|
|
2814
|
+
String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
|
|
2815
|
+
])
|
|
2816
|
+
) : empty("No organizations.");
|
|
2817
|
+
const memberships = seed.memberships.length ? table(
|
|
2818
|
+
["User", "Organization", "Roles", "Permissions in the token"],
|
|
2819
|
+
seed.memberships.map((m) => [
|
|
2820
|
+
e(userLabel(m.userId)),
|
|
2821
|
+
e(orgName(m.organizationCode)),
|
|
2822
|
+
chips(m.roles),
|
|
2823
|
+
chips(effectivePermissions(seed, m))
|
|
2824
|
+
])
|
|
2825
|
+
) : empty("No memberships.");
|
|
2826
|
+
const applications = seed.applications.length ? table(
|
|
2827
|
+
["Client ID", "Organization", "Scopes"],
|
|
2828
|
+
seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
|
|
2829
|
+
) : "";
|
|
2830
|
+
const tokens = data.tokens.length ? table(
|
|
2831
|
+
["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
|
|
2832
|
+
[...data.tokens].reverse().slice(0, 50).map((t) => [
|
|
2833
|
+
time(t.at),
|
|
2834
|
+
t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
|
|
2835
|
+
`<code>${e(t.subject ?? "none")}</code>`,
|
|
2836
|
+
e(t.organization ?? "none"),
|
|
2837
|
+
chips(t.permissions),
|
|
2838
|
+
`<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
|
|
2839
|
+
])
|
|
2840
|
+
) : empty("No tokens issued yet.");
|
|
2841
|
+
const requests = data.requests.length ? table(
|
|
2842
|
+
["Time", "Request", "Status", "Time taken"],
|
|
2843
|
+
[...data.requests].reverse().slice(0, 100).map((r) => [
|
|
2844
|
+
time(r.at),
|
|
2845
|
+
`<code>${e(r.method)} ${e(r.path)}</code>`,
|
|
2846
|
+
`<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
|
|
2847
|
+
`${r.durationMs} ms`
|
|
2848
|
+
])
|
|
2849
|
+
) : empty("No requests yet.");
|
|
2850
|
+
const deliveries = data.deliveries.length ? table(
|
|
2851
|
+
["Event", "Endpoint", "Copy", "Result"],
|
|
2852
|
+
[...data.deliveries].reverse().slice(0, 50).map((d) => [
|
|
2853
|
+
`<code>${e(d.type)}</code>`,
|
|
2854
|
+
`<code>${e(d.url)}</code>`,
|
|
2855
|
+
String(d.copy),
|
|
2856
|
+
d.delivered ? `<span class="ok">Delivered</span>` : `<span class="bad">${e(d.attempts.map((a) => a.status === null ? a.error ?? "error" : String(a.status)).join(", ") || "Not sent")}</span>`
|
|
2857
|
+
])
|
|
2858
|
+
) : empty("No webhooks sent yet.");
|
|
2859
|
+
const endpoints = data.endpoints.length ? `<p class="sub">Endpoints: ${data.endpoints.map((x) => `<code>${e(x.url)}</code>`).join(", ")}</p>` : `<p class="sub">No webhook endpoints. Add one in the seed, with <code>start --webhook</code> or <code>addEndpoint()</code>.</p>`;
|
|
2860
|
+
const webhookForm = data.endpoints.length ? form(
|
|
2861
|
+
"/dashboard/webhooks",
|
|
2862
|
+
`<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
|
|
2863
|
+
<label>User<select name="user"><option value="">First seeded user</option>${seed.users.map((u) => `<option value="${e(u.id)}">${e(u.email ?? u.id)}</option>`).join("")}</select></label>
|
|
2864
|
+
<label>Variant<select name="invalid"><option value="">Valid</option><option>bad-signature</option><option>unknown-key</option><option>unsigned</option><option>stale</option></select></label>
|
|
2865
|
+
<label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
|
|
2866
|
+
<button class="primary">Send</button>`
|
|
2867
|
+
) : "";
|
|
2868
|
+
const failures = data.failures.length ? table(
|
|
2869
|
+
["Path", "Method", "Effect", "Remaining", "Hits", ""],
|
|
2870
|
+
data.failures.map((f) => [
|
|
2871
|
+
`<code>${e(f.path)}</code>`,
|
|
2872
|
+
e(f.method ?? "any"),
|
|
2873
|
+
e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
|
|
2874
|
+
f.remaining === null ? "Until removed" : String(f.remaining),
|
|
2875
|
+
String(f.hits),
|
|
2876
|
+
form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
|
|
2877
|
+
])
|
|
2878
|
+
) : empty("No failure rules.");
|
|
2879
|
+
const coverage = `<div class="grid">${data.coverage.groups.map(
|
|
2880
|
+
(g) => `<div><div class="group"><span>${e(g.name)}</span><span class="${g.covered === g.total ? "ok" : "muted"}">${g.covered}/${g.total}</span></div><ul>${g.items.map((i) => `<li title="${e(i.hint)}"><span class="${i.covered ? "ok" : "muted"}">${i.covered ? "\u2713" : "\u25CB"}</span> ${e(i.label)}</li>`).join("")}</ul></div>`
|
|
2881
|
+
).join("")}</div>`;
|
|
2882
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2883
|
+
${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
|
|
2884
|
+
<title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
|
|
2885
|
+
<header>
|
|
2886
|
+
<div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
|
|
2887
|
+
<nav><a href="#users">Users</a><a href="#tokens">Tokens</a><a href="#requests">Requests</a><a href="#webhooks">Webhooks</a><a href="#failures">Failures</a><a href="#coverage">Coverage</a></nav>
|
|
2888
|
+
<div class="row">
|
|
2889
|
+
<a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
|
|
2890
|
+
${form("/dashboard/reset", `<button>Reset state</button>`)}
|
|
2891
|
+
</div>
|
|
2892
|
+
</header>
|
|
2893
|
+
<main>
|
|
2894
|
+
${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
|
|
2895
|
+
<section id="users"><h2>Users</h2><p class="sub">Seeded users, users created through the Management API, and emails that signed in.</p>${users}</section>
|
|
2896
|
+
<div class="split">
|
|
2897
|
+
<section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
|
|
2898
|
+
<section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
|
|
2899
|
+
</div>
|
|
2900
|
+
${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
|
|
2901
|
+
<section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
|
|
2902
|
+
<section id="requests"><h2>Requests</h2><p class="sub">The latest 100 requests your app and tests made. Codes, secrets and refresh tokens are hidden.</p>${requests}</section>
|
|
2903
|
+
<section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
|
|
2904
|
+
<section id="failures"><h2>Failures</h2><p class="sub">Make an endpoint fail, slow down or hang. Applies to Kinde endpoints, not <code>/testkit</code> or this page.</p>
|
|
2905
|
+
${form(
|
|
2906
|
+
"/dashboard/failures",
|
|
2907
|
+
`<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
|
|
2908
|
+
<label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
|
|
2909
|
+
<label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
|
|
2910
|
+
<label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
|
|
2911
|
+
<label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
|
|
2912
|
+
<label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
|
|
2913
|
+
<button class="primary">Add rule</button>`
|
|
2914
|
+
)}
|
|
2915
|
+
<div style="margin-top:14px">${failures}</div>
|
|
2916
|
+
${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
|
|
2917
|
+
</section>
|
|
2918
|
+
<section id="coverage"><h2>Coverage: ${data.coverage.covered}/${data.coverage.total}</h2><p class="sub">Authentication scenarios the testkit produced since it started or was reset. Hover an item to see how to cover it.</p>${coverage}
|
|
2919
|
+
<div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
|
|
2920
|
+
</main></body></html>`;
|
|
2921
|
+
}
|
|
2922
|
+
function table(headers, rows) {
|
|
2923
|
+
return `<table><thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
|
|
2924
|
+
}
|
|
2925
|
+
function chips(values) {
|
|
2926
|
+
if (values.length === 0) return `<span class="muted">none</span>`;
|
|
2927
|
+
return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
|
|
2928
|
+
}
|
|
2929
|
+
function empty(text) {
|
|
2930
|
+
return `<p class="empty">${escapeHtml(text)}</p>`;
|
|
2931
|
+
}
|
|
2932
|
+
function time(iso) {
|
|
2933
|
+
return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
|
|
2934
|
+
}
|
|
2935
|
+
function form(action, body) {
|
|
2936
|
+
return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
|
|
2937
|
+
}
|
|
2938
|
+
|
|
2939
|
+
// src/seed-file.ts
|
|
2940
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
|
|
2941
|
+
import { extname, resolve as resolve3 } from "path";
|
|
2942
|
+
import { pathToFileURL } from "url";
|
|
2943
|
+
import { parse as parseYaml } from "yaml";
|
|
2944
|
+
var DEFAULT_SEED_FILES = [
|
|
2945
|
+
"kinde-testkit.json",
|
|
2946
|
+
"kinde-testkit.yaml",
|
|
2947
|
+
"kinde-testkit.yml",
|
|
2948
|
+
"kinde-testkit.ts",
|
|
2949
|
+
"kinde-testkit.mts",
|
|
2950
|
+
"kinde-testkit.js",
|
|
2951
|
+
"kinde-testkit.mjs"
|
|
2952
|
+
];
|
|
2953
|
+
function findSeedFile(directory = ".") {
|
|
2954
|
+
return DEFAULT_SEED_FILES.map((name) => resolve3(directory, name)).find((path) => existsSync2(path));
|
|
2955
|
+
}
|
|
2956
|
+
async function loadSeedFile(path) {
|
|
2957
|
+
const file = resolve3(path);
|
|
2958
|
+
const extension = extname(file).toLowerCase();
|
|
2959
|
+
let value;
|
|
2960
|
+
try {
|
|
2961
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
2962
|
+
value = parseYaml(readFileSync3(file, "utf8"));
|
|
2963
|
+
} else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
|
|
2964
|
+
const module = await import(pathToFileURL(file).href);
|
|
2965
|
+
value = module.seed ?? module.default;
|
|
2966
|
+
if (value && typeof value === "object" && "default" in value && !("users" in value)) {
|
|
2967
|
+
value = value.default;
|
|
2968
|
+
}
|
|
2969
|
+
} else {
|
|
2970
|
+
value = JSON.parse(readFileSync3(file, "utf8"));
|
|
2971
|
+
}
|
|
2972
|
+
} catch (error) {
|
|
2973
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2974
|
+
const details = [message];
|
|
2975
|
+
if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message)) {
|
|
2976
|
+
details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
|
|
2977
|
+
}
|
|
2978
|
+
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
|
|
2979
|
+
}
|
|
2980
|
+
if (value === null || value === void 0) value = {};
|
|
2981
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
2982
|
+
throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
|
|
2983
|
+
}
|
|
2984
|
+
return value;
|
|
2419
2985
|
}
|
|
2420
2986
|
|
|
2421
2987
|
// src/server.ts
|
|
@@ -2430,30 +2996,49 @@ async function startKindeTestkit(options = {}) {
|
|
|
2430
2996
|
`kinde-testkit will not listen on ${host}. It signs tokens for any identity, so it stays on localhost unless you pass --allow-public (allowPublic: true in code).`
|
|
2431
2997
|
);
|
|
2432
2998
|
}
|
|
2433
|
-
const
|
|
2999
|
+
const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
|
|
3000
|
+
const seed = resolveSeed(seedInput);
|
|
2434
3001
|
const failures = new FailureInjector();
|
|
2435
3002
|
let ready;
|
|
2436
|
-
const testkitReady = new Promise((
|
|
3003
|
+
const testkitReady = new Promise((resolve4) => ready = resolve4);
|
|
2437
3004
|
const listener = (req, res) => {
|
|
2438
3005
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
2439
3006
|
};
|
|
2440
3007
|
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
2441
3008
|
const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
|
|
2442
|
-
await new Promise((
|
|
3009
|
+
await new Promise((resolve4, reject) => {
|
|
2443
3010
|
server.once("error", reject);
|
|
2444
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
3011
|
+
server.listen(options.port ?? 4400, host, () => resolve4());
|
|
2445
3012
|
});
|
|
2446
3013
|
const { port } = server.address();
|
|
2447
|
-
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
3014
|
+
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
2448
3015
|
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
2449
3016
|
const testkit = await KindeTestkit.create({
|
|
2450
|
-
issuer: options.issuer ??
|
|
2451
|
-
audience: options.audience ??
|
|
2452
|
-
clientId: options.clientId ??
|
|
3017
|
+
issuer: options.issuer ?? seedInput.issuer ?? url,
|
|
3018
|
+
audience: options.audience ?? seedInput.audience,
|
|
3019
|
+
clientId: options.clientId ?? seedInput.clientId
|
|
2453
3020
|
});
|
|
3021
|
+
const coverage = new CoverageRecorder();
|
|
3022
|
+
const activity = new ActivityLog();
|
|
3023
|
+
testkit.observe({
|
|
3024
|
+
accessToken(payload, invalid2, token) {
|
|
3025
|
+
coverage.observeAccessToken(payload, invalid2);
|
|
3026
|
+
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
3027
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid2, token);
|
|
3028
|
+
},
|
|
3029
|
+
idToken(payload, token) {
|
|
3030
|
+
coverage.hit("identity.id-token");
|
|
3031
|
+
activity.token("id", payload, void 0, token);
|
|
3032
|
+
},
|
|
3033
|
+
anonymous() {
|
|
3034
|
+
coverage.hit("identity.anonymous");
|
|
3035
|
+
}
|
|
3036
|
+
});
|
|
3037
|
+
const observe = (id) => coverage.hit(id);
|
|
2454
3038
|
const directory = new Directory(seed);
|
|
2455
3039
|
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
2456
|
-
|
|
3040
|
+
webhooks.observe = observe;
|
|
3041
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
|
|
2457
3042
|
const management = new ManagementApi(testkit, directory, webhooks);
|
|
2458
3043
|
const account = new AccountApi(testkit, directory);
|
|
2459
3044
|
const reset = () => {
|
|
@@ -2462,7 +3047,23 @@ async function startKindeTestkit(options = {}) {
|
|
|
2462
3047
|
webhooks.reset();
|
|
2463
3048
|
directory.restore();
|
|
2464
3049
|
};
|
|
2465
|
-
|
|
3050
|
+
const loadSeed = (input) => {
|
|
3051
|
+
const next = resolveSeed(input);
|
|
3052
|
+
directory.load(next);
|
|
3053
|
+
webhooks.replaceSeededEndpoints(next.webhooks);
|
|
3054
|
+
reset();
|
|
3055
|
+
};
|
|
3056
|
+
let closed = false;
|
|
3057
|
+
const close = () => new Promise((resolve4, reject) => {
|
|
3058
|
+
if (closed) return resolve4();
|
|
3059
|
+
closed = true;
|
|
3060
|
+
if (options.coverage) {
|
|
3061
|
+
coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
|
|
3062
|
+
}
|
|
3063
|
+
server.closeAllConnections();
|
|
3064
|
+
server.close((error) => error ? reject(error) : resolve4());
|
|
3065
|
+
});
|
|
3066
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
|
|
2466
3067
|
return {
|
|
2467
3068
|
url,
|
|
2468
3069
|
issuer: testkit.issuer,
|
|
@@ -2474,23 +3075,37 @@ async function startKindeTestkit(options = {}) {
|
|
|
2474
3075
|
webhooks,
|
|
2475
3076
|
directory,
|
|
2476
3077
|
certificatePath: certificate?.certPath ?? null,
|
|
3078
|
+
coverage,
|
|
3079
|
+
activity,
|
|
3080
|
+
loadSeed,
|
|
2477
3081
|
reset,
|
|
2478
|
-
close
|
|
2479
|
-
server.closeAllConnections();
|
|
2480
|
-
server.close((error) => error ? reject(error) : resolve2());
|
|
2481
|
-
})
|
|
3082
|
+
close
|
|
2482
3083
|
};
|
|
2483
3084
|
}
|
|
2484
3085
|
async function handle(req, res, context) {
|
|
2485
|
-
const { testkit, auth, seed, failures, webhooks } = context;
|
|
3086
|
+
const { testkit, auth, seed, failures, webhooks, coverage } = context;
|
|
2486
3087
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
2487
3088
|
const { pathname } = url;
|
|
2488
3089
|
const method = req.method ?? "GET";
|
|
2489
|
-
|
|
3090
|
+
const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
|
|
3091
|
+
let injected = false;
|
|
3092
|
+
if (!internal && pathname !== "/favicon.ico") {
|
|
3093
|
+
const started = Date.now();
|
|
3094
|
+
res.once("close", () => {
|
|
3095
|
+
context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
|
|
3096
|
+
});
|
|
3097
|
+
}
|
|
3098
|
+
if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
|
|
3099
|
+
if (!internal) {
|
|
2490
3100
|
const failure = failures.take(method, pathname);
|
|
2491
3101
|
if (failure) {
|
|
3102
|
+
injected = true;
|
|
3103
|
+
if (failure.hang) coverage.hit("outage.timeout");
|
|
3104
|
+
else if (failure.status === 429) coverage.hit("outage.rate-limit");
|
|
3105
|
+
else if (failure.status !== null) coverage.hit("outage.error");
|
|
3106
|
+
if (failure.delayMs > 0) coverage.hit("outage.slow");
|
|
2492
3107
|
if (failure.hang) return;
|
|
2493
|
-
if (failure.delayMs > 0) await new Promise((
|
|
3108
|
+
if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
|
|
2494
3109
|
if (failure.status !== null) {
|
|
2495
3110
|
const headers = {};
|
|
2496
3111
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
@@ -2499,8 +3114,15 @@ async function handle(req, res, context) {
|
|
|
2499
3114
|
}
|
|
2500
3115
|
}
|
|
2501
3116
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
2502
|
-
if (await context.management.handle(req, res, url, async () => await readJson(req)))
|
|
2503
|
-
|
|
3117
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) {
|
|
3118
|
+
if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
|
|
3119
|
+
else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
|
|
3120
|
+
return;
|
|
3121
|
+
}
|
|
3122
|
+
if (await context.account.handle(req, res, url)) {
|
|
3123
|
+
if (res.statusCode < 400) coverage.hit("api.account");
|
|
3124
|
+
return;
|
|
3125
|
+
}
|
|
2504
3126
|
if (method === "GET" && pathname === "/testkit/portal") {
|
|
2505
3127
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
2506
3128
|
res.end(
|
|
@@ -2557,11 +3179,119 @@ async function handle(req, res, context) {
|
|
|
2557
3179
|
}
|
|
2558
3180
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
2559
3181
|
const body = await readJson(req);
|
|
2560
|
-
|
|
3182
|
+
let accessToken;
|
|
3183
|
+
try {
|
|
3184
|
+
accessToken = await issueToken(testkit, seed, body);
|
|
3185
|
+
} catch (error) {
|
|
3186
|
+
if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
|
|
3187
|
+
throw error;
|
|
3188
|
+
}
|
|
2561
3189
|
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
2562
3190
|
}
|
|
3191
|
+
if (method === "GET" && pathname === "/testkit/coverage") {
|
|
3192
|
+
return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
|
|
3193
|
+
}
|
|
3194
|
+
if (method === "DELETE" && pathname === "/testkit/coverage") {
|
|
3195
|
+
coverage.reset();
|
|
3196
|
+
return sendJson4(res, 200, { ok: true });
|
|
3197
|
+
}
|
|
3198
|
+
if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
|
|
3199
|
+
if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
|
|
3200
|
+
if (method === "POST" && pathname === "/testkit/seed") {
|
|
3201
|
+
const body = await readJson(req);
|
|
3202
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
3203
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
3204
|
+
}
|
|
3205
|
+
context.loadSeed(body);
|
|
3206
|
+
return sendJson4(res, 200, {
|
|
3207
|
+
ok: true,
|
|
3208
|
+
users: seed.users.length,
|
|
3209
|
+
organizations: seed.organizations.length,
|
|
3210
|
+
memberships: seed.memberships.length
|
|
3211
|
+
});
|
|
3212
|
+
}
|
|
3213
|
+
if (method === "POST" && pathname === "/testkit/stop") {
|
|
3214
|
+
sendJson4(res, 200, { ok: true });
|
|
3215
|
+
res.once("finish", () => void context.close().catch(() => void 0));
|
|
3216
|
+
return;
|
|
3217
|
+
}
|
|
2563
3218
|
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
2564
3219
|
}
|
|
3220
|
+
async function dashboard(req, res, url, context) {
|
|
3221
|
+
const method = req.method ?? "GET";
|
|
3222
|
+
const { pathname } = url;
|
|
3223
|
+
if (method === "GET" && pathname === "/dashboard") {
|
|
3224
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
3225
|
+
res.end(
|
|
3226
|
+
renderDashboard({
|
|
3227
|
+
issuer: context.testkit.issuer,
|
|
3228
|
+
seed: context.seed,
|
|
3229
|
+
suspended: (id) => context.directory.isSuspended(id),
|
|
3230
|
+
signIns: (id) => {
|
|
3231
|
+
const user = context.directory.user(id);
|
|
3232
|
+
return user ? context.directory.meta(user).totalSignIns : 0;
|
|
3233
|
+
},
|
|
3234
|
+
tokens: context.activity.tokens(),
|
|
3235
|
+
requests: context.activity.requests(),
|
|
3236
|
+
deliveries: context.webhooks.deliveries(),
|
|
3237
|
+
endpoints: context.webhooks.listEndpoints(),
|
|
3238
|
+
failures: context.failures.list(),
|
|
3239
|
+
coverage: context.coverage.report(),
|
|
3240
|
+
webhookTypes: WEBHOOK_EVENT_TYPES,
|
|
3241
|
+
live: url.searchParams.has("live"),
|
|
3242
|
+
notice: url.searchParams.get("notice")
|
|
3243
|
+
})
|
|
3244
|
+
);
|
|
3245
|
+
return;
|
|
3246
|
+
}
|
|
3247
|
+
if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
3248
|
+
const origin = req.headers.origin;
|
|
3249
|
+
if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
|
|
3250
|
+
return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
|
|
3251
|
+
}
|
|
3252
|
+
const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
|
|
3253
|
+
let notice = "Done.";
|
|
3254
|
+
try {
|
|
3255
|
+
if (pathname === "/dashboard/reset") {
|
|
3256
|
+
context.reset();
|
|
3257
|
+
notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
|
|
3258
|
+
} else if (pathname === "/dashboard/coverage/reset") {
|
|
3259
|
+
context.coverage.reset();
|
|
3260
|
+
notice = "Cleared coverage.";
|
|
3261
|
+
} else if (pathname === "/dashboard/failures/clear") {
|
|
3262
|
+
context.failures.clear();
|
|
3263
|
+
notice = "Removed every failure rule.";
|
|
3264
|
+
} else if (pathname === "/dashboard/failures") {
|
|
3265
|
+
const rule = { path: form2.path ?? "" };
|
|
3266
|
+
if (form2.method) rule.method = form2.method;
|
|
3267
|
+
if (form2.status) rule.status = Number(form2.status);
|
|
3268
|
+
if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
|
|
3269
|
+
if (form2.times) rule.times = Number(form2.times);
|
|
3270
|
+
if (form2.hang) rule.hang = true;
|
|
3271
|
+
const added = context.failures.add(rule);
|
|
3272
|
+
notice = `Added ${added.id} for ${added.path}.`;
|
|
3273
|
+
} else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
|
|
3274
|
+
const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
|
|
3275
|
+
notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
|
|
3276
|
+
} else if (pathname === "/dashboard/webhooks") {
|
|
3277
|
+
const deliveries = await context.webhooks.send({
|
|
3278
|
+
type: form2.type ?? "",
|
|
3279
|
+
user: form2.user || void 0,
|
|
3280
|
+
invalid: form2.invalid || void 0,
|
|
3281
|
+
duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
|
|
3282
|
+
});
|
|
3283
|
+
const delivered = deliveries.filter((d) => d.delivered).length;
|
|
3284
|
+
notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
|
|
3285
|
+
} else {
|
|
3286
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
|
|
3287
|
+
}
|
|
3288
|
+
} catch (error) {
|
|
3289
|
+
notice = error.message.replace(/\s+/g, " ").trim();
|
|
3290
|
+
}
|
|
3291
|
+
const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
|
|
3292
|
+
res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
|
|
3293
|
+
res.end();
|
|
3294
|
+
}
|
|
2565
3295
|
function discovery(testkit) {
|
|
2566
3296
|
const base = testkit.issuer;
|
|
2567
3297
|
return {
|
|
@@ -2886,13 +3616,64 @@ function parseEnvFile(text) {
|
|
|
2886
3616
|
}
|
|
2887
3617
|
return values;
|
|
2888
3618
|
}
|
|
3619
|
+
|
|
3620
|
+
// src/handle.ts
|
|
3621
|
+
async function kindeTest(options) {
|
|
3622
|
+
const testkit = options.testkit ?? await getDefaultTestkit();
|
|
3623
|
+
const token = await testkit.tokenFor(options.scenario, options.token);
|
|
3624
|
+
const headers = token ? { authorization: `Bearer ${token}` } : {};
|
|
3625
|
+
return {
|
|
3626
|
+
token,
|
|
3627
|
+
headers,
|
|
3628
|
+
principal: testkit.principalFor(options.scenario),
|
|
3629
|
+
request: { headers }
|
|
3630
|
+
};
|
|
3631
|
+
}
|
|
3632
|
+
|
|
3633
|
+
// src/sign-in-flow.ts
|
|
3634
|
+
function appLoginUrl(loginPath, options) {
|
|
3635
|
+
const params = new URLSearchParams({ login_hint: options.user });
|
|
3636
|
+
if (options.org) params.set("org_code", options.org);
|
|
3637
|
+
return `${loginPath}${loginPath.includes("?") ? "&" : "?"}${params}`;
|
|
3638
|
+
}
|
|
3639
|
+
function readSignInRequest(html) {
|
|
3640
|
+
const match = /name="request" value="([^"]+)"/.exec(html);
|
|
3641
|
+
if (!match) {
|
|
3642
|
+
throw new Error("The page is not the kinde-testkit sign-in page. Check that the app's KINDE_ISSUER_URL points at the testkit.");
|
|
3643
|
+
}
|
|
3644
|
+
return decodeEntities(match[1]);
|
|
3645
|
+
}
|
|
3646
|
+
function signInForm(request, options) {
|
|
3647
|
+
const form2 = { request, email: options.user };
|
|
3648
|
+
if (options.org) form2.org = options.org;
|
|
3649
|
+
return form2;
|
|
3650
|
+
}
|
|
3651
|
+
function signInFailure(status, html, options) {
|
|
3652
|
+
if (status === 200 && html.includes("Choose an organization")) {
|
|
3653
|
+
return new Error(`${options.user} belongs to more than one organization. Pass one with { org: "org_..." }.`);
|
|
3654
|
+
}
|
|
3655
|
+
const alert = /role="alert"[^>]*>([\s\S]*?)<\//.exec(html)?.[1];
|
|
3656
|
+
const text = alert ? decodeEntities(alert.replace(/<[^>]+>/g, "")).trim() : `the sign-in page answered ${status}`;
|
|
3657
|
+
return new Error(`kinde-testkit refused the sign-in: ${text}`);
|
|
3658
|
+
}
|
|
3659
|
+
function resolveLocation(location, from) {
|
|
3660
|
+
return new URL(location, from).toString();
|
|
3661
|
+
}
|
|
3662
|
+
function decodeEntities(value) {
|
|
3663
|
+
return value.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
3664
|
+
}
|
|
2889
3665
|
export {
|
|
3666
|
+
ActivityLog,
|
|
2890
3667
|
BILLING_EVENT_TYPES,
|
|
3668
|
+
COVERAGE_GROUPS,
|
|
3669
|
+
CoverageRecorder,
|
|
2891
3670
|
DEFAULT_AUTH_METHODS,
|
|
2892
3671
|
DEFAULT_CLIENT_ID,
|
|
3672
|
+
DEFAULT_COVERAGE_DIRECTORY,
|
|
2893
3673
|
DEFAULT_ISSUER,
|
|
2894
3674
|
DEFAULT_M2M_CLIENT_ID,
|
|
2895
3675
|
DEFAULT_SCOPES,
|
|
3676
|
+
DEFAULT_SEED_FILES,
|
|
2896
3677
|
Directory,
|
|
2897
3678
|
FailureInjector,
|
|
2898
3679
|
INVALID_TOKEN_KINDS,
|
|
@@ -2901,22 +3682,35 @@ export {
|
|
|
2901
3682
|
TestkitError,
|
|
2902
3683
|
WEBHOOK_EVENT_TYPES,
|
|
2903
3684
|
WebhookDispatcher,
|
|
3685
|
+
appLoginUrl,
|
|
3686
|
+
buildReport,
|
|
3687
|
+
clearCoverageDirectory,
|
|
2904
3688
|
createKindeOrganization,
|
|
2905
3689
|
createKindeToken,
|
|
2906
3690
|
createKindeUser,
|
|
2907
3691
|
createLocalCertificate,
|
|
2908
3692
|
createMembership,
|
|
2909
3693
|
ensureLocalCertificate,
|
|
3694
|
+
findSeedFile,
|
|
3695
|
+
formatCoverageReport,
|
|
2910
3696
|
getDefaultTestkit,
|
|
2911
3697
|
inspectToken,
|
|
2912
3698
|
isAuthenticated,
|
|
3699
|
+
kindeTest,
|
|
3700
|
+
loadSeedFile,
|
|
3701
|
+
mergeSnapshots,
|
|
2913
3702
|
parseEnvFile,
|
|
2914
3703
|
principalFromClaims,
|
|
3704
|
+
readCoverageDirectory,
|
|
3705
|
+
readSignInRequest,
|
|
2915
3706
|
resetFactories,
|
|
3707
|
+
resolveLocation,
|
|
2916
3708
|
resolveSeed,
|
|
2917
3709
|
runDoctor,
|
|
2918
3710
|
scenario,
|
|
2919
3711
|
seedScenario,
|
|
3712
|
+
signInFailure,
|
|
3713
|
+
signInForm,
|
|
2920
3714
|
startKindeTestkit,
|
|
2921
3715
|
toKindeRole
|
|
2922
3716
|
};
|