kinde-testkit 0.2.2 → 0.4.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 +18 -0
- package/README.md +179 -7
- package/dist/cli.js +1014 -15
- package/dist/index.cjs +731 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +180 -2
- package/dist/index.d.ts +180 -2
- package/dist/index.js +723 -14
- package/dist/index.js.map +1 -1
- package/dist/playwright.d.ts +61 -1
- package/dist/playwright.js +36 -7
- package/dist/playwright.js.map +1 -1
- package/dist/vitest.d.ts +158 -0
- package/dist/vitest.js +553 -14
- package/dist/vitest.js.map +1 -1
- package/package.json +2 -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({
|
|
@@ -302,6 +324,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
302
324
|
if (scenario2.kind === "unauthenticated") return null;
|
|
303
325
|
return scenarioPrincipal(scenario2, this.issuer);
|
|
304
326
|
}
|
|
327
|
+
async signPayload(payload, invalid2) {
|
|
328
|
+
return this.sign(payload, invalid2);
|
|
329
|
+
}
|
|
305
330
|
async sign(payload, invalid2) {
|
|
306
331
|
if (invalid2 === "unsigned") {
|
|
307
332
|
const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
@@ -321,8 +346,10 @@ function principalFromClaims(claims) {
|
|
|
321
346
|
(role) => typeof role === "string" ? role : String(role.key ?? "")
|
|
322
347
|
) : [];
|
|
323
348
|
const permissions = Array.isArray(claims.permissions) ? claims.permissions.map(String) : [];
|
|
349
|
+
const machine = Array.isArray(claims.gty) && claims.gty.includes("client_credentials");
|
|
324
350
|
return {
|
|
325
|
-
|
|
351
|
+
type: machine ? "machine" : "user",
|
|
352
|
+
subject: String((machine ? claims.azp : claims.sub) ?? ""),
|
|
326
353
|
issuer: String(claims.iss ?? ""),
|
|
327
354
|
organization: typeof claims.org_code === "string" ? { code: claims.org_code } : null,
|
|
328
355
|
roles: roles.filter(Boolean),
|
|
@@ -332,6 +359,7 @@ function principalFromClaims(claims) {
|
|
|
332
359
|
}
|
|
333
360
|
function scenarioPrincipal(scenario2, issuer) {
|
|
334
361
|
return {
|
|
362
|
+
type: "user",
|
|
335
363
|
subject: scenario2.user.id,
|
|
336
364
|
issuer,
|
|
337
365
|
organization: scenario2.organization ? { code: scenario2.organization.code } : null,
|
|
@@ -422,6 +450,20 @@ function resolveSeed(input) {
|
|
|
422
450
|
const rawUsers = listOf(input.users, "users", problems);
|
|
423
451
|
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
424
452
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
453
|
+
const rawApplications = listOf(input.applications, "applications", problems);
|
|
454
|
+
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
455
|
+
const webhooks = [];
|
|
456
|
+
rawWebhooks.forEach((raw, index) => {
|
|
457
|
+
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
458
|
+
problems.push(`webhooks[${index}] needs an http or https "url".`);
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
|
|
462
|
+
problems.push(`webhooks[${index}].events must be a list of event type names.`);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
webhooks.push({ url: raw.url, events: raw.events });
|
|
466
|
+
});
|
|
425
467
|
const users = [];
|
|
426
468
|
rawUsers.forEach((raw, index) => {
|
|
427
469
|
if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
|
|
@@ -477,10 +519,43 @@ function resolveSeed(input) {
|
|
|
477
519
|
})
|
|
478
520
|
);
|
|
479
521
|
});
|
|
522
|
+
const applications = [];
|
|
523
|
+
rawApplications.forEach((raw, index) => {
|
|
524
|
+
if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
|
|
525
|
+
problems.push(`applications[${index}] needs a string "clientId".`);
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
if (applications.some((app) => app.clientId === raw.clientId)) {
|
|
529
|
+
problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
|
|
533
|
+
problems.push(`applications[${index}].clientSecret must be a string.`);
|
|
534
|
+
}
|
|
535
|
+
if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
|
|
536
|
+
problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
|
|
537
|
+
}
|
|
538
|
+
for (const field of ["scopes", "permissions"]) {
|
|
539
|
+
const value = raw[field];
|
|
540
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
|
|
541
|
+
problems.push(`applications[${index}].${field} must be a list of strings.`);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
const audience = raw.audience;
|
|
545
|
+
applications.push({
|
|
546
|
+
clientId: raw.clientId,
|
|
547
|
+
clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
|
|
548
|
+
name: typeof raw.name === "string" ? raw.name : raw.clientId,
|
|
549
|
+
organizationCode: typeof raw.organization === "string" ? raw.organization : null,
|
|
550
|
+
scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
|
|
551
|
+
permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
|
|
552
|
+
audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
|
|
553
|
+
});
|
|
554
|
+
});
|
|
480
555
|
if (problems.length > 0) {
|
|
481
556
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
482
557
|
}
|
|
483
|
-
return { users, organizations, memberships };
|
|
558
|
+
return { users, organizations, memberships, applications, webhooks };
|
|
484
559
|
}
|
|
485
560
|
function findUser(users, ref) {
|
|
486
561
|
const needle = ref.toLowerCase();
|
|
@@ -617,12 +692,14 @@ var OAuthError = class extends Error {
|
|
|
617
692
|
error;
|
|
618
693
|
};
|
|
619
694
|
var AuthorizationServer = class {
|
|
620
|
-
constructor(testkit, seed) {
|
|
695
|
+
constructor(testkit, seed, emit = () => void 0) {
|
|
621
696
|
this.testkit = testkit;
|
|
622
697
|
this.seed = seed;
|
|
698
|
+
this.emit = emit;
|
|
623
699
|
}
|
|
624
700
|
testkit;
|
|
625
701
|
seed;
|
|
702
|
+
emit;
|
|
626
703
|
codes = /* @__PURE__ */ new Map();
|
|
627
704
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
628
705
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -740,6 +817,7 @@ var AuthorizationServer = class {
|
|
|
740
817
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
741
818
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
742
819
|
});
|
|
820
|
+
this.emit("user.authenticated", user);
|
|
743
821
|
const target = new URL(request.redirectUri);
|
|
744
822
|
target.searchParams.set("code", code);
|
|
745
823
|
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
@@ -749,13 +827,16 @@ var AuthorizationServer = class {
|
|
|
749
827
|
try {
|
|
750
828
|
const clientId = clientIdFrom(req, form);
|
|
751
829
|
const grantType = form.grant_type;
|
|
830
|
+
if (grantType === "client_credentials") {
|
|
831
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
|
|
832
|
+
}
|
|
752
833
|
let grant;
|
|
753
834
|
if (grantType === "authorization_code") {
|
|
754
835
|
grant = this.redeemCode(form, clientId);
|
|
755
836
|
} else if (grantType === "refresh_token") {
|
|
756
837
|
grant = this.redeemRefreshToken(form, clientId);
|
|
757
838
|
} else {
|
|
758
|
-
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and
|
|
839
|
+
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
759
840
|
}
|
|
760
841
|
sendJson(res, 200, await this.issueTokens(grant));
|
|
761
842
|
} catch (error) {
|
|
@@ -765,6 +846,33 @@ var AuthorizationServer = class {
|
|
|
765
846
|
throw error;
|
|
766
847
|
}
|
|
767
848
|
}
|
|
849
|
+
async clientCredentials(clientId, clientSecret, form) {
|
|
850
|
+
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
851
|
+
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
852
|
+
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
853
|
+
}
|
|
854
|
+
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
855
|
+
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
856
|
+
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
857
|
+
return {
|
|
858
|
+
access_token: await this.testkit.m2mToken({
|
|
859
|
+
clientId,
|
|
860
|
+
organizationCode: app?.organizationCode ?? null,
|
|
861
|
+
scopes: requested,
|
|
862
|
+
grantedScopes: granted,
|
|
863
|
+
audience: audience.length > 0 ? audience : app?.audience ?? void 0,
|
|
864
|
+
permissions: app?.permissions ?? void 0
|
|
865
|
+
}),
|
|
866
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
867
|
+
scope: granted.join(" "),
|
|
868
|
+
token_type: "bearer"
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
reset() {
|
|
872
|
+
this.codes.clear();
|
|
873
|
+
this.refreshTokens.clear();
|
|
874
|
+
this.signedUpUsers.clear();
|
|
875
|
+
}
|
|
768
876
|
redeemCode(form, clientId) {
|
|
769
877
|
const code = form.code ?? "";
|
|
770
878
|
const pending = this.codes.get(code);
|
|
@@ -875,8 +983,11 @@ var AuthorizationServer = class {
|
|
|
875
983
|
if (seeded) return seeded;
|
|
876
984
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
877
985
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
878
|
-
this.signedUpUsers.
|
|
879
|
-
|
|
986
|
+
if (!this.signedUpUsers.has(user.id)) {
|
|
987
|
+
this.signedUpUsers.set(user.id, user);
|
|
988
|
+
this.emit("user.created", user);
|
|
989
|
+
}
|
|
990
|
+
return this.signedUpUsers.get(user.id);
|
|
880
991
|
}
|
|
881
992
|
organization(code) {
|
|
882
993
|
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
@@ -936,6 +1047,15 @@ function clientIdFrom(req, form) {
|
|
|
936
1047
|
if (form.client_id) return form.client_id;
|
|
937
1048
|
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
938
1049
|
}
|
|
1050
|
+
function clientSecretFrom(req, form) {
|
|
1051
|
+
const header = req.headers.authorization ?? "";
|
|
1052
|
+
if (header.startsWith("Basic ")) {
|
|
1053
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1054
|
+
const index = decoded.indexOf(":");
|
|
1055
|
+
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1056
|
+
}
|
|
1057
|
+
return form.client_secret ?? null;
|
|
1058
|
+
}
|
|
939
1059
|
function redirectWithError(res, request, error, description) {
|
|
940
1060
|
const target = new URL(request.redirectUri);
|
|
941
1061
|
target.searchParams.set("error", error);
|
|
@@ -976,6 +1096,351 @@ function sendJson(res, status, body) {
|
|
|
976
1096
|
res.end(JSON.stringify(body));
|
|
977
1097
|
}
|
|
978
1098
|
|
|
1099
|
+
// src/failures.ts
|
|
1100
|
+
var MAX_DELAY_MS = 6e4;
|
|
1101
|
+
var FailureInjector = class {
|
|
1102
|
+
rules = [];
|
|
1103
|
+
nextId = 1;
|
|
1104
|
+
add(rule) {
|
|
1105
|
+
const problems = validate(rule);
|
|
1106
|
+
if (problems.length > 0) {
|
|
1107
|
+
throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
|
|
1108
|
+
}
|
|
1109
|
+
const active = {
|
|
1110
|
+
id: `failure_${this.nextId++}`,
|
|
1111
|
+
path: rule.path,
|
|
1112
|
+
method: rule.method ? rule.method.toUpperCase() : null,
|
|
1113
|
+
status: rule.status ?? null,
|
|
1114
|
+
delayMs: rule.delayMs ?? 0,
|
|
1115
|
+
hang: rule.hang ?? false,
|
|
1116
|
+
remaining: rule.times ?? null,
|
|
1117
|
+
retryAfter: rule.retryAfter ?? 1,
|
|
1118
|
+
hits: 0
|
|
1119
|
+
};
|
|
1120
|
+
this.rules.push(active);
|
|
1121
|
+
return { ...active };
|
|
1122
|
+
}
|
|
1123
|
+
remove(id) {
|
|
1124
|
+
const before = this.rules.length;
|
|
1125
|
+
this.rules = this.rules.filter((rule) => rule.id !== id);
|
|
1126
|
+
return this.rules.length < before;
|
|
1127
|
+
}
|
|
1128
|
+
clear() {
|
|
1129
|
+
this.rules = [];
|
|
1130
|
+
}
|
|
1131
|
+
list() {
|
|
1132
|
+
return this.rules.map((rule) => ({ ...rule }));
|
|
1133
|
+
}
|
|
1134
|
+
take(method, path) {
|
|
1135
|
+
const rule = this.rules.find((r) => matches(r, method, path));
|
|
1136
|
+
if (!rule) return null;
|
|
1137
|
+
rule.hits += 1;
|
|
1138
|
+
if (rule.remaining !== null) {
|
|
1139
|
+
rule.remaining -= 1;
|
|
1140
|
+
if (rule.remaining <= 0) this.remove(rule.id);
|
|
1141
|
+
}
|
|
1142
|
+
return { ...rule };
|
|
1143
|
+
}
|
|
1144
|
+
};
|
|
1145
|
+
function failureBody(status) {
|
|
1146
|
+
const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
|
|
1147
|
+
return { error, error_description: `kinde-testkit injected a ${status} response.` };
|
|
1148
|
+
}
|
|
1149
|
+
function matches(rule, method, path) {
|
|
1150
|
+
if (rule.method && rule.method !== method.toUpperCase()) return false;
|
|
1151
|
+
if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
|
|
1152
|
+
return rule.path === path;
|
|
1153
|
+
}
|
|
1154
|
+
function validate(rule) {
|
|
1155
|
+
const problems = [];
|
|
1156
|
+
if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
|
|
1157
|
+
problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
|
|
1158
|
+
} else if (rule.path.startsWith("/testkit/")) {
|
|
1159
|
+
problems.push("Failures cannot target /testkit/ control endpoints.");
|
|
1160
|
+
}
|
|
1161
|
+
if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
|
|
1162
|
+
problems.push('"status" must be an HTTP error status between 400 and 599.');
|
|
1163
|
+
}
|
|
1164
|
+
if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
|
|
1165
|
+
problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
|
|
1166
|
+
}
|
|
1167
|
+
if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
|
|
1168
|
+
problems.push('"times" must be a whole number of 1 or more.');
|
|
1169
|
+
}
|
|
1170
|
+
if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
|
|
1171
|
+
problems.push('"retryAfter" must be a whole number of seconds.');
|
|
1172
|
+
}
|
|
1173
|
+
if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
|
|
1174
|
+
problems.push('Set at least one of "status", "delayMs" or "hang".');
|
|
1175
|
+
}
|
|
1176
|
+
return problems;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// src/webhooks.ts
|
|
1180
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
1181
|
+
var WEBHOOK_EVENT_TYPES = [
|
|
1182
|
+
"user.created",
|
|
1183
|
+
"user.updated",
|
|
1184
|
+
"user.deleted",
|
|
1185
|
+
"user.authenticated",
|
|
1186
|
+
"user.authentication_failed",
|
|
1187
|
+
"organization.created",
|
|
1188
|
+
"organization.updated",
|
|
1189
|
+
"organization.deleted",
|
|
1190
|
+
"role.created",
|
|
1191
|
+
"role.updated",
|
|
1192
|
+
"role.deleted",
|
|
1193
|
+
"permission.created",
|
|
1194
|
+
"permission.updated",
|
|
1195
|
+
"permission.deleted",
|
|
1196
|
+
"subscriber.created",
|
|
1197
|
+
"access_request.created"
|
|
1198
|
+
];
|
|
1199
|
+
var BILLING_EVENT_TYPES = [
|
|
1200
|
+
"customer.agreement_cancelled",
|
|
1201
|
+
"customer.agreement_created",
|
|
1202
|
+
"customer.invoice_overdue",
|
|
1203
|
+
"customer.meter_usage_updated",
|
|
1204
|
+
"customer.payment_failed",
|
|
1205
|
+
"customer.payment_succeeded",
|
|
1206
|
+
"customer.plan_assigned",
|
|
1207
|
+
"customer.plan_changed"
|
|
1208
|
+
];
|
|
1209
|
+
var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
|
|
1210
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
1211
|
+
var MAX_DUPLICATES = 10;
|
|
1212
|
+
var WebhookDispatcher = class {
|
|
1213
|
+
constructor(testkit, seed, endpoints = [], options = {}) {
|
|
1214
|
+
this.testkit = testkit;
|
|
1215
|
+
this.seed = seed;
|
|
1216
|
+
this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
1217
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1218
|
+
for (const endpoint of endpoints) this.addEndpoint(endpoint);
|
|
1219
|
+
this.seededEndpoints = [...this.endpoints];
|
|
1220
|
+
}
|
|
1221
|
+
testkit;
|
|
1222
|
+
seed;
|
|
1223
|
+
endpoints = [];
|
|
1224
|
+
seededEndpoints = [];
|
|
1225
|
+
log = [];
|
|
1226
|
+
nextEndpoint = 1;
|
|
1227
|
+
retryDelaysMs;
|
|
1228
|
+
timeoutMs;
|
|
1229
|
+
addEndpoint(input) {
|
|
1230
|
+
if (!isHttpUrl2(input.url)) {
|
|
1231
|
+
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
1232
|
+
}
|
|
1233
|
+
if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
|
|
1234
|
+
throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
|
|
1235
|
+
}
|
|
1236
|
+
const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
|
|
1237
|
+
this.endpoints.push(endpoint);
|
|
1238
|
+
return { ...endpoint };
|
|
1239
|
+
}
|
|
1240
|
+
removeEndpoint(id) {
|
|
1241
|
+
const before = this.endpoints.length;
|
|
1242
|
+
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
1243
|
+
return this.endpoints.length < before;
|
|
1244
|
+
}
|
|
1245
|
+
listEndpoints() {
|
|
1246
|
+
return this.endpoints.map((e) => ({ ...e }));
|
|
1247
|
+
}
|
|
1248
|
+
deliveries() {
|
|
1249
|
+
return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
|
|
1250
|
+
}
|
|
1251
|
+
reset() {
|
|
1252
|
+
this.log = [];
|
|
1253
|
+
this.endpoints = [...this.seededEndpoints];
|
|
1254
|
+
}
|
|
1255
|
+
buildEvent(options) {
|
|
1256
|
+
if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
|
|
1257
|
+
throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
|
|
1258
|
+
}
|
|
1259
|
+
const now = /* @__PURE__ */ new Date();
|
|
1260
|
+
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1261
|
+
const event = {
|
|
1262
|
+
data: options.data ?? this.buildData(options),
|
|
1263
|
+
event_id: `event_${randomBytes2(16).toString("hex")}`,
|
|
1264
|
+
event_timestamp: timestamp,
|
|
1265
|
+
source: options.source ?? "admin",
|
|
1266
|
+
timestamp,
|
|
1267
|
+
type: options.type
|
|
1268
|
+
};
|
|
1269
|
+
if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
|
|
1270
|
+
event.ip_address = options.ipAddress ?? "127.0.0.1";
|
|
1271
|
+
}
|
|
1272
|
+
return event;
|
|
1273
|
+
}
|
|
1274
|
+
async send(options) {
|
|
1275
|
+
const event = this.buildEvent(options);
|
|
1276
|
+
const copies = options.duplicate ?? 1;
|
|
1277
|
+
if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
|
|
1278
|
+
throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
|
|
1279
|
+
}
|
|
1280
|
+
const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
|
|
1281
|
+
if (options.to && !isHttpUrl2(options.to)) {
|
|
1282
|
+
throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
|
|
1283
|
+
}
|
|
1284
|
+
if (targets.length === 0) {
|
|
1285
|
+
throw new TestkitError(
|
|
1286
|
+
"INVALID_REQUEST",
|
|
1287
|
+
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
1288
|
+
);
|
|
1289
|
+
}
|
|
1290
|
+
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
1291
|
+
const signed = await this.testkit.signPayload(
|
|
1292
|
+
event,
|
|
1293
|
+
options.invalid === "stale" ? void 0 : options.invalid
|
|
1294
|
+
);
|
|
1295
|
+
const jobs = targets.flatMap((target) => {
|
|
1296
|
+
const webhookId = `wh_${randomBytes2(12).toString("hex")}`;
|
|
1297
|
+
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1298
|
+
});
|
|
1299
|
+
return Promise.all(jobs);
|
|
1300
|
+
}
|
|
1301
|
+
async deliver(url, webhookId, body, event, copy) {
|
|
1302
|
+
const delivery = {
|
|
1303
|
+
webhookId,
|
|
1304
|
+
eventId: String(event.event_id),
|
|
1305
|
+
type: String(event.type),
|
|
1306
|
+
url,
|
|
1307
|
+
copy,
|
|
1308
|
+
delivered: false,
|
|
1309
|
+
attempts: [],
|
|
1310
|
+
payload: event
|
|
1311
|
+
};
|
|
1312
|
+
this.log.push(delivery);
|
|
1313
|
+
for (const [index, delay] of this.retryDelaysMs.entries()) {
|
|
1314
|
+
if (delay > 0) await sleep(delay);
|
|
1315
|
+
const started = Date.now();
|
|
1316
|
+
try {
|
|
1317
|
+
const response = await fetch(url, {
|
|
1318
|
+
method: "POST",
|
|
1319
|
+
headers: { "content-type": "application/jwt", "webhook-id": webhookId },
|
|
1320
|
+
body,
|
|
1321
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
1322
|
+
});
|
|
1323
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
1324
|
+
delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
|
|
1325
|
+
if (response.status === 200) {
|
|
1326
|
+
delivery.delivered = true;
|
|
1327
|
+
break;
|
|
1328
|
+
}
|
|
1329
|
+
} catch (error) {
|
|
1330
|
+
const name = error.name;
|
|
1331
|
+
delivery.attempts.push({
|
|
1332
|
+
attempt: index + 1,
|
|
1333
|
+
status: null,
|
|
1334
|
+
error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
|
|
1335
|
+
durationMs: Date.now() - started
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
return { ...delivery, attempts: [...delivery.attempts] };
|
|
1340
|
+
}
|
|
1341
|
+
buildData(options) {
|
|
1342
|
+
const [subject] = options.type.split(".");
|
|
1343
|
+
switch (subject) {
|
|
1344
|
+
case "user":
|
|
1345
|
+
return { user: this.userData(options) };
|
|
1346
|
+
case "organization":
|
|
1347
|
+
return { organization: this.organizationData(options) };
|
|
1348
|
+
case "role":
|
|
1349
|
+
return { role: this.namedData(options, "role") };
|
|
1350
|
+
case "permission":
|
|
1351
|
+
return { permission: this.namedData(options, "permission") };
|
|
1352
|
+
case "subscriber": {
|
|
1353
|
+
const user = this.requireUser(options);
|
|
1354
|
+
return {
|
|
1355
|
+
subscriber: {
|
|
1356
|
+
email: user.email,
|
|
1357
|
+
first_name: user.givenName,
|
|
1358
|
+
id: stableId("sub", user.id),
|
|
1359
|
+
last_name: user.familyName,
|
|
1360
|
+
user_id: user.id
|
|
1361
|
+
}
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
case "access_request": {
|
|
1365
|
+
const user = this.requireUser(options);
|
|
1366
|
+
return {
|
|
1367
|
+
access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
default:
|
|
1371
|
+
throw new TestkitError(
|
|
1372
|
+
"INVALID_REQUEST",
|
|
1373
|
+
`kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
|
|
1374
|
+
);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
emitForUser(type, user) {
|
|
1378
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1379
|
+
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
1380
|
+
void this.send({ type, data, source: "user" }).catch(() => void 0);
|
|
1381
|
+
}
|
|
1382
|
+
userData(options) {
|
|
1383
|
+
const user = this.requireUser(options);
|
|
1384
|
+
if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
|
|
1385
|
+
return this.userPayload(user);
|
|
1386
|
+
}
|
|
1387
|
+
userPayload(user) {
|
|
1388
|
+
return {
|
|
1389
|
+
email: user.email,
|
|
1390
|
+
first_name: user.givenName,
|
|
1391
|
+
id: user.id,
|
|
1392
|
+
is_password_reset_requested: false,
|
|
1393
|
+
is_suspended: false,
|
|
1394
|
+
last_name: user.familyName,
|
|
1395
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
|
|
1396
|
+
code: m.organizationCode,
|
|
1397
|
+
permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
|
|
1398
|
+
roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
|
|
1399
|
+
})),
|
|
1400
|
+
phone: null,
|
|
1401
|
+
username: typeof user.claims.username === "string" ? user.claims.username : null
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
organizationData(options) {
|
|
1405
|
+
if (!options.organization) {
|
|
1406
|
+
throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
|
|
1407
|
+
}
|
|
1408
|
+
const org = this.seed.organizations.find((o) => o.code === options.organization);
|
|
1409
|
+
if (options.type === "organization.deleted") return { code: options.organization };
|
|
1410
|
+
const name = org?.name ?? titleCase(options.organization);
|
|
1411
|
+
const data = { code: options.organization, external_id: null, handle: slug(name), name };
|
|
1412
|
+
if (options.type === "organization.updated") data.is_allow_registrations = false;
|
|
1413
|
+
return data;
|
|
1414
|
+
}
|
|
1415
|
+
namedData(options, kind) {
|
|
1416
|
+
const key = kind === "role" ? options.role : options.permission;
|
|
1417
|
+
if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
|
|
1418
|
+
const id = stableId(kind === "role" ? "role" : "perm", key);
|
|
1419
|
+
if (options.type.endsWith(".deleted")) return { id };
|
|
1420
|
+
const data = { description: "", id, key, name: titleCase(key) };
|
|
1421
|
+
if (kind === "role") data.is_default_role = false;
|
|
1422
|
+
return data;
|
|
1423
|
+
}
|
|
1424
|
+
requireUser(options) {
|
|
1425
|
+
if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
|
|
1426
|
+
const user = findUser(this.seed.users, options.user);
|
|
1427
|
+
if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
|
|
1428
|
+
return user;
|
|
1429
|
+
}
|
|
1430
|
+
};
|
|
1431
|
+
function isHttpUrl2(value) {
|
|
1432
|
+
if (typeof value !== "string") return false;
|
|
1433
|
+
try {
|
|
1434
|
+
const { protocol } = new URL(value);
|
|
1435
|
+
return protocol === "http:" || protocol === "https:";
|
|
1436
|
+
} catch {
|
|
1437
|
+
return false;
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
function sleep(ms) {
|
|
1441
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1442
|
+
}
|
|
1443
|
+
|
|
979
1444
|
// src/server.ts
|
|
980
1445
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
981
1446
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
@@ -989,12 +1454,11 @@ async function startKindeTestkit(options = {}) {
|
|
|
989
1454
|
);
|
|
990
1455
|
}
|
|
991
1456
|
const seed = resolveSeed(options.seed ?? {});
|
|
1457
|
+
const failures = new FailureInjector();
|
|
992
1458
|
let ready;
|
|
993
|
-
const testkitReady = new Promise(
|
|
994
|
-
(resolve) => ready = resolve
|
|
995
|
-
);
|
|
1459
|
+
const testkitReady = new Promise((resolve) => ready = resolve);
|
|
996
1460
|
const server = createServer((req, res) => {
|
|
997
|
-
testkitReady.then((
|
|
1461
|
+
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
998
1462
|
});
|
|
999
1463
|
await new Promise((resolve, reject) => {
|
|
1000
1464
|
server.once("error", reject);
|
|
@@ -1008,7 +1472,14 @@ async function startKindeTestkit(options = {}) {
|
|
|
1008
1472
|
audience: options.audience ?? options.seed?.audience,
|
|
1009
1473
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1010
1474
|
});
|
|
1011
|
-
|
|
1475
|
+
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
1476
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
|
|
1477
|
+
const reset = () => {
|
|
1478
|
+
auth.reset();
|
|
1479
|
+
failures.clear();
|
|
1480
|
+
webhooks.reset();
|
|
1481
|
+
};
|
|
1482
|
+
ready({ testkit, auth, seed, failures, webhooks, reset });
|
|
1012
1483
|
return {
|
|
1013
1484
|
url,
|
|
1014
1485
|
issuer: testkit.issuer,
|
|
@@ -1016,16 +1487,32 @@ async function startKindeTestkit(options = {}) {
|
|
|
1016
1487
|
jwksUri: `${url}/.well-known/jwks`,
|
|
1017
1488
|
testkit,
|
|
1018
1489
|
seed,
|
|
1490
|
+
failures,
|
|
1491
|
+
webhooks,
|
|
1492
|
+
reset,
|
|
1019
1493
|
close: () => new Promise((resolve, reject) => {
|
|
1020
1494
|
server.closeAllConnections();
|
|
1021
1495
|
server.close((error) => error ? reject(error) : resolve());
|
|
1022
1496
|
})
|
|
1023
1497
|
};
|
|
1024
1498
|
}
|
|
1025
|
-
async function handle(req, res,
|
|
1499
|
+
async function handle(req, res, context) {
|
|
1500
|
+
const { testkit, auth, seed, failures, webhooks } = context;
|
|
1026
1501
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1027
1502
|
const { pathname } = url;
|
|
1028
1503
|
const method = req.method ?? "GET";
|
|
1504
|
+
if (!pathname.startsWith("/testkit/")) {
|
|
1505
|
+
const failure = failures.take(method, pathname);
|
|
1506
|
+
if (failure) {
|
|
1507
|
+
if (failure.hang) return;
|
|
1508
|
+
if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
|
|
1509
|
+
if (failure.status !== null) {
|
|
1510
|
+
const headers = {};
|
|
1511
|
+
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1512
|
+
return sendJson2(res, failure.status, failureBody(failure.status), headers);
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1029
1516
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
1030
1517
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1031
1518
|
return sendJson2(res, 200, discovery(testkit));
|
|
@@ -1043,6 +1530,37 @@ async function handle(req, res, testkit, auth, seed) {
|
|
|
1043
1530
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1044
1531
|
return sendJson2(res, 200, seed.memberships);
|
|
1045
1532
|
}
|
|
1533
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
|
|
1534
|
+
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1535
|
+
return sendJson2(res, 201, failures.add(await readJson(req)));
|
|
1536
|
+
}
|
|
1537
|
+
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1538
|
+
failures.clear();
|
|
1539
|
+
return sendJson2(res, 200, { ok: true });
|
|
1540
|
+
}
|
|
1541
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1542
|
+
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1543
|
+
return sendJson2(res, removed ? 200 : 404, { ok: removed });
|
|
1544
|
+
}
|
|
1545
|
+
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1546
|
+
return sendJson2(res, 200, await webhooks.send(await readJson(req)));
|
|
1547
|
+
}
|
|
1548
|
+
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1549
|
+
return sendJson2(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1550
|
+
}
|
|
1551
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson2(res, 200, webhooks.deliveries());
|
|
1552
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson2(res, 200, webhooks.listEndpoints());
|
|
1553
|
+
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1554
|
+
return sendJson2(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1555
|
+
}
|
|
1556
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1557
|
+
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1558
|
+
return sendJson2(res, removed ? 200 : 404, { ok: removed });
|
|
1559
|
+
}
|
|
1560
|
+
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1561
|
+
context.reset();
|
|
1562
|
+
return sendJson2(res, 200, { ok: true });
|
|
1563
|
+
}
|
|
1046
1564
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1047
1565
|
const body = await readJson(req);
|
|
1048
1566
|
const accessToken = await issueToken(testkit, seed, body);
|
|
@@ -1082,6 +1600,21 @@ async function issueToken(testkit, seed, body) {
|
|
|
1082
1600
|
]);
|
|
1083
1601
|
}
|
|
1084
1602
|
const expiresIn = input.expiresIn;
|
|
1603
|
+
if (input.m2m === true) {
|
|
1604
|
+
const clientId = optionalString(input, "clientId");
|
|
1605
|
+
const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
|
|
1606
|
+
const scopes = optionalStrings(input, "scopes") ?? [];
|
|
1607
|
+
return testkit.m2mToken({
|
|
1608
|
+
clientId,
|
|
1609
|
+
organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
|
|
1610
|
+
scopes,
|
|
1611
|
+
grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
|
|
1612
|
+
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
1613
|
+
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
1614
|
+
expiresIn,
|
|
1615
|
+
invalid: invalid2
|
|
1616
|
+
});
|
|
1617
|
+
}
|
|
1085
1618
|
const permissions = optionalStrings(input, "permissions");
|
|
1086
1619
|
const roles = optionalStrings(input, "roles");
|
|
1087
1620
|
const userRef = optionalString(input, "user");
|
|
@@ -1157,10 +1690,11 @@ async function readText(req) {
|
|
|
1157
1690
|
}
|
|
1158
1691
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1159
1692
|
}
|
|
1160
|
-
function sendJson2(res, status, body) {
|
|
1693
|
+
function sendJson2(res, status, body, headers = {}) {
|
|
1161
1694
|
res.writeHead(status, {
|
|
1162
1695
|
"content-type": "application/json; charset=utf-8",
|
|
1163
|
-
"cache-control": "no-store"
|
|
1696
|
+
"cache-control": "no-store",
|
|
1697
|
+
...headers
|
|
1164
1698
|
});
|
|
1165
1699
|
res.end(JSON.stringify(body));
|
|
1166
1700
|
}
|
|
@@ -1178,24 +1712,199 @@ function sendError(res, error) {
|
|
|
1178
1712
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1179
1713
|
});
|
|
1180
1714
|
}
|
|
1715
|
+
|
|
1716
|
+
// src/inspect.ts
|
|
1717
|
+
import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, jwtVerify as jwtVerify2 } from "jose";
|
|
1718
|
+
async function inspectToken(token, options = {}) {
|
|
1719
|
+
const checks = [];
|
|
1720
|
+
const trimmed = token.trim();
|
|
1721
|
+
let header = null;
|
|
1722
|
+
let payload = null;
|
|
1723
|
+
if (trimmed.split(".").length !== 3) {
|
|
1724
|
+
checks.push({ name: "Format", status: "fail", detail: "A JWT has three parts separated by dots." });
|
|
1725
|
+
return { kind: "unknown", header, payload, checks };
|
|
1726
|
+
}
|
|
1727
|
+
try {
|
|
1728
|
+
header = decodeProtectedHeader(trimmed);
|
|
1729
|
+
payload = decodeJwt(trimmed);
|
|
1730
|
+
} catch {
|
|
1731
|
+
checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
|
|
1732
|
+
return { kind: "unknown", header, payload, checks };
|
|
1733
|
+
}
|
|
1734
|
+
checks.push({ name: "Format", status: "pass", detail: "Three base64url parts with JSON header and payload." });
|
|
1735
|
+
checks.push(
|
|
1736
|
+
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.` }
|
|
1737
|
+
);
|
|
1738
|
+
const signer = typeof header.kid === "string" && header.kid.startsWith("kinde-testkit") ? "kinde-testkit" : "another issuer";
|
|
1739
|
+
checks.push({ name: "Key", status: "pass", detail: `kid ${String(header.kid ?? "missing")} (${signer}).` });
|
|
1740
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
1741
|
+
if (typeof payload.exp !== "number") {
|
|
1742
|
+
checks.push({ name: "Expiry", status: "fail", detail: "No exp claim." });
|
|
1743
|
+
} else if (payload.exp <= now) {
|
|
1744
|
+
checks.push({ name: "Expiry", status: "fail", detail: `Expired ${formatSpan(now - payload.exp)} ago.` });
|
|
1745
|
+
} else {
|
|
1746
|
+
checks.push({ name: "Expiry", status: "pass", detail: `Expires in ${formatSpan(payload.exp - now)}.` });
|
|
1747
|
+
}
|
|
1748
|
+
if (typeof payload.iat === "number" && payload.iat > now + 60) {
|
|
1749
|
+
checks.push({ name: "Issued at", status: "fail", detail: `iat is ${formatSpan(payload.iat - now)} in the future.` });
|
|
1750
|
+
}
|
|
1751
|
+
if (options.issuerUrl) {
|
|
1752
|
+
const issuer = options.issuerUrl.replace(/\/+$/, "");
|
|
1753
|
+
if (payload.iss !== issuer) {
|
|
1754
|
+
checks.push({ name: "Issuer", status: "fail", detail: `iss is ${String(payload.iss)}, not ${issuer}.` });
|
|
1755
|
+
} else {
|
|
1756
|
+
checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
|
|
1757
|
+
}
|
|
1758
|
+
try {
|
|
1759
|
+
await jwtVerify2(trimmed, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
|
|
1760
|
+
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1761
|
+
} catch (error) {
|
|
1762
|
+
const code = error.code ?? "";
|
|
1763
|
+
if (code === "ERR_JWT_EXPIRED" || code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
|
|
1764
|
+
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1765
|
+
} else {
|
|
1766
|
+
checks.push({ name: "Signature", status: "fail", detail: describeVerifyError(code, issuer) });
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
} else {
|
|
1770
|
+
checks.push({ name: "Signature", status: "warn", detail: "Not checked. Pass --url to verify against a running issuer." });
|
|
1771
|
+
}
|
|
1772
|
+
return { kind: kindOf(payload), header, payload, checks };
|
|
1773
|
+
}
|
|
1774
|
+
function kindOf(payload) {
|
|
1775
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) return "m2m";
|
|
1776
|
+
if ("email" in payload || "org_codes" in payload || "at_hash" in payload || "nonce" in payload) return "id";
|
|
1777
|
+
if ("scp" in payload || "permissions" in payload || "org_code" in payload) return "access";
|
|
1778
|
+
return "unknown";
|
|
1779
|
+
}
|
|
1780
|
+
function describeVerifyError(code, issuer) {
|
|
1781
|
+
if (code === "ERR_JWKS_NO_MATCHING_KEY") return `No key in ${issuer}'s JWKS matches this token's kid.`;
|
|
1782
|
+
if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "The signature does not match the token. It was changed after signing.";
|
|
1783
|
+
if (code === "ERR_JOSE_ALG_NOT_ALLOWED" || code === "ERR_JOSE_NOT_SUPPORTED") return "The token is not signed with RS256.";
|
|
1784
|
+
if (code === "ERR_JWKS_TIMEOUT" || code === "ERR_JOSE_GENERIC") return `Could not fetch keys from ${issuer}.`;
|
|
1785
|
+
return `Verification failed (${code || "unknown error"}).`;
|
|
1786
|
+
}
|
|
1787
|
+
function formatSpan(seconds) {
|
|
1788
|
+
const s = Math.max(0, Math.round(seconds));
|
|
1789
|
+
if (s < 60) return `${s}s`;
|
|
1790
|
+
if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
|
|
1791
|
+
if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor(s % 3600 / 60)}m`;
|
|
1792
|
+
return `${Math.floor(s / 86400)}d ${Math.floor(s % 86400 / 3600)}h`;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
// src/doctor.ts
|
|
1796
|
+
var SECRET_FORMAT = /^[a-zA-Z0-9]{40,60}$/;
|
|
1797
|
+
async function runDoctor(options) {
|
|
1798
|
+
const url = options.url.replace(/\/+$/, "");
|
|
1799
|
+
const checks = [];
|
|
1800
|
+
let issuer = null;
|
|
1801
|
+
try {
|
|
1802
|
+
const health = await (await fetch(`${url}/testkit/health`)).json();
|
|
1803
|
+
issuer = health.issuer ?? null;
|
|
1804
|
+
checks.push({ name: "Issuer running", status: "pass", detail: `${url} answers, issuer ${issuer}.` });
|
|
1805
|
+
} catch {
|
|
1806
|
+
checks.push({ name: "Issuer running", status: "fail", detail: `Nothing answers at ${url}. Start it with "kinde-testkit start".` });
|
|
1807
|
+
}
|
|
1808
|
+
if (issuer) {
|
|
1809
|
+
try {
|
|
1810
|
+
const discovery2 = await (await fetch(`${url}/.well-known/openid-configuration`)).json();
|
|
1811
|
+
checks.push(
|
|
1812
|
+
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}.` }
|
|
1813
|
+
);
|
|
1814
|
+
} catch {
|
|
1815
|
+
checks.push({ name: "Discovery", status: "fail", detail: "Could not read /.well-known/openid-configuration." });
|
|
1816
|
+
}
|
|
1817
|
+
try {
|
|
1818
|
+
const jwks = await (await fetch(`${url}/.well-known/jwks.json`)).json();
|
|
1819
|
+
const usable = (jwks.keys ?? []).filter((key) => key.kty === "RSA" && key.use === "sig");
|
|
1820
|
+
checks.push(
|
|
1821
|
+
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." }
|
|
1822
|
+
);
|
|
1823
|
+
} catch {
|
|
1824
|
+
checks.push({ name: "JWKS", status: "fail", detail: "Could not read /.well-known/jwks.json." });
|
|
1825
|
+
}
|
|
1826
|
+
try {
|
|
1827
|
+
const users = await (await fetch(`${url}/testkit/users`)).json();
|
|
1828
|
+
checks.push(
|
|
1829
|
+
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." }
|
|
1830
|
+
);
|
|
1831
|
+
} catch {
|
|
1832
|
+
checks.push({ name: "Seed", status: "warn", detail: "Could not read /testkit/users." });
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
const env = options.env;
|
|
1836
|
+
const configured = env.KINDE_ISSUER_URL?.trim().replace(/\/+$/, "");
|
|
1837
|
+
if (!configured) {
|
|
1838
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: "Not set. Set it to the testkit's issuer for test runs." });
|
|
1839
|
+
} else if (/\.kinde\.com$/i.test(new URL(configured, "http://x").hostname)) {
|
|
1840
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} is a real Kinde domain. Tests would sign in against Kinde, not the testkit.` });
|
|
1841
|
+
} else if (issuer && configured !== issuer) {
|
|
1842
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} does not match the testkit issuer ${issuer}. Token checks compare iss exactly.` });
|
|
1843
|
+
} else {
|
|
1844
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "pass", detail: `${configured}.` });
|
|
1845
|
+
}
|
|
1846
|
+
checks.push(
|
|
1847
|
+
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." }
|
|
1848
|
+
);
|
|
1849
|
+
const secret = env.KINDE_CLIENT_SECRET;
|
|
1850
|
+
if (!secret) {
|
|
1851
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "warn", detail: "Not set. Server-side SDKs, such as the Next.js SDK, need it." });
|
|
1852
|
+
} else if (!SECRET_FORMAT.test(secret)) {
|
|
1853
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "fail", detail: "The Next.js SDK only accepts 40 to 60 letters and digits." });
|
|
1854
|
+
} else {
|
|
1855
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1856
|
+
}
|
|
1857
|
+
const site = env.KINDE_SITE_URL;
|
|
1858
|
+
if (!site) {
|
|
1859
|
+
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
1860
|
+
} else if (!/^https?:\/\//.test(site)) {
|
|
1861
|
+
checks.push({ name: "KINDE_SITE_URL", status: "fail", detail: `${site} is not an http or https URL.` });
|
|
1862
|
+
} else {
|
|
1863
|
+
checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
|
|
1864
|
+
}
|
|
1865
|
+
return { url, checks, ok: checks.every((check) => check.status !== "fail") };
|
|
1866
|
+
}
|
|
1867
|
+
function parseEnvFile(text) {
|
|
1868
|
+
const values = {};
|
|
1869
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1870
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
1871
|
+
if (!match) continue;
|
|
1872
|
+
let value = match[2];
|
|
1873
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
1874
|
+
value = value.slice(1, -1);
|
|
1875
|
+
} else {
|
|
1876
|
+
value = value.replace(/\s+#.*$/, "");
|
|
1877
|
+
}
|
|
1878
|
+
values[match[1]] = value;
|
|
1879
|
+
}
|
|
1880
|
+
return values;
|
|
1881
|
+
}
|
|
1181
1882
|
export {
|
|
1883
|
+
BILLING_EVENT_TYPES,
|
|
1182
1884
|
DEFAULT_AUTH_METHODS,
|
|
1183
1885
|
DEFAULT_CLIENT_ID,
|
|
1184
1886
|
DEFAULT_ISSUER,
|
|
1887
|
+
DEFAULT_M2M_CLIENT_ID,
|
|
1185
1888
|
DEFAULT_SCOPES,
|
|
1889
|
+
FailureInjector,
|
|
1186
1890
|
INVALID_TOKEN_KINDS,
|
|
1187
1891
|
KindeTestkit,
|
|
1188
1892
|
ScenarioBuilder,
|
|
1189
1893
|
TestkitError,
|
|
1894
|
+
WEBHOOK_EVENT_TYPES,
|
|
1895
|
+
WebhookDispatcher,
|
|
1190
1896
|
createKindeOrganization,
|
|
1191
1897
|
createKindeToken,
|
|
1192
1898
|
createKindeUser,
|
|
1193
1899
|
createMembership,
|
|
1194
1900
|
getDefaultTestkit,
|
|
1901
|
+
inspectToken,
|
|
1195
1902
|
isAuthenticated,
|
|
1903
|
+
parseEnvFile,
|
|
1196
1904
|
principalFromClaims,
|
|
1197
1905
|
resetFactories,
|
|
1198
1906
|
resolveSeed,
|
|
1907
|
+
runDoctor,
|
|
1199
1908
|
scenario,
|
|
1200
1909
|
seedScenario,
|
|
1201
1910
|
startKindeTestkit,
|