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.js
CHANGED
|
@@ -171,6 +171,7 @@ function invalid(value) {
|
|
|
171
171
|
// src/testkit.ts
|
|
172
172
|
var DEFAULT_ISSUER = "http://localhost:4400";
|
|
173
173
|
var DEFAULT_CLIENT_ID = "kinde_testkit_client";
|
|
174
|
+
var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
|
|
174
175
|
var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
|
|
175
176
|
var DEFAULT_AUTH_METHODS = ["email"];
|
|
176
177
|
var INVALID_TOKEN_KINDS = [
|
|
@@ -249,6 +250,27 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
249
250
|
Object.assign(payload, options.claims ?? {});
|
|
250
251
|
return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
|
|
251
252
|
}
|
|
253
|
+
async m2mToken(options = {}) {
|
|
254
|
+
const now = this.clock();
|
|
255
|
+
const requested = [...options.scopes ?? []];
|
|
256
|
+
const granted = [...options.grantedScopes ?? requested];
|
|
257
|
+
const payload = {
|
|
258
|
+
aud: [...options.audience ?? this.audience],
|
|
259
|
+
azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
|
|
260
|
+
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
261
|
+
gty: ["client_credentials"],
|
|
262
|
+
iat: now,
|
|
263
|
+
iss: this.issuer,
|
|
264
|
+
jti: randomUUID(),
|
|
265
|
+
scope: granted.join(" "),
|
|
266
|
+
scp: requested,
|
|
267
|
+
v: "2"
|
|
268
|
+
};
|
|
269
|
+
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
270
|
+
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
271
|
+
Object.assign(payload, options.claims ?? {});
|
|
272
|
+
return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
|
|
273
|
+
}
|
|
252
274
|
async tokenFor(scenario2, overrides = {}) {
|
|
253
275
|
if (scenario2.kind === "unauthenticated") return null;
|
|
254
276
|
return this.token({
|
|
@@ -321,8 +343,10 @@ function principalFromClaims(claims) {
|
|
|
321
343
|
(role) => typeof role === "string" ? role : String(role.key ?? "")
|
|
322
344
|
) : [];
|
|
323
345
|
const permissions = Array.isArray(claims.permissions) ? claims.permissions.map(String) : [];
|
|
346
|
+
const machine = Array.isArray(claims.gty) && claims.gty.includes("client_credentials");
|
|
324
347
|
return {
|
|
325
|
-
|
|
348
|
+
type: machine ? "machine" : "user",
|
|
349
|
+
subject: String((machine ? claims.azp : claims.sub) ?? ""),
|
|
326
350
|
issuer: String(claims.iss ?? ""),
|
|
327
351
|
organization: typeof claims.org_code === "string" ? { code: claims.org_code } : null,
|
|
328
352
|
roles: roles.filter(Boolean),
|
|
@@ -332,6 +356,7 @@ function principalFromClaims(claims) {
|
|
|
332
356
|
}
|
|
333
357
|
function scenarioPrincipal(scenario2, issuer) {
|
|
334
358
|
return {
|
|
359
|
+
type: "user",
|
|
335
360
|
subject: scenario2.user.id,
|
|
336
361
|
issuer,
|
|
337
362
|
organization: scenario2.organization ? { code: scenario2.organization.code } : null,
|
|
@@ -422,6 +447,7 @@ function resolveSeed(input) {
|
|
|
422
447
|
const rawUsers = listOf(input.users, "users", problems);
|
|
423
448
|
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
424
449
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
450
|
+
const rawApplications = listOf(input.applications, "applications", problems);
|
|
425
451
|
const users = [];
|
|
426
452
|
rawUsers.forEach((raw, index) => {
|
|
427
453
|
if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
|
|
@@ -477,10 +503,43 @@ function resolveSeed(input) {
|
|
|
477
503
|
})
|
|
478
504
|
);
|
|
479
505
|
});
|
|
506
|
+
const applications = [];
|
|
507
|
+
rawApplications.forEach((raw, index) => {
|
|
508
|
+
if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
|
|
509
|
+
problems.push(`applications[${index}] needs a string "clientId".`);
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
if (applications.some((app) => app.clientId === raw.clientId)) {
|
|
513
|
+
problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
|
|
517
|
+
problems.push(`applications[${index}].clientSecret must be a string.`);
|
|
518
|
+
}
|
|
519
|
+
if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
|
|
520
|
+
problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
|
|
521
|
+
}
|
|
522
|
+
for (const field of ["scopes", "permissions"]) {
|
|
523
|
+
const value = raw[field];
|
|
524
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
|
|
525
|
+
problems.push(`applications[${index}].${field} must be a list of strings.`);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
const audience = raw.audience;
|
|
529
|
+
applications.push({
|
|
530
|
+
clientId: raw.clientId,
|
|
531
|
+
clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
|
|
532
|
+
name: typeof raw.name === "string" ? raw.name : raw.clientId,
|
|
533
|
+
organizationCode: typeof raw.organization === "string" ? raw.organization : null,
|
|
534
|
+
scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
|
|
535
|
+
permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
|
|
536
|
+
audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
|
|
537
|
+
});
|
|
538
|
+
});
|
|
480
539
|
if (problems.length > 0) {
|
|
481
540
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
482
541
|
}
|
|
483
|
-
return { users, organizations, memberships };
|
|
542
|
+
return { users, organizations, memberships, applications };
|
|
484
543
|
}
|
|
485
544
|
function findUser(users, ref) {
|
|
486
545
|
const needle = ref.toLowerCase();
|
|
@@ -749,13 +808,16 @@ var AuthorizationServer = class {
|
|
|
749
808
|
try {
|
|
750
809
|
const clientId = clientIdFrom(req, form);
|
|
751
810
|
const grantType = form.grant_type;
|
|
811
|
+
if (grantType === "client_credentials") {
|
|
812
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
|
|
813
|
+
}
|
|
752
814
|
let grant;
|
|
753
815
|
if (grantType === "authorization_code") {
|
|
754
816
|
grant = this.redeemCode(form, clientId);
|
|
755
817
|
} else if (grantType === "refresh_token") {
|
|
756
818
|
grant = this.redeemRefreshToken(form, clientId);
|
|
757
819
|
} else {
|
|
758
|
-
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and
|
|
820
|
+
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
759
821
|
}
|
|
760
822
|
sendJson(res, 200, await this.issueTokens(grant));
|
|
761
823
|
} catch (error) {
|
|
@@ -765,6 +827,33 @@ var AuthorizationServer = class {
|
|
|
765
827
|
throw error;
|
|
766
828
|
}
|
|
767
829
|
}
|
|
830
|
+
async clientCredentials(clientId, clientSecret, form) {
|
|
831
|
+
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
832
|
+
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
833
|
+
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
834
|
+
}
|
|
835
|
+
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
836
|
+
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
837
|
+
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
838
|
+
return {
|
|
839
|
+
access_token: await this.testkit.m2mToken({
|
|
840
|
+
clientId,
|
|
841
|
+
organizationCode: app?.organizationCode ?? null,
|
|
842
|
+
scopes: requested,
|
|
843
|
+
grantedScopes: granted,
|
|
844
|
+
audience: audience.length > 0 ? audience : app?.audience ?? void 0,
|
|
845
|
+
permissions: app?.permissions ?? void 0
|
|
846
|
+
}),
|
|
847
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
848
|
+
scope: granted.join(" "),
|
|
849
|
+
token_type: "bearer"
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
reset() {
|
|
853
|
+
this.codes.clear();
|
|
854
|
+
this.refreshTokens.clear();
|
|
855
|
+
this.signedUpUsers.clear();
|
|
856
|
+
}
|
|
768
857
|
redeemCode(form, clientId) {
|
|
769
858
|
const code = form.code ?? "";
|
|
770
859
|
const pending = this.codes.get(code);
|
|
@@ -936,6 +1025,15 @@ function clientIdFrom(req, form) {
|
|
|
936
1025
|
if (form.client_id) return form.client_id;
|
|
937
1026
|
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
938
1027
|
}
|
|
1028
|
+
function clientSecretFrom(req, form) {
|
|
1029
|
+
const header = req.headers.authorization ?? "";
|
|
1030
|
+
if (header.startsWith("Basic ")) {
|
|
1031
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1032
|
+
const index = decoded.indexOf(":");
|
|
1033
|
+
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1034
|
+
}
|
|
1035
|
+
return form.client_secret ?? null;
|
|
1036
|
+
}
|
|
939
1037
|
function redirectWithError(res, request, error, description) {
|
|
940
1038
|
const target = new URL(request.redirectUri);
|
|
941
1039
|
target.searchParams.set("error", error);
|
|
@@ -976,6 +1074,86 @@ function sendJson(res, status, body) {
|
|
|
976
1074
|
res.end(JSON.stringify(body));
|
|
977
1075
|
}
|
|
978
1076
|
|
|
1077
|
+
// src/failures.ts
|
|
1078
|
+
var MAX_DELAY_MS = 6e4;
|
|
1079
|
+
var FailureInjector = class {
|
|
1080
|
+
rules = [];
|
|
1081
|
+
nextId = 1;
|
|
1082
|
+
add(rule) {
|
|
1083
|
+
const problems = validate(rule);
|
|
1084
|
+
if (problems.length > 0) {
|
|
1085
|
+
throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
|
|
1086
|
+
}
|
|
1087
|
+
const active = {
|
|
1088
|
+
id: `failure_${this.nextId++}`,
|
|
1089
|
+
path: rule.path,
|
|
1090
|
+
method: rule.method ? rule.method.toUpperCase() : null,
|
|
1091
|
+
status: rule.status ?? null,
|
|
1092
|
+
delayMs: rule.delayMs ?? 0,
|
|
1093
|
+
hang: rule.hang ?? false,
|
|
1094
|
+
remaining: rule.times ?? null,
|
|
1095
|
+
retryAfter: rule.retryAfter ?? 1,
|
|
1096
|
+
hits: 0
|
|
1097
|
+
};
|
|
1098
|
+
this.rules.push(active);
|
|
1099
|
+
return { ...active };
|
|
1100
|
+
}
|
|
1101
|
+
remove(id) {
|
|
1102
|
+
const before = this.rules.length;
|
|
1103
|
+
this.rules = this.rules.filter((rule) => rule.id !== id);
|
|
1104
|
+
return this.rules.length < before;
|
|
1105
|
+
}
|
|
1106
|
+
clear() {
|
|
1107
|
+
this.rules = [];
|
|
1108
|
+
}
|
|
1109
|
+
list() {
|
|
1110
|
+
return this.rules.map((rule) => ({ ...rule }));
|
|
1111
|
+
}
|
|
1112
|
+
take(method, path) {
|
|
1113
|
+
const rule = this.rules.find((r) => matches(r, method, path));
|
|
1114
|
+
if (!rule) return null;
|
|
1115
|
+
rule.hits += 1;
|
|
1116
|
+
if (rule.remaining !== null) {
|
|
1117
|
+
rule.remaining -= 1;
|
|
1118
|
+
if (rule.remaining <= 0) this.remove(rule.id);
|
|
1119
|
+
}
|
|
1120
|
+
return { ...rule };
|
|
1121
|
+
}
|
|
1122
|
+
};
|
|
1123
|
+
function failureBody(status) {
|
|
1124
|
+
const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
|
|
1125
|
+
return { error, error_description: `kinde-testkit injected a ${status} response.` };
|
|
1126
|
+
}
|
|
1127
|
+
function matches(rule, method, path) {
|
|
1128
|
+
if (rule.method && rule.method !== method.toUpperCase()) return false;
|
|
1129
|
+
if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
|
|
1130
|
+
return rule.path === path;
|
|
1131
|
+
}
|
|
1132
|
+
function validate(rule) {
|
|
1133
|
+
const problems = [];
|
|
1134
|
+
if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
|
|
1135
|
+
problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
|
|
1136
|
+
} else if (rule.path.startsWith("/testkit/")) {
|
|
1137
|
+
problems.push("Failures cannot target /testkit/ control endpoints.");
|
|
1138
|
+
}
|
|
1139
|
+
if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
|
|
1140
|
+
problems.push('"status" must be an HTTP error status between 400 and 599.');
|
|
1141
|
+
}
|
|
1142
|
+
if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
|
|
1143
|
+
problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
|
|
1144
|
+
}
|
|
1145
|
+
if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
|
|
1146
|
+
problems.push('"times" must be a whole number of 1 or more.');
|
|
1147
|
+
}
|
|
1148
|
+
if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
|
|
1149
|
+
problems.push('"retryAfter" must be a whole number of seconds.');
|
|
1150
|
+
}
|
|
1151
|
+
if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
|
|
1152
|
+
problems.push('Set at least one of "status", "delayMs" or "hang".');
|
|
1153
|
+
}
|
|
1154
|
+
return problems;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
979
1157
|
// src/server.ts
|
|
980
1158
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
981
1159
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
@@ -989,12 +1167,11 @@ async function startKindeTestkit(options = {}) {
|
|
|
989
1167
|
);
|
|
990
1168
|
}
|
|
991
1169
|
const seed = resolveSeed(options.seed ?? {});
|
|
1170
|
+
const failures = new FailureInjector();
|
|
992
1171
|
let ready;
|
|
993
|
-
const testkitReady = new Promise(
|
|
994
|
-
(resolve) => ready = resolve
|
|
995
|
-
);
|
|
1172
|
+
const testkitReady = new Promise((resolve) => ready = resolve);
|
|
996
1173
|
const server = createServer((req, res) => {
|
|
997
|
-
testkitReady.then((
|
|
1174
|
+
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
998
1175
|
});
|
|
999
1176
|
await new Promise((resolve, reject) => {
|
|
1000
1177
|
server.once("error", reject);
|
|
@@ -1008,7 +1185,12 @@ async function startKindeTestkit(options = {}) {
|
|
|
1008
1185
|
audience: options.audience ?? options.seed?.audience,
|
|
1009
1186
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1010
1187
|
});
|
|
1011
|
-
|
|
1188
|
+
const auth = new AuthorizationServer(testkit, seed);
|
|
1189
|
+
const reset = () => {
|
|
1190
|
+
auth.reset();
|
|
1191
|
+
failures.clear();
|
|
1192
|
+
};
|
|
1193
|
+
ready({ testkit, auth, seed, failures, reset });
|
|
1012
1194
|
return {
|
|
1013
1195
|
url,
|
|
1014
1196
|
issuer: testkit.issuer,
|
|
@@ -1016,16 +1198,31 @@ async function startKindeTestkit(options = {}) {
|
|
|
1016
1198
|
jwksUri: `${url}/.well-known/jwks`,
|
|
1017
1199
|
testkit,
|
|
1018
1200
|
seed,
|
|
1201
|
+
failures,
|
|
1202
|
+
reset,
|
|
1019
1203
|
close: () => new Promise((resolve, reject) => {
|
|
1020
1204
|
server.closeAllConnections();
|
|
1021
1205
|
server.close((error) => error ? reject(error) : resolve());
|
|
1022
1206
|
})
|
|
1023
1207
|
};
|
|
1024
1208
|
}
|
|
1025
|
-
async function handle(req, res,
|
|
1209
|
+
async function handle(req, res, context) {
|
|
1210
|
+
const { testkit, auth, seed, failures } = context;
|
|
1026
1211
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1027
1212
|
const { pathname } = url;
|
|
1028
1213
|
const method = req.method ?? "GET";
|
|
1214
|
+
if (!pathname.startsWith("/testkit/")) {
|
|
1215
|
+
const failure = failures.take(method, pathname);
|
|
1216
|
+
if (failure) {
|
|
1217
|
+
if (failure.hang) return;
|
|
1218
|
+
if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
|
|
1219
|
+
if (failure.status !== null) {
|
|
1220
|
+
const headers = {};
|
|
1221
|
+
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1222
|
+
return sendJson2(res, failure.status, failureBody(failure.status), headers);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1029
1226
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
1030
1227
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1031
1228
|
return sendJson2(res, 200, discovery(testkit));
|
|
@@ -1043,6 +1240,22 @@ async function handle(req, res, testkit, auth, seed) {
|
|
|
1043
1240
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1044
1241
|
return sendJson2(res, 200, seed.memberships);
|
|
1045
1242
|
}
|
|
1243
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
|
|
1244
|
+
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1245
|
+
return sendJson2(res, 201, failures.add(await readJson(req)));
|
|
1246
|
+
}
|
|
1247
|
+
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1248
|
+
failures.clear();
|
|
1249
|
+
return sendJson2(res, 200, { ok: true });
|
|
1250
|
+
}
|
|
1251
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1252
|
+
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1253
|
+
return sendJson2(res, removed ? 200 : 404, { ok: removed });
|
|
1254
|
+
}
|
|
1255
|
+
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1256
|
+
context.reset();
|
|
1257
|
+
return sendJson2(res, 200, { ok: true });
|
|
1258
|
+
}
|
|
1046
1259
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1047
1260
|
const body = await readJson(req);
|
|
1048
1261
|
const accessToken = await issueToken(testkit, seed, body);
|
|
@@ -1082,6 +1295,21 @@ async function issueToken(testkit, seed, body) {
|
|
|
1082
1295
|
]);
|
|
1083
1296
|
}
|
|
1084
1297
|
const expiresIn = input.expiresIn;
|
|
1298
|
+
if (input.m2m === true) {
|
|
1299
|
+
const clientId = optionalString(input, "clientId");
|
|
1300
|
+
const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
|
|
1301
|
+
const scopes = optionalStrings(input, "scopes") ?? [];
|
|
1302
|
+
return testkit.m2mToken({
|
|
1303
|
+
clientId,
|
|
1304
|
+
organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
|
|
1305
|
+
scopes,
|
|
1306
|
+
grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
|
|
1307
|
+
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
1308
|
+
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
1309
|
+
expiresIn,
|
|
1310
|
+
invalid: invalid2
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1085
1313
|
const permissions = optionalStrings(input, "permissions");
|
|
1086
1314
|
const roles = optionalStrings(input, "roles");
|
|
1087
1315
|
const userRef = optionalString(input, "user");
|
|
@@ -1157,10 +1385,11 @@ async function readText(req) {
|
|
|
1157
1385
|
}
|
|
1158
1386
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1159
1387
|
}
|
|
1160
|
-
function sendJson2(res, status, body) {
|
|
1388
|
+
function sendJson2(res, status, body, headers = {}) {
|
|
1161
1389
|
res.writeHead(status, {
|
|
1162
1390
|
"content-type": "application/json; charset=utf-8",
|
|
1163
|
-
"cache-control": "no-store"
|
|
1391
|
+
"cache-control": "no-store",
|
|
1392
|
+
...headers
|
|
1164
1393
|
});
|
|
1165
1394
|
res.end(JSON.stringify(body));
|
|
1166
1395
|
}
|
|
@@ -1178,11 +1407,180 @@ function sendError(res, error) {
|
|
|
1178
1407
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1179
1408
|
});
|
|
1180
1409
|
}
|
|
1410
|
+
|
|
1411
|
+
// src/inspect.ts
|
|
1412
|
+
import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, jwtVerify as jwtVerify2 } from "jose";
|
|
1413
|
+
async function inspectToken(token, options = {}) {
|
|
1414
|
+
const checks = [];
|
|
1415
|
+
const trimmed = token.trim();
|
|
1416
|
+
let header = null;
|
|
1417
|
+
let payload = null;
|
|
1418
|
+
if (trimmed.split(".").length !== 3) {
|
|
1419
|
+
checks.push({ name: "Format", status: "fail", detail: "A JWT has three parts separated by dots." });
|
|
1420
|
+
return { kind: "unknown", header, payload, checks };
|
|
1421
|
+
}
|
|
1422
|
+
try {
|
|
1423
|
+
header = decodeProtectedHeader(trimmed);
|
|
1424
|
+
payload = decodeJwt(trimmed);
|
|
1425
|
+
} catch {
|
|
1426
|
+
checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
|
|
1427
|
+
return { kind: "unknown", header, payload, checks };
|
|
1428
|
+
}
|
|
1429
|
+
checks.push({ name: "Format", status: "pass", detail: "Three base64url parts with JSON header and payload." });
|
|
1430
|
+
checks.push(
|
|
1431
|
+
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.` }
|
|
1432
|
+
);
|
|
1433
|
+
const signer = typeof header.kid === "string" && header.kid.startsWith("kinde-testkit") ? "kinde-testkit" : "another issuer";
|
|
1434
|
+
checks.push({ name: "Key", status: "pass", detail: `kid ${String(header.kid ?? "missing")} (${signer}).` });
|
|
1435
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
1436
|
+
if (typeof payload.exp !== "number") {
|
|
1437
|
+
checks.push({ name: "Expiry", status: "fail", detail: "No exp claim." });
|
|
1438
|
+
} else if (payload.exp <= now) {
|
|
1439
|
+
checks.push({ name: "Expiry", status: "fail", detail: `Expired ${formatSpan(now - payload.exp)} ago.` });
|
|
1440
|
+
} else {
|
|
1441
|
+
checks.push({ name: "Expiry", status: "pass", detail: `Expires in ${formatSpan(payload.exp - now)}.` });
|
|
1442
|
+
}
|
|
1443
|
+
if (typeof payload.iat === "number" && payload.iat > now + 60) {
|
|
1444
|
+
checks.push({ name: "Issued at", status: "fail", detail: `iat is ${formatSpan(payload.iat - now)} in the future.` });
|
|
1445
|
+
}
|
|
1446
|
+
if (options.issuerUrl) {
|
|
1447
|
+
const issuer = options.issuerUrl.replace(/\/+$/, "");
|
|
1448
|
+
if (payload.iss !== issuer) {
|
|
1449
|
+
checks.push({ name: "Issuer", status: "fail", detail: `iss is ${String(payload.iss)}, not ${issuer}.` });
|
|
1450
|
+
} else {
|
|
1451
|
+
checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
|
|
1452
|
+
}
|
|
1453
|
+
try {
|
|
1454
|
+
await jwtVerify2(trimmed, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
|
|
1455
|
+
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1456
|
+
} catch (error) {
|
|
1457
|
+
const code = error.code ?? "";
|
|
1458
|
+
if (code === "ERR_JWT_EXPIRED" || code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
|
|
1459
|
+
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1460
|
+
} else {
|
|
1461
|
+
checks.push({ name: "Signature", status: "fail", detail: describeVerifyError(code, issuer) });
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
} else {
|
|
1465
|
+
checks.push({ name: "Signature", status: "warn", detail: "Not checked. Pass --url to verify against a running issuer." });
|
|
1466
|
+
}
|
|
1467
|
+
return { kind: kindOf(payload), header, payload, checks };
|
|
1468
|
+
}
|
|
1469
|
+
function kindOf(payload) {
|
|
1470
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) return "m2m";
|
|
1471
|
+
if ("email" in payload || "org_codes" in payload || "at_hash" in payload || "nonce" in payload) return "id";
|
|
1472
|
+
if ("scp" in payload || "permissions" in payload || "org_code" in payload) return "access";
|
|
1473
|
+
return "unknown";
|
|
1474
|
+
}
|
|
1475
|
+
function describeVerifyError(code, issuer) {
|
|
1476
|
+
if (code === "ERR_JWKS_NO_MATCHING_KEY") return `No key in ${issuer}'s JWKS matches this token's kid.`;
|
|
1477
|
+
if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "The signature does not match the token. It was changed after signing.";
|
|
1478
|
+
if (code === "ERR_JOSE_ALG_NOT_ALLOWED" || code === "ERR_JOSE_NOT_SUPPORTED") return "The token is not signed with RS256.";
|
|
1479
|
+
if (code === "ERR_JWKS_TIMEOUT" || code === "ERR_JOSE_GENERIC") return `Could not fetch keys from ${issuer}.`;
|
|
1480
|
+
return `Verification failed (${code || "unknown error"}).`;
|
|
1481
|
+
}
|
|
1482
|
+
function formatSpan(seconds) {
|
|
1483
|
+
const s = Math.max(0, Math.round(seconds));
|
|
1484
|
+
if (s < 60) return `${s}s`;
|
|
1485
|
+
if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
|
|
1486
|
+
if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor(s % 3600 / 60)}m`;
|
|
1487
|
+
return `${Math.floor(s / 86400)}d ${Math.floor(s % 86400 / 3600)}h`;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
// src/doctor.ts
|
|
1491
|
+
var SECRET_FORMAT = /^[a-zA-Z0-9]{40,60}$/;
|
|
1492
|
+
async function runDoctor(options) {
|
|
1493
|
+
const url = options.url.replace(/\/+$/, "");
|
|
1494
|
+
const checks = [];
|
|
1495
|
+
let issuer = null;
|
|
1496
|
+
try {
|
|
1497
|
+
const health = await (await fetch(`${url}/testkit/health`)).json();
|
|
1498
|
+
issuer = health.issuer ?? null;
|
|
1499
|
+
checks.push({ name: "Issuer running", status: "pass", detail: `${url} answers, issuer ${issuer}.` });
|
|
1500
|
+
} catch {
|
|
1501
|
+
checks.push({ name: "Issuer running", status: "fail", detail: `Nothing answers at ${url}. Start it with "kinde-testkit start".` });
|
|
1502
|
+
}
|
|
1503
|
+
if (issuer) {
|
|
1504
|
+
try {
|
|
1505
|
+
const discovery2 = await (await fetch(`${url}/.well-known/openid-configuration`)).json();
|
|
1506
|
+
checks.push(
|
|
1507
|
+
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}.` }
|
|
1508
|
+
);
|
|
1509
|
+
} catch {
|
|
1510
|
+
checks.push({ name: "Discovery", status: "fail", detail: "Could not read /.well-known/openid-configuration." });
|
|
1511
|
+
}
|
|
1512
|
+
try {
|
|
1513
|
+
const jwks = await (await fetch(`${url}/.well-known/jwks.json`)).json();
|
|
1514
|
+
const usable = (jwks.keys ?? []).filter((key) => key.kty === "RSA" && key.use === "sig");
|
|
1515
|
+
checks.push(
|
|
1516
|
+
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." }
|
|
1517
|
+
);
|
|
1518
|
+
} catch {
|
|
1519
|
+
checks.push({ name: "JWKS", status: "fail", detail: "Could not read /.well-known/jwks.json." });
|
|
1520
|
+
}
|
|
1521
|
+
try {
|
|
1522
|
+
const users = await (await fetch(`${url}/testkit/users`)).json();
|
|
1523
|
+
checks.push(
|
|
1524
|
+
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." }
|
|
1525
|
+
);
|
|
1526
|
+
} catch {
|
|
1527
|
+
checks.push({ name: "Seed", status: "warn", detail: "Could not read /testkit/users." });
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
const env = options.env;
|
|
1531
|
+
const configured = env.KINDE_ISSUER_URL?.trim().replace(/\/+$/, "");
|
|
1532
|
+
if (!configured) {
|
|
1533
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: "Not set. Set it to the testkit's issuer for test runs." });
|
|
1534
|
+
} else if (/\.kinde\.com$/i.test(new URL(configured, "http://x").hostname)) {
|
|
1535
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} is a real Kinde domain. Tests would sign in against Kinde, not the testkit.` });
|
|
1536
|
+
} else if (issuer && configured !== issuer) {
|
|
1537
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} does not match the testkit issuer ${issuer}. Token checks compare iss exactly.` });
|
|
1538
|
+
} else {
|
|
1539
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "pass", detail: `${configured}.` });
|
|
1540
|
+
}
|
|
1541
|
+
checks.push(
|
|
1542
|
+
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." }
|
|
1543
|
+
);
|
|
1544
|
+
const secret = env.KINDE_CLIENT_SECRET;
|
|
1545
|
+
if (!secret) {
|
|
1546
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "warn", detail: "Not set. Server-side SDKs, such as the Next.js SDK, need it." });
|
|
1547
|
+
} else if (!SECRET_FORMAT.test(secret)) {
|
|
1548
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "fail", detail: "The Next.js SDK only accepts 40 to 60 letters and digits." });
|
|
1549
|
+
} else {
|
|
1550
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1551
|
+
}
|
|
1552
|
+
const site = env.KINDE_SITE_URL;
|
|
1553
|
+
if (!site) {
|
|
1554
|
+
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
1555
|
+
} else if (!/^https?:\/\//.test(site)) {
|
|
1556
|
+
checks.push({ name: "KINDE_SITE_URL", status: "fail", detail: `${site} is not an http or https URL.` });
|
|
1557
|
+
} else {
|
|
1558
|
+
checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
|
|
1559
|
+
}
|
|
1560
|
+
return { url, checks, ok: checks.every((check) => check.status !== "fail") };
|
|
1561
|
+
}
|
|
1562
|
+
function parseEnvFile(text) {
|
|
1563
|
+
const values = {};
|
|
1564
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1565
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
1566
|
+
if (!match) continue;
|
|
1567
|
+
let value = match[2];
|
|
1568
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
1569
|
+
value = value.slice(1, -1);
|
|
1570
|
+
} else {
|
|
1571
|
+
value = value.replace(/\s+#.*$/, "");
|
|
1572
|
+
}
|
|
1573
|
+
values[match[1]] = value;
|
|
1574
|
+
}
|
|
1575
|
+
return values;
|
|
1576
|
+
}
|
|
1181
1577
|
export {
|
|
1182
1578
|
DEFAULT_AUTH_METHODS,
|
|
1183
1579
|
DEFAULT_CLIENT_ID,
|
|
1184
1580
|
DEFAULT_ISSUER,
|
|
1581
|
+
DEFAULT_M2M_CLIENT_ID,
|
|
1185
1582
|
DEFAULT_SCOPES,
|
|
1583
|
+
FailureInjector,
|
|
1186
1584
|
INVALID_TOKEN_KINDS,
|
|
1187
1585
|
KindeTestkit,
|
|
1188
1586
|
ScenarioBuilder,
|
|
@@ -1192,10 +1590,13 @@ export {
|
|
|
1192
1590
|
createKindeUser,
|
|
1193
1591
|
createMembership,
|
|
1194
1592
|
getDefaultTestkit,
|
|
1593
|
+
inspectToken,
|
|
1195
1594
|
isAuthenticated,
|
|
1595
|
+
parseEnvFile,
|
|
1196
1596
|
principalFromClaims,
|
|
1197
1597
|
resetFactories,
|
|
1198
1598
|
resolveSeed,
|
|
1599
|
+
runDoctor,
|
|
1199
1600
|
scenario,
|
|
1200
1601
|
seedScenario,
|
|
1201
1602
|
startKindeTestkit,
|