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.cjs
CHANGED
|
@@ -20,23 +20,31 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var src_exports = {};
|
|
22
22
|
__export(src_exports, {
|
|
23
|
+
BILLING_EVENT_TYPES: () => BILLING_EVENT_TYPES,
|
|
23
24
|
DEFAULT_AUTH_METHODS: () => DEFAULT_AUTH_METHODS,
|
|
24
25
|
DEFAULT_CLIENT_ID: () => DEFAULT_CLIENT_ID,
|
|
25
26
|
DEFAULT_ISSUER: () => DEFAULT_ISSUER,
|
|
27
|
+
DEFAULT_M2M_CLIENT_ID: () => DEFAULT_M2M_CLIENT_ID,
|
|
26
28
|
DEFAULT_SCOPES: () => DEFAULT_SCOPES,
|
|
29
|
+
FailureInjector: () => FailureInjector,
|
|
27
30
|
INVALID_TOKEN_KINDS: () => INVALID_TOKEN_KINDS,
|
|
28
31
|
KindeTestkit: () => KindeTestkit,
|
|
29
32
|
ScenarioBuilder: () => ScenarioBuilder,
|
|
30
33
|
TestkitError: () => TestkitError,
|
|
34
|
+
WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
|
|
35
|
+
WebhookDispatcher: () => WebhookDispatcher,
|
|
31
36
|
createKindeOrganization: () => createKindeOrganization,
|
|
32
37
|
createKindeToken: () => createKindeToken,
|
|
33
38
|
createKindeUser: () => createKindeUser,
|
|
34
39
|
createMembership: () => createMembership,
|
|
35
40
|
getDefaultTestkit: () => getDefaultTestkit,
|
|
41
|
+
inspectToken: () => inspectToken,
|
|
36
42
|
isAuthenticated: () => isAuthenticated,
|
|
43
|
+
parseEnvFile: () => parseEnvFile,
|
|
37
44
|
principalFromClaims: () => principalFromClaims,
|
|
38
45
|
resetFactories: () => resetFactories,
|
|
39
46
|
resolveSeed: () => resolveSeed,
|
|
47
|
+
runDoctor: () => runDoctor,
|
|
40
48
|
scenario: () => scenario,
|
|
41
49
|
seedScenario: () => seedScenario,
|
|
42
50
|
startKindeTestkit: () => startKindeTestkit,
|
|
@@ -210,6 +218,7 @@ function invalid(value) {
|
|
|
210
218
|
// src/testkit.ts
|
|
211
219
|
var DEFAULT_ISSUER = "http://localhost:4400";
|
|
212
220
|
var DEFAULT_CLIENT_ID = "kinde_testkit_client";
|
|
221
|
+
var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
|
|
213
222
|
var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
|
|
214
223
|
var DEFAULT_AUTH_METHODS = ["email"];
|
|
215
224
|
var INVALID_TOKEN_KINDS = [
|
|
@@ -288,6 +297,27 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
288
297
|
Object.assign(payload, options.claims ?? {});
|
|
289
298
|
return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
|
|
290
299
|
}
|
|
300
|
+
async m2mToken(options = {}) {
|
|
301
|
+
const now = this.clock();
|
|
302
|
+
const requested = [...options.scopes ?? []];
|
|
303
|
+
const granted = [...options.grantedScopes ?? requested];
|
|
304
|
+
const payload = {
|
|
305
|
+
aud: [...options.audience ?? this.audience],
|
|
306
|
+
azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
|
|
307
|
+
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
308
|
+
gty: ["client_credentials"],
|
|
309
|
+
iat: now,
|
|
310
|
+
iss: this.issuer,
|
|
311
|
+
jti: (0, import_node_crypto2.randomUUID)(),
|
|
312
|
+
scope: granted.join(" "),
|
|
313
|
+
scp: requested,
|
|
314
|
+
v: "2"
|
|
315
|
+
};
|
|
316
|
+
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
317
|
+
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
318
|
+
Object.assign(payload, options.claims ?? {});
|
|
319
|
+
return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
|
|
320
|
+
}
|
|
291
321
|
async tokenFor(scenario2, overrides = {}) {
|
|
292
322
|
if (scenario2.kind === "unauthenticated") return null;
|
|
293
323
|
return this.token({
|
|
@@ -341,6 +371,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
341
371
|
if (scenario2.kind === "unauthenticated") return null;
|
|
342
372
|
return scenarioPrincipal(scenario2, this.issuer);
|
|
343
373
|
}
|
|
374
|
+
async signPayload(payload, invalid2) {
|
|
375
|
+
return this.sign(payload, invalid2);
|
|
376
|
+
}
|
|
344
377
|
async sign(payload, invalid2) {
|
|
345
378
|
if (invalid2 === "unsigned") {
|
|
346
379
|
const header = import_jose.base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
@@ -360,8 +393,10 @@ function principalFromClaims(claims) {
|
|
|
360
393
|
(role) => typeof role === "string" ? role : String(role.key ?? "")
|
|
361
394
|
) : [];
|
|
362
395
|
const permissions = Array.isArray(claims.permissions) ? claims.permissions.map(String) : [];
|
|
396
|
+
const machine = Array.isArray(claims.gty) && claims.gty.includes("client_credentials");
|
|
363
397
|
return {
|
|
364
|
-
|
|
398
|
+
type: machine ? "machine" : "user",
|
|
399
|
+
subject: String((machine ? claims.azp : claims.sub) ?? ""),
|
|
365
400
|
issuer: String(claims.iss ?? ""),
|
|
366
401
|
organization: typeof claims.org_code === "string" ? { code: claims.org_code } : null,
|
|
367
402
|
roles: roles.filter(Boolean),
|
|
@@ -371,6 +406,7 @@ function principalFromClaims(claims) {
|
|
|
371
406
|
}
|
|
372
407
|
function scenarioPrincipal(scenario2, issuer) {
|
|
373
408
|
return {
|
|
409
|
+
type: "user",
|
|
374
410
|
subject: scenario2.user.id,
|
|
375
411
|
issuer,
|
|
376
412
|
organization: scenario2.organization ? { code: scenario2.organization.code } : null,
|
|
@@ -461,6 +497,20 @@ function resolveSeed(input) {
|
|
|
461
497
|
const rawUsers = listOf(input.users, "users", problems);
|
|
462
498
|
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
463
499
|
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
500
|
+
const rawApplications = listOf(input.applications, "applications", problems);
|
|
501
|
+
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
502
|
+
const webhooks = [];
|
|
503
|
+
rawWebhooks.forEach((raw, index) => {
|
|
504
|
+
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
505
|
+
problems.push(`webhooks[${index}] needs an http or https "url".`);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
|
|
509
|
+
problems.push(`webhooks[${index}].events must be a list of event type names.`);
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
webhooks.push({ url: raw.url, events: raw.events });
|
|
513
|
+
});
|
|
464
514
|
const users = [];
|
|
465
515
|
rawUsers.forEach((raw, index) => {
|
|
466
516
|
if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
|
|
@@ -516,10 +566,43 @@ function resolveSeed(input) {
|
|
|
516
566
|
})
|
|
517
567
|
);
|
|
518
568
|
});
|
|
569
|
+
const applications = [];
|
|
570
|
+
rawApplications.forEach((raw, index) => {
|
|
571
|
+
if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
|
|
572
|
+
problems.push(`applications[${index}] needs a string "clientId".`);
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
if (applications.some((app) => app.clientId === raw.clientId)) {
|
|
576
|
+
problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
|
|
580
|
+
problems.push(`applications[${index}].clientSecret must be a string.`);
|
|
581
|
+
}
|
|
582
|
+
if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
|
|
583
|
+
problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
|
|
584
|
+
}
|
|
585
|
+
for (const field of ["scopes", "permissions"]) {
|
|
586
|
+
const value = raw[field];
|
|
587
|
+
if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
|
|
588
|
+
problems.push(`applications[${index}].${field} must be a list of strings.`);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
const audience = raw.audience;
|
|
592
|
+
applications.push({
|
|
593
|
+
clientId: raw.clientId,
|
|
594
|
+
clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
|
|
595
|
+
name: typeof raw.name === "string" ? raw.name : raw.clientId,
|
|
596
|
+
organizationCode: typeof raw.organization === "string" ? raw.organization : null,
|
|
597
|
+
scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
|
|
598
|
+
permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
|
|
599
|
+
audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
|
|
600
|
+
});
|
|
601
|
+
});
|
|
519
602
|
if (problems.length > 0) {
|
|
520
603
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
521
604
|
}
|
|
522
|
-
return { users, organizations, memberships };
|
|
605
|
+
return { users, organizations, memberships, applications, webhooks };
|
|
523
606
|
}
|
|
524
607
|
function findUser(users, ref) {
|
|
525
608
|
const needle = ref.toLowerCase();
|
|
@@ -656,12 +739,14 @@ var OAuthError = class extends Error {
|
|
|
656
739
|
error;
|
|
657
740
|
};
|
|
658
741
|
var AuthorizationServer = class {
|
|
659
|
-
constructor(testkit, seed) {
|
|
742
|
+
constructor(testkit, seed, emit = () => void 0) {
|
|
660
743
|
this.testkit = testkit;
|
|
661
744
|
this.seed = seed;
|
|
745
|
+
this.emit = emit;
|
|
662
746
|
}
|
|
663
747
|
testkit;
|
|
664
748
|
seed;
|
|
749
|
+
emit;
|
|
665
750
|
codes = /* @__PURE__ */ new Map();
|
|
666
751
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
667
752
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -779,6 +864,7 @@ var AuthorizationServer = class {
|
|
|
779
864
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
780
865
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
781
866
|
});
|
|
867
|
+
this.emit("user.authenticated", user);
|
|
782
868
|
const target = new URL(request.redirectUri);
|
|
783
869
|
target.searchParams.set("code", code);
|
|
784
870
|
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
@@ -788,13 +874,16 @@ var AuthorizationServer = class {
|
|
|
788
874
|
try {
|
|
789
875
|
const clientId = clientIdFrom(req, form);
|
|
790
876
|
const grantType = form.grant_type;
|
|
877
|
+
if (grantType === "client_credentials") {
|
|
878
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
|
|
879
|
+
}
|
|
791
880
|
let grant;
|
|
792
881
|
if (grantType === "authorization_code") {
|
|
793
882
|
grant = this.redeemCode(form, clientId);
|
|
794
883
|
} else if (grantType === "refresh_token") {
|
|
795
884
|
grant = this.redeemRefreshToken(form, clientId);
|
|
796
885
|
} else {
|
|
797
|
-
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and
|
|
886
|
+
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
798
887
|
}
|
|
799
888
|
sendJson(res, 200, await this.issueTokens(grant));
|
|
800
889
|
} catch (error) {
|
|
@@ -804,6 +893,33 @@ var AuthorizationServer = class {
|
|
|
804
893
|
throw error;
|
|
805
894
|
}
|
|
806
895
|
}
|
|
896
|
+
async clientCredentials(clientId, clientSecret, form) {
|
|
897
|
+
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
898
|
+
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
899
|
+
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
900
|
+
}
|
|
901
|
+
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
902
|
+
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
903
|
+
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
904
|
+
return {
|
|
905
|
+
access_token: await this.testkit.m2mToken({
|
|
906
|
+
clientId,
|
|
907
|
+
organizationCode: app?.organizationCode ?? null,
|
|
908
|
+
scopes: requested,
|
|
909
|
+
grantedScopes: granted,
|
|
910
|
+
audience: audience.length > 0 ? audience : app?.audience ?? void 0,
|
|
911
|
+
permissions: app?.permissions ?? void 0
|
|
912
|
+
}),
|
|
913
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
914
|
+
scope: granted.join(" "),
|
|
915
|
+
token_type: "bearer"
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
reset() {
|
|
919
|
+
this.codes.clear();
|
|
920
|
+
this.refreshTokens.clear();
|
|
921
|
+
this.signedUpUsers.clear();
|
|
922
|
+
}
|
|
807
923
|
redeemCode(form, clientId) {
|
|
808
924
|
const code = form.code ?? "";
|
|
809
925
|
const pending = this.codes.get(code);
|
|
@@ -914,8 +1030,11 @@ var AuthorizationServer = class {
|
|
|
914
1030
|
if (seeded) return seeded;
|
|
915
1031
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
916
1032
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
917
|
-
this.signedUpUsers.
|
|
918
|
-
|
|
1033
|
+
if (!this.signedUpUsers.has(user.id)) {
|
|
1034
|
+
this.signedUpUsers.set(user.id, user);
|
|
1035
|
+
this.emit("user.created", user);
|
|
1036
|
+
}
|
|
1037
|
+
return this.signedUpUsers.get(user.id);
|
|
919
1038
|
}
|
|
920
1039
|
organization(code) {
|
|
921
1040
|
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
@@ -975,6 +1094,15 @@ function clientIdFrom(req, form) {
|
|
|
975
1094
|
if (form.client_id) return form.client_id;
|
|
976
1095
|
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
977
1096
|
}
|
|
1097
|
+
function clientSecretFrom(req, form) {
|
|
1098
|
+
const header = req.headers.authorization ?? "";
|
|
1099
|
+
if (header.startsWith("Basic ")) {
|
|
1100
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1101
|
+
const index = decoded.indexOf(":");
|
|
1102
|
+
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1103
|
+
}
|
|
1104
|
+
return form.client_secret ?? null;
|
|
1105
|
+
}
|
|
978
1106
|
function redirectWithError(res, request, error, description) {
|
|
979
1107
|
const target = new URL(request.redirectUri);
|
|
980
1108
|
target.searchParams.set("error", error);
|
|
@@ -1015,6 +1143,351 @@ function sendJson(res, status, body) {
|
|
|
1015
1143
|
res.end(JSON.stringify(body));
|
|
1016
1144
|
}
|
|
1017
1145
|
|
|
1146
|
+
// src/failures.ts
|
|
1147
|
+
var MAX_DELAY_MS = 6e4;
|
|
1148
|
+
var FailureInjector = class {
|
|
1149
|
+
rules = [];
|
|
1150
|
+
nextId = 1;
|
|
1151
|
+
add(rule) {
|
|
1152
|
+
const problems = validate(rule);
|
|
1153
|
+
if (problems.length > 0) {
|
|
1154
|
+
throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
|
|
1155
|
+
}
|
|
1156
|
+
const active = {
|
|
1157
|
+
id: `failure_${this.nextId++}`,
|
|
1158
|
+
path: rule.path,
|
|
1159
|
+
method: rule.method ? rule.method.toUpperCase() : null,
|
|
1160
|
+
status: rule.status ?? null,
|
|
1161
|
+
delayMs: rule.delayMs ?? 0,
|
|
1162
|
+
hang: rule.hang ?? false,
|
|
1163
|
+
remaining: rule.times ?? null,
|
|
1164
|
+
retryAfter: rule.retryAfter ?? 1,
|
|
1165
|
+
hits: 0
|
|
1166
|
+
};
|
|
1167
|
+
this.rules.push(active);
|
|
1168
|
+
return { ...active };
|
|
1169
|
+
}
|
|
1170
|
+
remove(id) {
|
|
1171
|
+
const before = this.rules.length;
|
|
1172
|
+
this.rules = this.rules.filter((rule) => rule.id !== id);
|
|
1173
|
+
return this.rules.length < before;
|
|
1174
|
+
}
|
|
1175
|
+
clear() {
|
|
1176
|
+
this.rules = [];
|
|
1177
|
+
}
|
|
1178
|
+
list() {
|
|
1179
|
+
return this.rules.map((rule) => ({ ...rule }));
|
|
1180
|
+
}
|
|
1181
|
+
take(method, path) {
|
|
1182
|
+
const rule = this.rules.find((r) => matches(r, method, path));
|
|
1183
|
+
if (!rule) return null;
|
|
1184
|
+
rule.hits += 1;
|
|
1185
|
+
if (rule.remaining !== null) {
|
|
1186
|
+
rule.remaining -= 1;
|
|
1187
|
+
if (rule.remaining <= 0) this.remove(rule.id);
|
|
1188
|
+
}
|
|
1189
|
+
return { ...rule };
|
|
1190
|
+
}
|
|
1191
|
+
};
|
|
1192
|
+
function failureBody(status) {
|
|
1193
|
+
const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
|
|
1194
|
+
return { error, error_description: `kinde-testkit injected a ${status} response.` };
|
|
1195
|
+
}
|
|
1196
|
+
function matches(rule, method, path) {
|
|
1197
|
+
if (rule.method && rule.method !== method.toUpperCase()) return false;
|
|
1198
|
+
if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
|
|
1199
|
+
return rule.path === path;
|
|
1200
|
+
}
|
|
1201
|
+
function validate(rule) {
|
|
1202
|
+
const problems = [];
|
|
1203
|
+
if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
|
|
1204
|
+
problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
|
|
1205
|
+
} else if (rule.path.startsWith("/testkit/")) {
|
|
1206
|
+
problems.push("Failures cannot target /testkit/ control endpoints.");
|
|
1207
|
+
}
|
|
1208
|
+
if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
|
|
1209
|
+
problems.push('"status" must be an HTTP error status between 400 and 599.');
|
|
1210
|
+
}
|
|
1211
|
+
if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
|
|
1212
|
+
problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
|
|
1213
|
+
}
|
|
1214
|
+
if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
|
|
1215
|
+
problems.push('"times" must be a whole number of 1 or more.');
|
|
1216
|
+
}
|
|
1217
|
+
if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
|
|
1218
|
+
problems.push('"retryAfter" must be a whole number of seconds.');
|
|
1219
|
+
}
|
|
1220
|
+
if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
|
|
1221
|
+
problems.push('Set at least one of "status", "delayMs" or "hang".');
|
|
1222
|
+
}
|
|
1223
|
+
return problems;
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
// src/webhooks.ts
|
|
1227
|
+
var import_node_crypto4 = require("crypto");
|
|
1228
|
+
var WEBHOOK_EVENT_TYPES = [
|
|
1229
|
+
"user.created",
|
|
1230
|
+
"user.updated",
|
|
1231
|
+
"user.deleted",
|
|
1232
|
+
"user.authenticated",
|
|
1233
|
+
"user.authentication_failed",
|
|
1234
|
+
"organization.created",
|
|
1235
|
+
"organization.updated",
|
|
1236
|
+
"organization.deleted",
|
|
1237
|
+
"role.created",
|
|
1238
|
+
"role.updated",
|
|
1239
|
+
"role.deleted",
|
|
1240
|
+
"permission.created",
|
|
1241
|
+
"permission.updated",
|
|
1242
|
+
"permission.deleted",
|
|
1243
|
+
"subscriber.created",
|
|
1244
|
+
"access_request.created"
|
|
1245
|
+
];
|
|
1246
|
+
var BILLING_EVENT_TYPES = [
|
|
1247
|
+
"customer.agreement_cancelled",
|
|
1248
|
+
"customer.agreement_created",
|
|
1249
|
+
"customer.invoice_overdue",
|
|
1250
|
+
"customer.meter_usage_updated",
|
|
1251
|
+
"customer.payment_failed",
|
|
1252
|
+
"customer.payment_succeeded",
|
|
1253
|
+
"customer.plan_assigned",
|
|
1254
|
+
"customer.plan_changed"
|
|
1255
|
+
];
|
|
1256
|
+
var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
|
|
1257
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
1258
|
+
var MAX_DUPLICATES = 10;
|
|
1259
|
+
var WebhookDispatcher = class {
|
|
1260
|
+
constructor(testkit, seed, endpoints = [], options = {}) {
|
|
1261
|
+
this.testkit = testkit;
|
|
1262
|
+
this.seed = seed;
|
|
1263
|
+
this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
1264
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1265
|
+
for (const endpoint of endpoints) this.addEndpoint(endpoint);
|
|
1266
|
+
this.seededEndpoints = [...this.endpoints];
|
|
1267
|
+
}
|
|
1268
|
+
testkit;
|
|
1269
|
+
seed;
|
|
1270
|
+
endpoints = [];
|
|
1271
|
+
seededEndpoints = [];
|
|
1272
|
+
log = [];
|
|
1273
|
+
nextEndpoint = 1;
|
|
1274
|
+
retryDelaysMs;
|
|
1275
|
+
timeoutMs;
|
|
1276
|
+
addEndpoint(input) {
|
|
1277
|
+
if (!isHttpUrl2(input.url)) {
|
|
1278
|
+
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
1279
|
+
}
|
|
1280
|
+
if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
|
|
1281
|
+
throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
|
|
1282
|
+
}
|
|
1283
|
+
const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
|
|
1284
|
+
this.endpoints.push(endpoint);
|
|
1285
|
+
return { ...endpoint };
|
|
1286
|
+
}
|
|
1287
|
+
removeEndpoint(id) {
|
|
1288
|
+
const before = this.endpoints.length;
|
|
1289
|
+
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
1290
|
+
return this.endpoints.length < before;
|
|
1291
|
+
}
|
|
1292
|
+
listEndpoints() {
|
|
1293
|
+
return this.endpoints.map((e) => ({ ...e }));
|
|
1294
|
+
}
|
|
1295
|
+
deliveries() {
|
|
1296
|
+
return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
|
|
1297
|
+
}
|
|
1298
|
+
reset() {
|
|
1299
|
+
this.log = [];
|
|
1300
|
+
this.endpoints = [...this.seededEndpoints];
|
|
1301
|
+
}
|
|
1302
|
+
buildEvent(options) {
|
|
1303
|
+
if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
|
|
1304
|
+
throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
|
|
1305
|
+
}
|
|
1306
|
+
const now = /* @__PURE__ */ new Date();
|
|
1307
|
+
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1308
|
+
const event = {
|
|
1309
|
+
data: options.data ?? this.buildData(options),
|
|
1310
|
+
event_id: `event_${(0, import_node_crypto4.randomBytes)(16).toString("hex")}`,
|
|
1311
|
+
event_timestamp: timestamp,
|
|
1312
|
+
source: options.source ?? "admin",
|
|
1313
|
+
timestamp,
|
|
1314
|
+
type: options.type
|
|
1315
|
+
};
|
|
1316
|
+
if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
|
|
1317
|
+
event.ip_address = options.ipAddress ?? "127.0.0.1";
|
|
1318
|
+
}
|
|
1319
|
+
return event;
|
|
1320
|
+
}
|
|
1321
|
+
async send(options) {
|
|
1322
|
+
const event = this.buildEvent(options);
|
|
1323
|
+
const copies = options.duplicate ?? 1;
|
|
1324
|
+
if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
|
|
1325
|
+
throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
|
|
1326
|
+
}
|
|
1327
|
+
const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
|
|
1328
|
+
if (options.to && !isHttpUrl2(options.to)) {
|
|
1329
|
+
throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
|
|
1330
|
+
}
|
|
1331
|
+
if (targets.length === 0) {
|
|
1332
|
+
throw new TestkitError(
|
|
1333
|
+
"INVALID_REQUEST",
|
|
1334
|
+
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
1335
|
+
);
|
|
1336
|
+
}
|
|
1337
|
+
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
1338
|
+
const signed = await this.testkit.signPayload(
|
|
1339
|
+
event,
|
|
1340
|
+
options.invalid === "stale" ? void 0 : options.invalid
|
|
1341
|
+
);
|
|
1342
|
+
const jobs = targets.flatMap((target) => {
|
|
1343
|
+
const webhookId = `wh_${(0, import_node_crypto4.randomBytes)(12).toString("hex")}`;
|
|
1344
|
+
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1345
|
+
});
|
|
1346
|
+
return Promise.all(jobs);
|
|
1347
|
+
}
|
|
1348
|
+
async deliver(url, webhookId, body, event, copy) {
|
|
1349
|
+
const delivery = {
|
|
1350
|
+
webhookId,
|
|
1351
|
+
eventId: String(event.event_id),
|
|
1352
|
+
type: String(event.type),
|
|
1353
|
+
url,
|
|
1354
|
+
copy,
|
|
1355
|
+
delivered: false,
|
|
1356
|
+
attempts: [],
|
|
1357
|
+
payload: event
|
|
1358
|
+
};
|
|
1359
|
+
this.log.push(delivery);
|
|
1360
|
+
for (const [index, delay] of this.retryDelaysMs.entries()) {
|
|
1361
|
+
if (delay > 0) await sleep(delay);
|
|
1362
|
+
const started = Date.now();
|
|
1363
|
+
try {
|
|
1364
|
+
const response = await fetch(url, {
|
|
1365
|
+
method: "POST",
|
|
1366
|
+
headers: { "content-type": "application/jwt", "webhook-id": webhookId },
|
|
1367
|
+
body,
|
|
1368
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
1369
|
+
});
|
|
1370
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
1371
|
+
delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
|
|
1372
|
+
if (response.status === 200) {
|
|
1373
|
+
delivery.delivered = true;
|
|
1374
|
+
break;
|
|
1375
|
+
}
|
|
1376
|
+
} catch (error) {
|
|
1377
|
+
const name = error.name;
|
|
1378
|
+
delivery.attempts.push({
|
|
1379
|
+
attempt: index + 1,
|
|
1380
|
+
status: null,
|
|
1381
|
+
error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
|
|
1382
|
+
durationMs: Date.now() - started
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
return { ...delivery, attempts: [...delivery.attempts] };
|
|
1387
|
+
}
|
|
1388
|
+
buildData(options) {
|
|
1389
|
+
const [subject] = options.type.split(".");
|
|
1390
|
+
switch (subject) {
|
|
1391
|
+
case "user":
|
|
1392
|
+
return { user: this.userData(options) };
|
|
1393
|
+
case "organization":
|
|
1394
|
+
return { organization: this.organizationData(options) };
|
|
1395
|
+
case "role":
|
|
1396
|
+
return { role: this.namedData(options, "role") };
|
|
1397
|
+
case "permission":
|
|
1398
|
+
return { permission: this.namedData(options, "permission") };
|
|
1399
|
+
case "subscriber": {
|
|
1400
|
+
const user = this.requireUser(options);
|
|
1401
|
+
return {
|
|
1402
|
+
subscriber: {
|
|
1403
|
+
email: user.email,
|
|
1404
|
+
first_name: user.givenName,
|
|
1405
|
+
id: stableId("sub", user.id),
|
|
1406
|
+
last_name: user.familyName,
|
|
1407
|
+
user_id: user.id
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
case "access_request": {
|
|
1412
|
+
const user = this.requireUser(options);
|
|
1413
|
+
return {
|
|
1414
|
+
access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
default:
|
|
1418
|
+
throw new TestkitError(
|
|
1419
|
+
"INVALID_REQUEST",
|
|
1420
|
+
`kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
|
|
1421
|
+
);
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
emitForUser(type, user) {
|
|
1425
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1426
|
+
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
1427
|
+
void this.send({ type, data, source: "user" }).catch(() => void 0);
|
|
1428
|
+
}
|
|
1429
|
+
userData(options) {
|
|
1430
|
+
const user = this.requireUser(options);
|
|
1431
|
+
if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
|
|
1432
|
+
return this.userPayload(user);
|
|
1433
|
+
}
|
|
1434
|
+
userPayload(user) {
|
|
1435
|
+
return {
|
|
1436
|
+
email: user.email,
|
|
1437
|
+
first_name: user.givenName,
|
|
1438
|
+
id: user.id,
|
|
1439
|
+
is_password_reset_requested: false,
|
|
1440
|
+
is_suspended: false,
|
|
1441
|
+
last_name: user.familyName,
|
|
1442
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
|
|
1443
|
+
code: m.organizationCode,
|
|
1444
|
+
permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
|
|
1445
|
+
roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
|
|
1446
|
+
})),
|
|
1447
|
+
phone: null,
|
|
1448
|
+
username: typeof user.claims.username === "string" ? user.claims.username : null
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1451
|
+
organizationData(options) {
|
|
1452
|
+
if (!options.organization) {
|
|
1453
|
+
throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
|
|
1454
|
+
}
|
|
1455
|
+
const org = this.seed.organizations.find((o) => o.code === options.organization);
|
|
1456
|
+
if (options.type === "organization.deleted") return { code: options.organization };
|
|
1457
|
+
const name = org?.name ?? titleCase(options.organization);
|
|
1458
|
+
const data = { code: options.organization, external_id: null, handle: slug(name), name };
|
|
1459
|
+
if (options.type === "organization.updated") data.is_allow_registrations = false;
|
|
1460
|
+
return data;
|
|
1461
|
+
}
|
|
1462
|
+
namedData(options, kind) {
|
|
1463
|
+
const key = kind === "role" ? options.role : options.permission;
|
|
1464
|
+
if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
|
|
1465
|
+
const id = stableId(kind === "role" ? "role" : "perm", key);
|
|
1466
|
+
if (options.type.endsWith(".deleted")) return { id };
|
|
1467
|
+
const data = { description: "", id, key, name: titleCase(key) };
|
|
1468
|
+
if (kind === "role") data.is_default_role = false;
|
|
1469
|
+
return data;
|
|
1470
|
+
}
|
|
1471
|
+
requireUser(options) {
|
|
1472
|
+
if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
|
|
1473
|
+
const user = findUser(this.seed.users, options.user);
|
|
1474
|
+
if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
|
|
1475
|
+
return user;
|
|
1476
|
+
}
|
|
1477
|
+
};
|
|
1478
|
+
function isHttpUrl2(value) {
|
|
1479
|
+
if (typeof value !== "string") return false;
|
|
1480
|
+
try {
|
|
1481
|
+
const { protocol } = new URL(value);
|
|
1482
|
+
return protocol === "http:" || protocol === "https:";
|
|
1483
|
+
} catch {
|
|
1484
|
+
return false;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
function sleep(ms) {
|
|
1488
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1018
1491
|
// src/server.ts
|
|
1019
1492
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
1020
1493
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
@@ -1028,12 +1501,11 @@ async function startKindeTestkit(options = {}) {
|
|
|
1028
1501
|
);
|
|
1029
1502
|
}
|
|
1030
1503
|
const seed = resolveSeed(options.seed ?? {});
|
|
1504
|
+
const failures = new FailureInjector();
|
|
1031
1505
|
let ready;
|
|
1032
|
-
const testkitReady = new Promise(
|
|
1033
|
-
(resolve) => ready = resolve
|
|
1034
|
-
);
|
|
1506
|
+
const testkitReady = new Promise((resolve) => ready = resolve);
|
|
1035
1507
|
const server = (0, import_node_http.createServer)((req, res) => {
|
|
1036
|
-
testkitReady.then((
|
|
1508
|
+
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1037
1509
|
});
|
|
1038
1510
|
await new Promise((resolve, reject) => {
|
|
1039
1511
|
server.once("error", reject);
|
|
@@ -1047,7 +1519,14 @@ async function startKindeTestkit(options = {}) {
|
|
|
1047
1519
|
audience: options.audience ?? options.seed?.audience,
|
|
1048
1520
|
clientId: options.clientId ?? options.seed?.clientId
|
|
1049
1521
|
});
|
|
1050
|
-
|
|
1522
|
+
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
1523
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user));
|
|
1524
|
+
const reset = () => {
|
|
1525
|
+
auth.reset();
|
|
1526
|
+
failures.clear();
|
|
1527
|
+
webhooks.reset();
|
|
1528
|
+
};
|
|
1529
|
+
ready({ testkit, auth, seed, failures, webhooks, reset });
|
|
1051
1530
|
return {
|
|
1052
1531
|
url,
|
|
1053
1532
|
issuer: testkit.issuer,
|
|
@@ -1055,16 +1534,32 @@ async function startKindeTestkit(options = {}) {
|
|
|
1055
1534
|
jwksUri: `${url}/.well-known/jwks`,
|
|
1056
1535
|
testkit,
|
|
1057
1536
|
seed,
|
|
1537
|
+
failures,
|
|
1538
|
+
webhooks,
|
|
1539
|
+
reset,
|
|
1058
1540
|
close: () => new Promise((resolve, reject) => {
|
|
1059
1541
|
server.closeAllConnections();
|
|
1060
1542
|
server.close((error) => error ? reject(error) : resolve());
|
|
1061
1543
|
})
|
|
1062
1544
|
};
|
|
1063
1545
|
}
|
|
1064
|
-
async function handle(req, res,
|
|
1546
|
+
async function handle(req, res, context) {
|
|
1547
|
+
const { testkit, auth, seed, failures, webhooks } = context;
|
|
1065
1548
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1066
1549
|
const { pathname } = url;
|
|
1067
1550
|
const method = req.method ?? "GET";
|
|
1551
|
+
if (!pathname.startsWith("/testkit/")) {
|
|
1552
|
+
const failure = failures.take(method, pathname);
|
|
1553
|
+
if (failure) {
|
|
1554
|
+
if (failure.hang) return;
|
|
1555
|
+
if (failure.delayMs > 0) await new Promise((resolve) => setTimeout(resolve, failure.delayMs));
|
|
1556
|
+
if (failure.status !== null) {
|
|
1557
|
+
const headers = {};
|
|
1558
|
+
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1559
|
+
return sendJson2(res, failure.status, failureBody(failure.status), headers);
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1068
1563
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
1069
1564
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1070
1565
|
return sendJson2(res, 200, discovery(testkit));
|
|
@@ -1082,6 +1577,37 @@ async function handle(req, res, testkit, auth, seed) {
|
|
|
1082
1577
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1083
1578
|
return sendJson2(res, 200, seed.memberships);
|
|
1084
1579
|
}
|
|
1580
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson2(res, 200, failures.list());
|
|
1581
|
+
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1582
|
+
return sendJson2(res, 201, failures.add(await readJson(req)));
|
|
1583
|
+
}
|
|
1584
|
+
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1585
|
+
failures.clear();
|
|
1586
|
+
return sendJson2(res, 200, { ok: true });
|
|
1587
|
+
}
|
|
1588
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1589
|
+
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1590
|
+
return sendJson2(res, removed ? 200 : 404, { ok: removed });
|
|
1591
|
+
}
|
|
1592
|
+
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1593
|
+
return sendJson2(res, 200, await webhooks.send(await readJson(req)));
|
|
1594
|
+
}
|
|
1595
|
+
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1596
|
+
return sendJson2(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1597
|
+
}
|
|
1598
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson2(res, 200, webhooks.deliveries());
|
|
1599
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson2(res, 200, webhooks.listEndpoints());
|
|
1600
|
+
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1601
|
+
return sendJson2(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1602
|
+
}
|
|
1603
|
+
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1604
|
+
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1605
|
+
return sendJson2(res, removed ? 200 : 404, { ok: removed });
|
|
1606
|
+
}
|
|
1607
|
+
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1608
|
+
context.reset();
|
|
1609
|
+
return sendJson2(res, 200, { ok: true });
|
|
1610
|
+
}
|
|
1085
1611
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1086
1612
|
const body = await readJson(req);
|
|
1087
1613
|
const accessToken = await issueToken(testkit, seed, body);
|
|
@@ -1121,6 +1647,21 @@ async function issueToken(testkit, seed, body) {
|
|
|
1121
1647
|
]);
|
|
1122
1648
|
}
|
|
1123
1649
|
const expiresIn = input.expiresIn;
|
|
1650
|
+
if (input.m2m === true) {
|
|
1651
|
+
const clientId = optionalString(input, "clientId");
|
|
1652
|
+
const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
|
|
1653
|
+
const scopes = optionalStrings(input, "scopes") ?? [];
|
|
1654
|
+
return testkit.m2mToken({
|
|
1655
|
+
clientId,
|
|
1656
|
+
organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
|
|
1657
|
+
scopes,
|
|
1658
|
+
grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
|
|
1659
|
+
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
1660
|
+
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
1661
|
+
expiresIn,
|
|
1662
|
+
invalid: invalid2
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1124
1665
|
const permissions = optionalStrings(input, "permissions");
|
|
1125
1666
|
const roles = optionalStrings(input, "roles");
|
|
1126
1667
|
const userRef = optionalString(input, "user");
|
|
@@ -1196,10 +1737,11 @@ async function readText(req) {
|
|
|
1196
1737
|
}
|
|
1197
1738
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1198
1739
|
}
|
|
1199
|
-
function sendJson2(res, status, body) {
|
|
1740
|
+
function sendJson2(res, status, body, headers = {}) {
|
|
1200
1741
|
res.writeHead(status, {
|
|
1201
1742
|
"content-type": "application/json; charset=utf-8",
|
|
1202
|
-
"cache-control": "no-store"
|
|
1743
|
+
"cache-control": "no-store",
|
|
1744
|
+
...headers
|
|
1203
1745
|
});
|
|
1204
1746
|
res.end(JSON.stringify(body));
|
|
1205
1747
|
}
|
|
@@ -1217,25 +1759,200 @@ function sendError(res, error) {
|
|
|
1217
1759
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1218
1760
|
});
|
|
1219
1761
|
}
|
|
1762
|
+
|
|
1763
|
+
// src/inspect.ts
|
|
1764
|
+
var import_jose2 = require("jose");
|
|
1765
|
+
async function inspectToken(token, options = {}) {
|
|
1766
|
+
const checks = [];
|
|
1767
|
+
const trimmed = token.trim();
|
|
1768
|
+
let header = null;
|
|
1769
|
+
let payload = null;
|
|
1770
|
+
if (trimmed.split(".").length !== 3) {
|
|
1771
|
+
checks.push({ name: "Format", status: "fail", detail: "A JWT has three parts separated by dots." });
|
|
1772
|
+
return { kind: "unknown", header, payload, checks };
|
|
1773
|
+
}
|
|
1774
|
+
try {
|
|
1775
|
+
header = (0, import_jose2.decodeProtectedHeader)(trimmed);
|
|
1776
|
+
payload = (0, import_jose2.decodeJwt)(trimmed);
|
|
1777
|
+
} catch {
|
|
1778
|
+
checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
|
|
1779
|
+
return { kind: "unknown", header, payload, checks };
|
|
1780
|
+
}
|
|
1781
|
+
checks.push({ name: "Format", status: "pass", detail: "Three base64url parts with JSON header and payload." });
|
|
1782
|
+
checks.push(
|
|
1783
|
+
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.` }
|
|
1784
|
+
);
|
|
1785
|
+
const signer = typeof header.kid === "string" && header.kid.startsWith("kinde-testkit") ? "kinde-testkit" : "another issuer";
|
|
1786
|
+
checks.push({ name: "Key", status: "pass", detail: `kid ${String(header.kid ?? "missing")} (${signer}).` });
|
|
1787
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
1788
|
+
if (typeof payload.exp !== "number") {
|
|
1789
|
+
checks.push({ name: "Expiry", status: "fail", detail: "No exp claim." });
|
|
1790
|
+
} else if (payload.exp <= now) {
|
|
1791
|
+
checks.push({ name: "Expiry", status: "fail", detail: `Expired ${formatSpan(now - payload.exp)} ago.` });
|
|
1792
|
+
} else {
|
|
1793
|
+
checks.push({ name: "Expiry", status: "pass", detail: `Expires in ${formatSpan(payload.exp - now)}.` });
|
|
1794
|
+
}
|
|
1795
|
+
if (typeof payload.iat === "number" && payload.iat > now + 60) {
|
|
1796
|
+
checks.push({ name: "Issued at", status: "fail", detail: `iat is ${formatSpan(payload.iat - now)} in the future.` });
|
|
1797
|
+
}
|
|
1798
|
+
if (options.issuerUrl) {
|
|
1799
|
+
const issuer = options.issuerUrl.replace(/\/+$/, "");
|
|
1800
|
+
if (payload.iss !== issuer) {
|
|
1801
|
+
checks.push({ name: "Issuer", status: "fail", detail: `iss is ${String(payload.iss)}, not ${issuer}.` });
|
|
1802
|
+
} else {
|
|
1803
|
+
checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
|
|
1804
|
+
}
|
|
1805
|
+
try {
|
|
1806
|
+
await (0, import_jose2.jwtVerify)(trimmed, (0, import_jose2.createRemoteJWKSet)(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
|
|
1807
|
+
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1808
|
+
} catch (error) {
|
|
1809
|
+
const code = error.code ?? "";
|
|
1810
|
+
if (code === "ERR_JWT_EXPIRED" || code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
|
|
1811
|
+
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1812
|
+
} else {
|
|
1813
|
+
checks.push({ name: "Signature", status: "fail", detail: describeVerifyError(code, issuer) });
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
} else {
|
|
1817
|
+
checks.push({ name: "Signature", status: "warn", detail: "Not checked. Pass --url to verify against a running issuer." });
|
|
1818
|
+
}
|
|
1819
|
+
return { kind: kindOf(payload), header, payload, checks };
|
|
1820
|
+
}
|
|
1821
|
+
function kindOf(payload) {
|
|
1822
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) return "m2m";
|
|
1823
|
+
if ("email" in payload || "org_codes" in payload || "at_hash" in payload || "nonce" in payload) return "id";
|
|
1824
|
+
if ("scp" in payload || "permissions" in payload || "org_code" in payload) return "access";
|
|
1825
|
+
return "unknown";
|
|
1826
|
+
}
|
|
1827
|
+
function describeVerifyError(code, issuer) {
|
|
1828
|
+
if (code === "ERR_JWKS_NO_MATCHING_KEY") return `No key in ${issuer}'s JWKS matches this token's kid.`;
|
|
1829
|
+
if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "The signature does not match the token. It was changed after signing.";
|
|
1830
|
+
if (code === "ERR_JOSE_ALG_NOT_ALLOWED" || code === "ERR_JOSE_NOT_SUPPORTED") return "The token is not signed with RS256.";
|
|
1831
|
+
if (code === "ERR_JWKS_TIMEOUT" || code === "ERR_JOSE_GENERIC") return `Could not fetch keys from ${issuer}.`;
|
|
1832
|
+
return `Verification failed (${code || "unknown error"}).`;
|
|
1833
|
+
}
|
|
1834
|
+
function formatSpan(seconds) {
|
|
1835
|
+
const s = Math.max(0, Math.round(seconds));
|
|
1836
|
+
if (s < 60) return `${s}s`;
|
|
1837
|
+
if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
|
|
1838
|
+
if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor(s % 3600 / 60)}m`;
|
|
1839
|
+
return `${Math.floor(s / 86400)}d ${Math.floor(s % 86400 / 3600)}h`;
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
// src/doctor.ts
|
|
1843
|
+
var SECRET_FORMAT = /^[a-zA-Z0-9]{40,60}$/;
|
|
1844
|
+
async function runDoctor(options) {
|
|
1845
|
+
const url = options.url.replace(/\/+$/, "");
|
|
1846
|
+
const checks = [];
|
|
1847
|
+
let issuer = null;
|
|
1848
|
+
try {
|
|
1849
|
+
const health = await (await fetch(`${url}/testkit/health`)).json();
|
|
1850
|
+
issuer = health.issuer ?? null;
|
|
1851
|
+
checks.push({ name: "Issuer running", status: "pass", detail: `${url} answers, issuer ${issuer}.` });
|
|
1852
|
+
} catch {
|
|
1853
|
+
checks.push({ name: "Issuer running", status: "fail", detail: `Nothing answers at ${url}. Start it with "kinde-testkit start".` });
|
|
1854
|
+
}
|
|
1855
|
+
if (issuer) {
|
|
1856
|
+
try {
|
|
1857
|
+
const discovery2 = await (await fetch(`${url}/.well-known/openid-configuration`)).json();
|
|
1858
|
+
checks.push(
|
|
1859
|
+
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}.` }
|
|
1860
|
+
);
|
|
1861
|
+
} catch {
|
|
1862
|
+
checks.push({ name: "Discovery", status: "fail", detail: "Could not read /.well-known/openid-configuration." });
|
|
1863
|
+
}
|
|
1864
|
+
try {
|
|
1865
|
+
const jwks = await (await fetch(`${url}/.well-known/jwks.json`)).json();
|
|
1866
|
+
const usable = (jwks.keys ?? []).filter((key) => key.kty === "RSA" && key.use === "sig");
|
|
1867
|
+
checks.push(
|
|
1868
|
+
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." }
|
|
1869
|
+
);
|
|
1870
|
+
} catch {
|
|
1871
|
+
checks.push({ name: "JWKS", status: "fail", detail: "Could not read /.well-known/jwks.json." });
|
|
1872
|
+
}
|
|
1873
|
+
try {
|
|
1874
|
+
const users = await (await fetch(`${url}/testkit/users`)).json();
|
|
1875
|
+
checks.push(
|
|
1876
|
+
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." }
|
|
1877
|
+
);
|
|
1878
|
+
} catch {
|
|
1879
|
+
checks.push({ name: "Seed", status: "warn", detail: "Could not read /testkit/users." });
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
const env = options.env;
|
|
1883
|
+
const configured = env.KINDE_ISSUER_URL?.trim().replace(/\/+$/, "");
|
|
1884
|
+
if (!configured) {
|
|
1885
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: "Not set. Set it to the testkit's issuer for test runs." });
|
|
1886
|
+
} else if (/\.kinde\.com$/i.test(new URL(configured, "http://x").hostname)) {
|
|
1887
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} is a real Kinde domain. Tests would sign in against Kinde, not the testkit.` });
|
|
1888
|
+
} else if (issuer && configured !== issuer) {
|
|
1889
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} does not match the testkit issuer ${issuer}. Token checks compare iss exactly.` });
|
|
1890
|
+
} else {
|
|
1891
|
+
checks.push({ name: "KINDE_ISSUER_URL", status: "pass", detail: `${configured}.` });
|
|
1892
|
+
}
|
|
1893
|
+
checks.push(
|
|
1894
|
+
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." }
|
|
1895
|
+
);
|
|
1896
|
+
const secret = env.KINDE_CLIENT_SECRET;
|
|
1897
|
+
if (!secret) {
|
|
1898
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "warn", detail: "Not set. Server-side SDKs, such as the Next.js SDK, need it." });
|
|
1899
|
+
} else if (!SECRET_FORMAT.test(secret)) {
|
|
1900
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "fail", detail: "The Next.js SDK only accepts 40 to 60 letters and digits." });
|
|
1901
|
+
} else {
|
|
1902
|
+
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1903
|
+
}
|
|
1904
|
+
const site = env.KINDE_SITE_URL;
|
|
1905
|
+
if (!site) {
|
|
1906
|
+
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
1907
|
+
} else if (!/^https?:\/\//.test(site)) {
|
|
1908
|
+
checks.push({ name: "KINDE_SITE_URL", status: "fail", detail: `${site} is not an http or https URL.` });
|
|
1909
|
+
} else {
|
|
1910
|
+
checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
|
|
1911
|
+
}
|
|
1912
|
+
return { url, checks, ok: checks.every((check) => check.status !== "fail") };
|
|
1913
|
+
}
|
|
1914
|
+
function parseEnvFile(text) {
|
|
1915
|
+
const values = {};
|
|
1916
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1917
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
1918
|
+
if (!match) continue;
|
|
1919
|
+
let value = match[2];
|
|
1920
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
1921
|
+
value = value.slice(1, -1);
|
|
1922
|
+
} else {
|
|
1923
|
+
value = value.replace(/\s+#.*$/, "");
|
|
1924
|
+
}
|
|
1925
|
+
values[match[1]] = value;
|
|
1926
|
+
}
|
|
1927
|
+
return values;
|
|
1928
|
+
}
|
|
1220
1929
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1221
1930
|
0 && (module.exports = {
|
|
1931
|
+
BILLING_EVENT_TYPES,
|
|
1222
1932
|
DEFAULT_AUTH_METHODS,
|
|
1223
1933
|
DEFAULT_CLIENT_ID,
|
|
1224
1934
|
DEFAULT_ISSUER,
|
|
1935
|
+
DEFAULT_M2M_CLIENT_ID,
|
|
1225
1936
|
DEFAULT_SCOPES,
|
|
1937
|
+
FailureInjector,
|
|
1226
1938
|
INVALID_TOKEN_KINDS,
|
|
1227
1939
|
KindeTestkit,
|
|
1228
1940
|
ScenarioBuilder,
|
|
1229
1941
|
TestkitError,
|
|
1942
|
+
WEBHOOK_EVENT_TYPES,
|
|
1943
|
+
WebhookDispatcher,
|
|
1230
1944
|
createKindeOrganization,
|
|
1231
1945
|
createKindeToken,
|
|
1232
1946
|
createKindeUser,
|
|
1233
1947
|
createMembership,
|
|
1234
1948
|
getDefaultTestkit,
|
|
1949
|
+
inspectToken,
|
|
1235
1950
|
isAuthenticated,
|
|
1951
|
+
parseEnvFile,
|
|
1236
1952
|
principalFromClaims,
|
|
1237
1953
|
resetFactories,
|
|
1238
1954
|
resolveSeed,
|
|
1955
|
+
runDoctor,
|
|
1239
1956
|
scenario,
|
|
1240
1957
|
seedScenario,
|
|
1241
1958
|
startKindeTestkit,
|