kinde-testkit 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +118 -5
- package/dist/cli.js +601 -11
- package/dist/index.cjs +417 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +95 -2
- package/dist/index.d.ts +95 -2
- package/dist/index.js +412 -11
- package/dist/index.js.map +1 -1
- package/dist/playwright.d.ts +27 -1
- package/dist/playwright.js +32 -7
- package/dist/playwright.js.map +1 -1
- package/dist/vitest.d.ts +54 -0
- package/dist/vitest.js +242 -11
- package/dist/vitest.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -23,7 +23,9 @@ __export(src_exports, {
|
|
|
23
23
|
DEFAULT_AUTH_METHODS: () => DEFAULT_AUTH_METHODS,
|
|
24
24
|
DEFAULT_CLIENT_ID: () => DEFAULT_CLIENT_ID,
|
|
25
25
|
DEFAULT_ISSUER: () => DEFAULT_ISSUER,
|
|
26
|
+
DEFAULT_M2M_CLIENT_ID: () => DEFAULT_M2M_CLIENT_ID,
|
|
26
27
|
DEFAULT_SCOPES: () => DEFAULT_SCOPES,
|
|
28
|
+
FailureInjector: () => FailureInjector,
|
|
27
29
|
INVALID_TOKEN_KINDS: () => INVALID_TOKEN_KINDS,
|
|
28
30
|
KindeTestkit: () => KindeTestkit,
|
|
29
31
|
ScenarioBuilder: () => ScenarioBuilder,
|
|
@@ -33,10 +35,13 @@ __export(src_exports, {
|
|
|
33
35
|
createKindeUser: () => createKindeUser,
|
|
34
36
|
createMembership: () => createMembership,
|
|
35
37
|
getDefaultTestkit: () => getDefaultTestkit,
|
|
38
|
+
inspectToken: () => inspectToken,
|
|
36
39
|
isAuthenticated: () => isAuthenticated,
|
|
40
|
+
parseEnvFile: () => parseEnvFile,
|
|
37
41
|
principalFromClaims: () => principalFromClaims,
|
|
38
42
|
resetFactories: () => resetFactories,
|
|
39
43
|
resolveSeed: () => resolveSeed,
|
|
44
|
+
runDoctor: () => runDoctor,
|
|
40
45
|
scenario: () => scenario,
|
|
41
46
|
seedScenario: () => seedScenario,
|
|
42
47
|
startKindeTestkit: () => startKindeTestkit,
|
|
@@ -210,6 +215,7 @@ function invalid(value) {
|
|
|
210
215
|
// src/testkit.ts
|
|
211
216
|
var DEFAULT_ISSUER = "http://localhost:4400";
|
|
212
217
|
var DEFAULT_CLIENT_ID = "kinde_testkit_client";
|
|
218
|
+
var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
|
|
213
219
|
var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
|
|
214
220
|
var DEFAULT_AUTH_METHODS = ["email"];
|
|
215
221
|
var INVALID_TOKEN_KINDS = [
|
|
@@ -288,6 +294,27 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
288
294
|
Object.assign(payload, options.claims ?? {});
|
|
289
295
|
return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
|
|
290
296
|
}
|
|
297
|
+
async m2mToken(options = {}) {
|
|
298
|
+
const now = this.clock();
|
|
299
|
+
const requested = [...options.scopes ?? []];
|
|
300
|
+
const granted = [...options.grantedScopes ?? requested];
|
|
301
|
+
const payload = {
|
|
302
|
+
aud: [...options.audience ?? this.audience],
|
|
303
|
+
azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
|
|
304
|
+
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
305
|
+
gty: ["client_credentials"],
|
|
306
|
+
iat: now,
|
|
307
|
+
iss: this.issuer,
|
|
308
|
+
jti: (0, import_node_crypto2.randomUUID)(),
|
|
309
|
+
scope: granted.join(" "),
|
|
310
|
+
scp: requested,
|
|
311
|
+
v: "2"
|
|
312
|
+
};
|
|
313
|
+
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
314
|
+
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
315
|
+
Object.assign(payload, options.claims ?? {});
|
|
316
|
+
return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
|
|
317
|
+
}
|
|
291
318
|
async tokenFor(scenario2, overrides = {}) {
|
|
292
319
|
if (scenario2.kind === "unauthenticated") return null;
|
|
293
320
|
return this.token({
|
|
@@ -360,8 +387,10 @@ function principalFromClaims(claims) {
|
|
|
360
387
|
(role) => typeof role === "string" ? role : String(role.key ?? "")
|
|
361
388
|
) : [];
|
|
362
389
|
const permissions = Array.isArray(claims.permissions) ? claims.permissions.map(String) : [];
|
|
390
|
+
const machine = Array.isArray(claims.gty) && claims.gty.includes("client_credentials");
|
|
363
391
|
return {
|
|
364
|
-
|
|
392
|
+
type: machine ? "machine" : "user",
|
|
393
|
+
subject: String((machine ? claims.azp : claims.sub) ?? ""),
|
|
365
394
|
issuer: String(claims.iss ?? ""),
|
|
366
395
|
organization: typeof claims.org_code === "string" ? { code: claims.org_code } : null,
|
|
367
396
|
roles: roles.filter(Boolean),
|
|
@@ -371,6 +400,7 @@ function principalFromClaims(claims) {
|
|
|
371
400
|
}
|
|
372
401
|
function scenarioPrincipal(scenario2, issuer) {
|
|
373
402
|
return {
|
|
403
|
+
type: "user",
|
|
374
404
|
subject: scenario2.user.id,
|
|
375
405
|
issuer,
|
|
376
406
|
organization: scenario2.organization ? { code: scenario2.organization.code } : null,
|
|
@@ -461,6 +491,7 @@ function resolveSeed(input) {
|
|
|
461
491
|
const rawUsers = listOf(input.users, "users", problems);
|
|
462
492
|
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
463
493
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
494
|
+
const rawApplications = listOf(input.applications, "applications", problems);
|
|
464
495
|
const users = [];
|
|
465
496
|
rawUsers.forEach((raw, index) => {
|
|
466
497
|
if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
|
|
@@ -516,10 +547,43 @@ function resolveSeed(input) {
|
|
|
516
547
|
})
|
|
517
548
|
);
|
|
518
549
|
});
|
|
550
|
+
const applications = [];
|
|
551
|
+
rawApplications.forEach((raw, index) => {
|
|
552
|
+
if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
|
|
553
|
+
problems.push(`applications[${index}] needs a string "clientId".`);
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
if (applications.some((app) => app.clientId === raw.clientId)) {
|
|
557
|
+
problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
|
|
561
|
+
problems.push(`applications[${index}].clientSecret must be a string.`);
|
|
562
|
+
}
|
|
563
|
+
if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
|
|
564
|
+
problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
|
|
565
|
+
}
|
|
566
|
+
for (const field of ["scopes", "permissions"]) {
|
|
567
|
+
const value = raw[field];
|
|
568
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
|
|
569
|
+
problems.push(`applications[${index}].${field} must be a list of strings.`);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const audience = raw.audience;
|
|
573
|
+
applications.push({
|
|
574
|
+
clientId: raw.clientId,
|
|
575
|
+
clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
|
|
576
|
+
name: typeof raw.name === "string" ? raw.name : raw.clientId,
|
|
577
|
+
organizationCode: typeof raw.organization === "string" ? raw.organization : null,
|
|
578
|
+
scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
|
|
579
|
+
permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
|
|
580
|
+
audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
|
|
581
|
+
});
|
|
582
|
+
});
|
|
519
583
|
if (problems.length > 0) {
|
|
520
584
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
521
585
|
}
|
|
522
|
-
return { users, organizations, memberships };
|
|
586
|
+
return { users, organizations, memberships, applications };
|
|
523
587
|
}
|
|
524
588
|
function findUser(users, ref) {
|
|
525
589
|
const needle = ref.toLowerCase();
|
|
@@ -788,13 +852,16 @@ var AuthorizationServer = class {
|
|
|
788
852
|
try {
|
|
789
853
|
const clientId = clientIdFrom(req, form);
|
|
790
854
|
const grantType = form.grant_type;
|
|
855
|
+
if (grantType === "client_credentials") {
|
|
856
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
|
|
857
|
+
}
|
|
791
858
|
let grant;
|
|
792
859
|
if (grantType === "authorization_code") {
|
|
793
860
|
grant = this.redeemCode(form, clientId);
|
|
794
861
|
} else if (grantType === "refresh_token") {
|
|
795
862
|
grant = this.redeemRefreshToken(form, clientId);
|
|
796
863
|
} else {
|
|
797
|
-
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and
|
|
864
|
+
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
798
865
|
}
|
|
799
866
|
sendJson(res, 200, await this.issueTokens(grant));
|
|
800
867
|
} catch (error) {
|
|
@@ -804,6 +871,33 @@ var AuthorizationServer = class {
|
|
|
804
871
|
throw error;
|
|
805
872
|
}
|
|
806
873
|
}
|
|
874
|
+
async clientCredentials(clientId, clientSecret, form) {
|
|
875
|
+
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
876
|
+
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
877
|
+
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
878
|
+
}
|
|
879
|
+
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
880
|
+
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
881
|
+
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
882
|
+
return {
|
|
883
|
+
access_token: await this.testkit.m2mToken({
|
|
884
|
+
clientId,
|
|
885
|
+
organizationCode: app?.organizationCode ?? null,
|
|
886
|
+
scopes: requested,
|
|
887
|
+
grantedScopes: granted,
|
|
888
|
+
audience: audience.length > 0 ? audience : app?.audience ?? void 0,
|
|
889
|
+
permissions: app?.permissions ?? void 0
|
|
890
|
+
}),
|
|
891
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
892
|
+
scope: granted.join(" "),
|
|
893
|
+
token_type: "bearer"
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
reset() {
|
|
897
|
+
this.codes.clear();
|
|
898
|
+
this.refreshTokens.clear();
|
|
899
|
+
this.signedUpUsers.clear();
|
|
900
|
+
}
|
|
807
901
|
redeemCode(form, clientId) {
|
|
808
902
|
const code = form.code ?? "";
|
|
809
903
|
const pending = this.codes.get(code);
|
|
@@ -975,6 +1069,15 @@ function clientIdFrom(req, form) {
|
|
|
975
1069
|
if (form.client_id) return form.client_id;
|
|
976
1070
|
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
977
1071
|
}
|
|
1072
|
+
function clientSecretFrom(req, form) {
|
|
1073
|
+
const header = req.headers.authorization ?? "";
|
|
1074
|
+
if (header.startsWith("Basic ")) {
|
|
1075
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1076
|
+
const index = decoded.indexOf(":");
|
|
1077
|
+
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1078
|
+
}
|
|
1079
|
+
return form.client_secret ?? null;
|
|
1080
|
+
}
|
|
978
1081
|
function redirectWithError(res, request, error, description) {
|
|
979
1082
|
const target = new URL(request.redirectUri);
|
|
980
1083
|
target.searchParams.set("error", error);
|
|
@@ -1015,6 +1118,86 @@ function sendJson(res, status, body) {
|
|
|
1015
1118
|
res.end(JSON.stringify(body));
|
|
1016
1119
|
}
|
|
1017
1120
|
|
|
1121
|
+
// src/failures.ts
|
|
1122
|
+
var MAX_DELAY_MS = 6e4;
|
|
1123
|
+
var FailureInjector = class {
|
|
1124
|
+
rules = [];
|
|
1125
|
+
nextId = 1;
|
|
1126
|
+
add(rule) {
|
|
1127
|
+
const problems = validate(rule);
|
|
1128
|
+
if (problems.length > 0) {
|
|
1129
|
+
throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
|
|
1130
|
+
}
|
|
1131
|
+
const active = {
|
|
1132
|
+
id: `failure_${this.nextId++}`,
|
|
1133
|
+
path: rule.path,
|
|
1134
|
+
method: rule.method ? rule.method.toUpperCase() : null,
|
|
1135
|
+
status: rule.status ?? null,
|
|
1136
|
+
delayMs: rule.delayMs ?? 0,
|
|
1137
|
+
hang: rule.hang ?? false,
|
|
1138
|
+
remaining: rule.times ?? null,
|
|
1139
|
+
retryAfter: rule.retryAfter ?? 1,
|
|
1140
|
+
hits: 0
|
|
1141
|
+
};
|
|
1142
|
+
this.rules.push(active);
|
|
1143
|
+
return { ...active };
|
|
1144
|
+
}
|
|
1145
|
+
remove(id) {
|
|
1146
|
+
const before = this.rules.length;
|
|
1147
|
+
this.rules = this.rules.filter((rule) => rule.id !== id);
|
|
1148
|
+
return this.rules.length < before;
|
|
1149
|
+
}
|
|
1150
|
+
clear() {
|
|
1151
|
+
this.rules = [];
|
|
1152
|
+
}
|
|
1153
|
+
list() {
|
|
1154
|
+
return this.rules.map((rule) => ({ ...rule }));
|
|
1155
|
+
}
|
|
1156
|
+
take(method, path) {
|
|
1157
|
+
const rule = this.rules.find((r) => matches(r, method, path));
|
|
1158
|
+
if (!rule) return null;
|
|
1159
|
+
rule.hits += 1;
|
|
1160
|
+
if (rule.remaining !== null) {
|
|
1161
|
+
rule.remaining -= 1;
|
|
1162
|
+
if (rule.remaining <= 0) this.remove(rule.id);
|
|
1163
|
+
}
|
|
1164
|
+
return { ...rule };
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
function failureBody(status) {
|
|
1168
|
+
const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
|
|
1169
|
+
return { error, error_description: `kinde-testkit injected a ${status} response.` };
|
|
1170
|
+
}
|
|
1171
|
+
function matches(rule, method, path) {
|
|
1172
|
+
if (rule.method && rule.method !== method.toUpperCase()) return false;
|
|
1173
|
+
if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
|
|
1174
|
+
return rule.path === path;
|
|
1175
|
+
}
|
|
1176
|
+
function validate(rule) {
|
|
1177
|
+
const problems = [];
|
|
1178
|
+
if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
|
|
1179
|
+
problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
|
|
1180
|
+
} else if (rule.path.startsWith("/testkit/")) {
|
|
1181
|
+
problems.push("Failures cannot target /testkit/ control endpoints.");
|
|
1182
|
+
}
|
|
1183
|
+
if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
|
|
1184
|
+
problems.push('"status" must be an HTTP error status between 400 and 599.');
|
|
1185
|
+
}
|
|
1186
|
+
if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
|
|
1187
|
+
problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
|
|
1188
|
+
}
|
|
1189
|
+
if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
|
|
1190
|
+
problems.push('"times" must be a whole number of 1 or more.');
|
|
1191
|
+
}
|
|
1192
|
+
if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
|
|
1193
|
+
problems.push('"retryAfter" must be a whole number of seconds.');
|
|
1194
|
+
}
|
|
1195
|
+
if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
|
|
1196
|
+
problems.push('Set at least one of "status", "delayMs" or "hang".');
|
|
1197
|
+
}
|
|
1198
|
+
return problems;
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1018
1201
|
// src/server.ts
|
|
1019
1202
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
1020
1203
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
@@ -1028,12 +1211,11 @@ async function startKindeTestkit(options = {}) {
|
|
|
1028
1211
|
);
|
|
1029
1212
|
}
|
|
1030
1213
|
const seed = resolveSeed(options.seed ?? {});
|
|
1214
|
+
const failures = new FailureInjector();
|
|
1031
1215
|
let ready;
|
|
1032
|
-
const testkitReady = new Promise(
|
|
1033
|
-
(resolve) => ready = resolve
|
|
1034
|
-
);
|
|
1216
|
+
const testkitReady = new Promise((resolve) => ready = resolve);
|
|
1035
1217
|
const server = (0, import_node_http.createServer)((req, res) => {
|
|
1036
|
-
testkitReady.then((
|
|
1218
|
+
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1037
1219
|
});
|
|
1038
1220
|
await new Promise((resolve, reject) => {
|
|
1039
1221
|
server.once("error", reject);
|
|
@@ -1047,7 +1229,12 @@ async function startKindeTestkit(options = {}) {
|
|
|
1047
1229
|
audience: options.audience ?? options.seed?.audience,
|
|
1048
1230
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1049
1231
|
});
|
|
1050
|
-
|
|
1232
|
+
const auth = new AuthorizationServer(testkit, seed);
|
|
1233
|
+
const reset = () => {
|
|
1234
|
+
auth.reset();
|
|
1235
|
+
failures.clear();
|
|
1236
|
+
};
|
|
1237
|
+
ready({ testkit, auth, seed, failures, reset });
|
|
1051
1238
|
return {
|
|
1052
1239
|
url,
|
|
1053
1240
|
issuer: testkit.issuer,
|
|
@@ -1055,16 +1242,31 @@ async function startKindeTestkit(options = {}) {
|
|
|
1055
1242
|
jwksUri: `${url}/.well-known/jwks`,
|
|
1056
1243
|
testkit,
|
|
1057
1244
|
seed,
|
|
1245
|
+
failures,
|
|
1246
|
+
reset,
|
|
1058
1247
|
close: () => new Promise((resolve, reject) => {
|
|
1059
1248
|
server.closeAllConnections();
|
|
1060
1249
|
server.close((error) => error ? reject(error) : resolve());
|
|
1061
1250
|
})
|
|
1062
1251
|
};
|
|
1063
1252
|
}
|
|
1064
|
-
async function handle(req, res,
|
|
1253
|
+
async function handle(req, res, context) {
|
|
1254
|
+
const { testkit, auth, seed, failures } = context;
|
|
1065
1255
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1066
1256
|
const { pathname } = url;
|
|
1067
1257
|
const method = req.method ?? "GET";
|
|
1258
|
+
if (!pathname.startsWith("/testkit/")) {
|
|
1259
|
+
const failure = failures.take(method, pathname);
|
|
1260
|
+
if (failure) {
|
|
1261
|
+
if (failure.hang) return;
|
|
1262
|
+
if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
|
|
1263
|
+
if (failure.status !== null) {
|
|
1264
|
+
const headers = {};
|
|
1265
|
+
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1266
|
+
return sendJson2(res, failure.status, failureBody(failure.status), headers);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1068
1270
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
1069
1271
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1070
1272
|
return sendJson2(res, 200, discovery(testkit));
|
|
@@ -1082,6 +1284,22 @@ async function handle(req, res, testkit, auth, seed) {
|
|
|
1082
1284
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1083
1285
|
return sendJson2(res, 200, seed.memberships);
|
|
1084
1286
|
}
|
|
1287
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
|
|
1288
|
+
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1289
|
+
return sendJson2(res, 201, failures.add(await readJson(req)));
|
|
1290
|
+
}
|
|
1291
|
+
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1292
|
+
failures.clear();
|
|
1293
|
+
return sendJson2(res, 200, { ok: true });
|
|
1294
|
+
}
|
|
1295
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1296
|
+
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1297
|
+
return sendJson2(res, removed ? 200 : 404, { ok: removed });
|
|
1298
|
+
}
|
|
1299
|
+
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1300
|
+
context.reset();
|
|
1301
|
+
return sendJson2(res, 200, { ok: true });
|
|
1302
|
+
}
|
|
1085
1303
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1086
1304
|
const body = await readJson(req);
|
|
1087
1305
|
const accessToken = await issueToken(testkit, seed, body);
|
|
@@ -1121,6 +1339,21 @@ async function issueToken(testkit, seed, body) {
|
|
|
1121
1339
|
]);
|
|
1122
1340
|
}
|
|
1123
1341
|
const expiresIn = input.expiresIn;
|
|
1342
|
+
if (input.m2m === true) {
|
|
1343
|
+
const clientId = optionalString(input, "clientId");
|
|
1344
|
+
const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
|
|
1345
|
+
const scopes = optionalStrings(input, "scopes") ?? [];
|
|
1346
|
+
return testkit.m2mToken({
|
|
1347
|
+
clientId,
|
|
1348
|
+
organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
|
|
1349
|
+
scopes,
|
|
1350
|
+
grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
|
|
1351
|
+
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
1352
|
+
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
1353
|
+
expiresIn,
|
|
1354
|
+
invalid: invalid2
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1124
1357
|
const permissions = optionalStrings(input, "permissions");
|
|
1125
1358
|
const roles = optionalStrings(input, "roles");
|
|
1126
1359
|
const userRef = optionalString(input, "user");
|
|
@@ -1196,10 +1429,11 @@ async function readText(req) {
|
|
|
1196
1429
|
}
|
|
1197
1430
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1198
1431
|
}
|
|
1199
|
-
function sendJson2(res, status, body) {
|
|
1432
|
+
function sendJson2(res, status, body, headers = {}) {
|
|
1200
1433
|
res.writeHead(status, {
|
|
1201
1434
|
"content-type": "application/json; charset=utf-8",
|
|
1202
|
-
"cache-control": "no-store"
|
|
1435
|
+
"cache-control": "no-store",
|
|
1436
|
+
...headers
|
|
1203
1437
|
});
|
|
1204
1438
|
res.end(JSON.stringify(body));
|
|
1205
1439
|
}
|
|
@@ -1217,12 +1451,181 @@ function sendError(res, error) {
|
|
|
1217
1451
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1218
1452
|
});
|
|
1219
1453
|
}
|
|
1454
|
+
|
|
1455
|
+
// src/inspect.ts
|
|
1456
|
+
var import_jose2 = require("jose");
|
|
1457
|
+
async function inspectToken(token, options = {}) {
|
|
1458
|
+
const checks = [];
|
|
1459
|
+
const trimmed = token.trim();
|
|
1460
|
+
let header = null;
|
|
1461
|
+
let payload = null;
|
|
1462
|
+
if (trimmed.split(".").length !== 3) {
|
|
1463
|
+
checks.push({ name: "Format", status: "fail", detail: "A JWT has three parts separated by dots." });
|
|
1464
|
+
return { kind: "unknown", header, payload, checks };
|
|
1465
|
+
}
|
|
1466
|
+
try {
|
|
1467
|
+
header = (0, import_jose2.decodeProtectedHeader)(trimmed);
|
|
1468
|
+
payload = (0, import_jose2.decodeJwt)(trimmed);
|
|
1469
|
+
} catch {
|
|
1470
|
+
checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
|
|
1471
|
+
return { kind: "unknown", header, payload, checks };
|
|
1472
|
+
}
|
|
1473
|
+
checks.push({ name: "Format", status: "pass", detail: "Three base64url parts with JSON header and payload." });
|
|
1474
|
+
checks.push(
|
|
1475
|
+
header.alg === "RS256" ? { name: "Algorithm", status: "pass", detail: "RS256, the algorithm Kinde signs with." } : { name: "Algorithm", status: "fail", detail: `${String(header.alg)} is not RS256. Kinde tokens are always RS256.` }
|
|
1476
|
+
);
|
|
1477
|
+
const signer = typeof header.kid === "string" && header.kid.startsWith("kinde-testkit") ? "kinde-testkit" : "another issuer";
|
|
1478
|
+
checks.push({ name: "Key", status: "pass", detail: `kid ${String(header.kid ?? "missing")} (${signer}).` });
|
|
1479
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
1480
|
+
if (typeof payload.exp !== "number") {
|
|
1481
|
+
checks.push({ name: "Expiry", status: "fail", detail: "No exp claim." });
|
|
1482
|
+
} else if (payload.exp <= now) {
|
|
1483
|
+
checks.push({ name: "Expiry", status: "fail", detail: `Expired ${formatSpan(now - payload.exp)} ago.` });
|
|
1484
|
+
} else {
|
|
1485
|
+
checks.push({ name: "Expiry", status: "pass", detail: `Expires in ${formatSpan(payload.exp - now)}.` });
|
|
1486
|
+
}
|
|
1487
|
+
if (typeof payload.iat === "number" && payload.iat > now + 60) {
|
|
1488
|
+
checks.push({ name: "Issued at", status: "fail", detail: `iat is ${formatSpan(payload.iat - now)} in the future.` });
|
|
1489
|
+
}
|
|
1490
|
+
if (options.issuerUrl) {
|
|
1491
|
+
const issuer = options.issuerUrl.replace(/\/+$/, "");
|
|
1492
|
+
if (payload.iss !== issuer) {
|
|
1493
|
+
checks.push({ name: "Issuer", status: "fail", detail: `iss is ${String(payload.iss)}, not ${issuer}.` });
|
|
1494
|
+
} else {
|
|
1495
|
+
checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
|
|
1496
|
+
}
|
|
1497
|
+
try {
|
|
1498
|
+
await (0, import_jose2.jwtVerify)(trimmed, (0, import_jose2.createRemoteJWKSet)(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
|
|
1499
|
+
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1500
|
+
} catch (error) {
|
|
1501
|
+
const code = error.code ?? "";
|
|
1502
|
+
if (code === "ERR_JWT_EXPIRED" || code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
|
|
1503
|
+
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1504
|
+
} else {
|
|
1505
|
+
checks.push({ name: "Signature", status: "fail", detail: describeVerifyError(code, issuer) });
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
} else {
|
|
1509
|
+
checks.push({ name: "Signature", status: "warn", detail: "Not checked. Pass --url to verify against a running issuer." });
|
|
1510
|
+
}
|
|
1511
|
+
return { kind: kindOf(payload), header, payload, checks };
|
|
1512
|
+
}
|
|
1513
|
+
function kindOf(payload) {
|
|
1514
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) return "m2m";
|
|
1515
|
+
if ("email" in payload || "org_codes" in payload || "at_hash" in payload || "nonce" in payload) return "id";
|
|
1516
|
+
if ("scp" in payload || "permissions" in payload || "org_code" in payload) return "access";
|
|
1517
|
+
return "unknown";
|
|
1518
|
+
}
|
|
1519
|
+
function describeVerifyError(code, issuer) {
|
|
1520
|
+
if (code === "ERR_JWKS_NO_MATCHING_KEY") return `No key in ${issuer}'s JWKS matches this token's kid.`;
|
|
1521
|
+
if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "The signature does not match the token. It was changed after signing.";
|
|
1522
|
+
if (code === "ERR_JOSE_ALG_NOT_ALLOWED" || code === "ERR_JOSE_NOT_SUPPORTED") return "The token is not signed with RS256.";
|
|
1523
|
+
if (code === "ERR_JWKS_TIMEOUT" || code === "ERR_JOSE_GENERIC") return `Could not fetch keys from ${issuer}.`;
|
|
1524
|
+
return `Verification failed (${code || "unknown error"}).`;
|
|
1525
|
+
}
|
|
1526
|
+
function formatSpan(seconds) {
|
|
1527
|
+
const s = Math.max(0, Math.round(seconds));
|
|
1528
|
+
if (s < 60) return `${s}s`;
|
|
1529
|
+
if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
|
|
1530
|
+
if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor(s % 3600 / 60)}m`;
|
|
1531
|
+
return `${Math.floor(s / 86400)}d ${Math.floor(s % 86400 / 3600)}h`;
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
// src/doctor.ts
|
|
1535
|
+
var SECRET_FORMAT = /^[a-zA-Z0-9]{40,60}$/;
|
|
1536
|
+
async function runDoctor(options) {
|
|
1537
|
+
const url = options.url.replace(/\/+$/, "");
|
|
1538
|
+
const checks = [];
|
|
1539
|
+
let issuer = null;
|
|
1540
|
+
try {
|
|
1541
|
+
const health = await (await fetch(`${url}/testkit/health`)).json();
|
|
1542
|
+
issuer = health.issuer ?? null;
|
|
1543
|
+
checks.push({ name: "Issuer running", status: "pass", detail: `${url} answers, issuer ${issuer}.` });
|
|
1544
|
+
} catch {
|
|
1545
|
+
checks.push({ name: "Issuer running", status: "fail", detail: `Nothing answers at ${url}. Start it with "kinde-testkit start".` });
|
|
1546
|
+
}
|
|
1547
|
+
if (issuer) {
|
|
1548
|
+
try {
|
|
1549
|
+
const discovery2 = await (await fetch(`${url}/.well-known/openid-configuration`)).json();
|
|
1550
|
+
checks.push(
|
|
1551
|
+
discovery2.issuer === issuer ? { name: "Discovery", status: "pass", detail: "The discovery document names the same issuer." } : { name: "Discovery", status: "fail", detail: `Discovery says ${String(discovery2.issuer)}, health says ${issuer}.` }
|
|
1552
|
+
);
|
|
1553
|
+
} catch {
|
|
1554
|
+
checks.push({ name: "Discovery", status: "fail", detail: "Could not read /.well-known/openid-configuration." });
|
|
1555
|
+
}
|
|
1556
|
+
try {
|
|
1557
|
+
const jwks = await (await fetch(`${url}/.well-known/jwks.json`)).json();
|
|
1558
|
+
const usable = (jwks.keys ?? []).filter((key) => key.kty === "RSA" && key.use === "sig");
|
|
1559
|
+
checks.push(
|
|
1560
|
+
usable.length > 0 ? { name: "JWKS", status: "pass", detail: `${usable.length} RS256 signing key at /.well-known/jwks.json.` } : { name: "JWKS", status: "fail", detail: "No RSA signing key at /.well-known/jwks.json." }
|
|
1561
|
+
);
|
|
1562
|
+
} catch {
|
|
1563
|
+
checks.push({ name: "JWKS", status: "fail", detail: "Could not read /.well-known/jwks.json." });
|
|
1564
|
+
}
|
|
1565
|
+
try {
|
|
1566
|
+
const users = await (await fetch(`${url}/testkit/users`)).json();
|
|
1567
|
+
checks.push(
|
|
1568
|
+
users.length > 0 ? { name: "Seed", status: "pass", detail: `${users.length} seeded ${users.length === 1 ? "user" : "users"}.` } : { name: "Seed", status: "warn", detail: "No seeded users. The sign-in page still accepts any email, but those users have no organization." }
|
|
1569
|
+
);
|
|
1570
|
+
} catch {
|
|
1571
|
+
checks.push({ name: "Seed", status: "warn", detail: "Could not read /testkit/users." });
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
const env = options.env;
|
|
1575
|
+
const configured = env.KINDE_ISSUER_URL?.trim().replace(/\/+$/, "");
|
|
1576
|
+
if (!configured) {
|
|
1577
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: "Not set. Set it to the testkit's issuer for test runs." });
|
|
1578
|
+
} else if (/\.kinde\.com$/i.test(new URL(configured, "http://x").hostname)) {
|
|
1579
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} is a real Kinde domain. Tests would sign in against Kinde, not the testkit.` });
|
|
1580
|
+
} else if (issuer && configured !== issuer) {
|
|
1581
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} does not match the testkit issuer ${issuer}. Token checks compare iss exactly.` });
|
|
1582
|
+
} else {
|
|
1583
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "pass", detail: `${configured}.` });
|
|
1584
|
+
}
|
|
1585
|
+
checks.push(
|
|
1586
|
+
env.KINDE_CLIENT_ID ? { name: "KINDE_CLIENT_ID", status: "pass", detail: "Set. The testkit accepts any client ID." } : { name: "KINDE_CLIENT_ID", status: "fail", detail: "Not set. Kinde's SDKs refuse to start without it." }
|
|
1587
|
+
);
|
|
1588
|
+
const secret = env.KINDE_CLIENT_SECRET;
|
|
1589
|
+
if (!secret) {
|
|
1590
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "warn", detail: "Not set. Server-side SDKs, such as the Next.js SDK, need it." });
|
|
1591
|
+
} else if (!SECRET_FORMAT.test(secret)) {
|
|
1592
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "fail", detail: "The Next.js SDK only accepts 40 to 60 letters and digits." });
|
|
1593
|
+
} else {
|
|
1594
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1595
|
+
}
|
|
1596
|
+
const site = env.KINDE_SITE_URL;
|
|
1597
|
+
if (!site) {
|
|
1598
|
+
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
1599
|
+
} else if (!/^https?:\/\//.test(site)) {
|
|
1600
|
+
checks.push({ name: "KINDE_SITE_URL", status: "fail", detail: `${site} is not an http or https URL.` });
|
|
1601
|
+
} else {
|
|
1602
|
+
checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
|
|
1603
|
+
}
|
|
1604
|
+
return { url, checks, ok: checks.every((check) => check.status !== "fail") };
|
|
1605
|
+
}
|
|
1606
|
+
function parseEnvFile(text) {
|
|
1607
|
+
const values = {};
|
|
1608
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1609
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
1610
|
+
if (!match) continue;
|
|
1611
|
+
let value = match[2];
|
|
1612
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
1613
|
+
value = value.slice(1, -1);
|
|
1614
|
+
} else {
|
|
1615
|
+
value = value.replace(/\s+#.*$/, "");
|
|
1616
|
+
}
|
|
1617
|
+
values[match[1]] = value;
|
|
1618
|
+
}
|
|
1619
|
+
return values;
|
|
1620
|
+
}
|
|
1220
1621
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1221
1622
|
0 && (module.exports = {
|
|
1222
1623
|
DEFAULT_AUTH_METHODS,
|
|
1223
1624
|
DEFAULT_CLIENT_ID,
|
|
1224
1625
|
DEFAULT_ISSUER,
|
|
1626
|
+
DEFAULT_M2M_CLIENT_ID,
|
|
1225
1627
|
DEFAULT_SCOPES,
|
|
1628
|
+
FailureInjector,
|
|
1226
1629
|
INVALID_TOKEN_KINDS,
|
|
1227
1630
|
KindeTestkit,
|
|
1228
1631
|
ScenarioBuilder,
|
|
@@ -1232,10 +1635,13 @@ function sendError(res, error) {
|
|
|
1232
1635
|
createKindeUser,
|
|
1233
1636
|
createMembership,
|
|
1234
1637
|
getDefaultTestkit,
|
|
1638
|
+
inspectToken,
|
|
1235
1639
|
isAuthenticated,
|
|
1640
|
+
parseEnvFile,
|
|
1236
1641
|
principalFromClaims,
|
|
1237
1642
|
resetFactories,
|
|
1238
1643
|
resolveSeed,
|
|
1644
|
+
runDoctor,
|
|
1239
1645
|
scenario,
|
|
1240
1646
|
seedScenario,
|
|
1241
1647
|
startKindeTestkit,
|