kinde-testkit 0.7.1 → 0.8.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 +11 -0
- package/README.md +97 -9
- package/dist/chunk-BPPG4G52.js +427 -0
- package/dist/chunk-BPPG4G52.js.map +1 -0
- package/dist/{chunk-IOP27RQ5.js → chunk-CY75AADD.js} +167 -450
- package/dist/chunk-CY75AADD.js.map +1 -0
- package/dist/chunk-EZUKOKNO.js +48 -0
- package/dist/chunk-EZUKOKNO.js.map +1 -0
- package/dist/{chunk-K5YNZAOM.js → chunk-YJPE5HAM.js} +5 -3
- package/dist/{chunk-K5YNZAOM.js.map → chunk-YJPE5HAM.js.map} +1 -1
- package/dist/cli.js +8 -2
- package/dist/cli.js.map +1 -1
- package/dist/cypress-support.d.ts +45 -1
- package/dist/cypress-support.js +21 -6
- package/dist/cypress-support.js.map +1 -1
- package/dist/cypress.cjs +134 -10
- package/dist/cypress.d.cts +1 -1
- package/dist/cypress.d.ts +3 -2
- package/dist/cypress.js +2 -1
- package/dist/cypress.js.map +1 -1
- package/dist/{handle-QF340J2E.d.cts → handle-DRPxm36j.d.cts} +1 -1
- package/dist/{handle-DxF0uwza.d.ts → handle-Pjt9fSUq.d.ts} +3 -2
- package/dist/index.cjs +137 -10
- package/dist/index.d.cts +17 -4
- package/dist/index.d.ts +8 -26
- package/dist/index.js +27 -51
- package/dist/index.js.map +1 -1
- package/dist/jest.cjs +134 -10
- package/dist/jest.d.cts +3 -3
- package/dist/jest.d.ts +5 -4
- package/dist/jest.js +3 -2
- package/dist/jest.js.map +1 -1
- package/dist/playwright.d.ts +12 -3
- package/dist/playwright.js +30 -0
- package/dist/playwright.js.map +1 -1
- package/dist/react.d.ts +43 -0
- package/dist/react.js +110 -0
- package/dist/react.js.map +1 -0
- package/dist/{server-CcXI3vJ-.d.cts → server-CLRn67qI.d.cts} +24 -0
- package/dist/{server-Dghq0aLx.d.ts → server-CuHAHsaN.d.ts} +3 -58
- package/dist/sign-in-flow-DNrDXSLI.d.ts +35 -0
- package/dist/testkit-BvCAFsSj.d.ts +156 -0
- package/dist/vitest.d.ts +5 -4
- package/dist/vitest.js +3 -2
- package/dist/vitest.js.map +1 -1
- package/dist/{webhooks-DJyCsbdF.d.ts → webhooks-CiK9_pVw.d.ts} +82 -155
- package/package.json +30 -3
- package/dist/chunk-IOP27RQ5.js.map +0 -1
|
@@ -1,410 +1,19 @@
|
|
|
1
|
-
// src/ids.ts
|
|
2
|
-
import { createHash } from "crypto";
|
|
3
|
-
var counters = /* @__PURE__ */ new Map();
|
|
4
|
-
function stableId(prefix, seed) {
|
|
5
|
-
return `${prefix}_${createHash("sha256").update(seed).digest("hex").slice(0, 16)}`;
|
|
6
|
-
}
|
|
7
|
-
function nextSequence(prefix) {
|
|
8
|
-
const next = (counters.get(prefix) ?? 0) + 1;
|
|
9
|
-
counters.set(prefix, next);
|
|
10
|
-
return next;
|
|
11
|
-
}
|
|
12
|
-
function resetSequences() {
|
|
13
|
-
counters.clear();
|
|
14
|
-
}
|
|
15
|
-
function slug(value) {
|
|
16
|
-
return value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
17
|
-
}
|
|
18
|
-
function titleCase(value) {
|
|
19
|
-
return value.replace(/^org_/, "").split(/[_\-\s]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
// src/factories.ts
|
|
23
|
-
function createKindeUser(options = {}) {
|
|
24
|
-
const email = options.email === void 0 ? `user-${nextSequence("user")}@example.test` : options.email;
|
|
25
|
-
const id = options.id ?? (email ? stableId("kp", email) : `kp_test_${nextSequence("kp")}`);
|
|
26
|
-
return {
|
|
27
|
-
id,
|
|
28
|
-
email,
|
|
29
|
-
emailVerified: options.emailVerified ?? email !== null,
|
|
30
|
-
givenName: options.givenName === void 0 ? null : options.givenName,
|
|
31
|
-
familyName: options.familyName === void 0 ? null : options.familyName,
|
|
32
|
-
picture: options.picture === void 0 ? null : options.picture,
|
|
33
|
-
claims: { ...options.claims ?? {} }
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
function createKindeOrganization(options = {}) {
|
|
37
|
-
const code = options.code ?? (options.name ? `org_${slug(options.name)}` : `org_test_${nextSequence("org")}`);
|
|
38
|
-
return {
|
|
39
|
-
code,
|
|
40
|
-
name: options.name ?? titleCase(code),
|
|
41
|
-
metadata: { ...options.metadata ?? {} }
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
function createMembership(options) {
|
|
45
|
-
return {
|
|
46
|
-
userId: options.userId,
|
|
47
|
-
organizationCode: options.organizationCode,
|
|
48
|
-
roles: unique(options.roles ?? []),
|
|
49
|
-
permissions: unique(options.permissions ?? [])
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
function toKindeRole(role) {
|
|
53
|
-
if (typeof role !== "string") return role;
|
|
54
|
-
return { id: stableId("role", role), key: role, name: titleCase(role) };
|
|
55
|
-
}
|
|
56
|
-
function resetFactories() {
|
|
57
|
-
resetSequences();
|
|
58
|
-
}
|
|
59
|
-
function unique(values) {
|
|
60
|
-
return [...new Set(values)];
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// src/errors.ts
|
|
64
|
-
var TestkitError = class extends Error {
|
|
65
|
-
code;
|
|
66
|
-
details;
|
|
67
|
-
/** The message without the details list. */
|
|
68
|
-
summary;
|
|
69
|
-
constructor(code, message, details = []) {
|
|
70
|
-
super(details.length > 0 ? `${message}
|
|
71
|
-
|
|
72
|
-
${details.map((d) => ` - ${d}`).join("\n")}` : message);
|
|
73
|
-
this.name = "TestkitError";
|
|
74
|
-
this.code = code;
|
|
75
|
-
this.details = details;
|
|
76
|
-
this.summary = message;
|
|
77
|
-
}
|
|
78
|
-
toString() {
|
|
79
|
-
return `${this.code}
|
|
80
|
-
|
|
81
|
-
${this.message}`;
|
|
82
|
-
}
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
// src/testkit.ts
|
|
86
|
-
import { randomUUID } from "crypto";
|
|
87
1
|
import {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
if (!Number.isFinite(value) || value < 0) throw invalid(String(value));
|
|
101
|
-
return Math.floor(value);
|
|
102
|
-
}
|
|
103
|
-
const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
|
|
104
|
-
if (!match) {
|
|
105
|
-
if (/^\d+$/.test(value.trim())) return Number(value.trim());
|
|
106
|
-
throw invalid(value);
|
|
107
|
-
}
|
|
108
|
-
return Number(match[1]) * UNITS[match[2]];
|
|
109
|
-
}
|
|
110
|
-
function invalid(value) {
|
|
111
|
-
return new TestkitError(
|
|
112
|
-
"INVALID_DURATION",
|
|
113
|
-
`"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
|
|
114
|
-
);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// src/testkit.ts
|
|
118
|
-
var DEFAULT_ISSUER = "http://localhost:4400";
|
|
119
|
-
var DEFAULT_CLIENT_ID = "kinde_testkit_client";
|
|
120
|
-
var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
|
|
121
|
-
var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
|
|
122
|
-
var DEFAULT_AUTH_METHODS = ["email"];
|
|
123
|
-
var INVALID_TOKEN_KINDS = [
|
|
124
|
-
"expired",
|
|
125
|
-
"wrong-issuer",
|
|
126
|
-
"wrong-audience",
|
|
127
|
-
"missing-subject",
|
|
128
|
-
"missing-organization",
|
|
129
|
-
"missing-permissions",
|
|
130
|
-
"future-iat",
|
|
131
|
-
"bad-signature",
|
|
132
|
-
"unknown-key",
|
|
133
|
-
"unsigned"
|
|
134
|
-
];
|
|
135
|
-
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
136
|
-
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
137
|
-
var KindeTestkit = class _KindeTestkit {
|
|
138
|
-
observers = [];
|
|
139
|
-
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
140
|
-
observe(observer) {
|
|
141
|
-
this.observers.push(observer);
|
|
142
|
-
return () => {
|
|
143
|
-
this.observers = this.observers.filter((o) => o !== observer);
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
async signAccess(payload, invalid2, now) {
|
|
147
|
-
const final = applyInvalidClaims(payload, invalid2, now);
|
|
148
|
-
const token = await this.sign(final, invalid2);
|
|
149
|
-
for (const observer of this.observers) observer.accessToken?.(final, invalid2, token);
|
|
150
|
-
return token;
|
|
151
|
-
}
|
|
152
|
-
issuer;
|
|
153
|
-
audience;
|
|
154
|
-
clientId;
|
|
155
|
-
accessTokenExpiresIn;
|
|
156
|
-
idTokenExpiresIn;
|
|
157
|
-
clock;
|
|
158
|
-
signingKey;
|
|
159
|
-
strangerKey = null;
|
|
160
|
-
static async create(options = {}) {
|
|
161
|
-
return new _KindeTestkit(options, await createSigningKey("kinde-testkit"));
|
|
162
|
-
}
|
|
163
|
-
constructor(options, signingKey) {
|
|
164
|
-
this.issuer = trimSlash(options.issuer ?? DEFAULT_ISSUER);
|
|
165
|
-
this.audience = toArray(options.audience);
|
|
166
|
-
this.clientId = options.clientId ?? DEFAULT_CLIENT_ID;
|
|
167
|
-
this.accessTokenExpiresIn = options.accessTokenExpiresIn ?? "24h";
|
|
168
|
-
this.idTokenExpiresIn = options.idTokenExpiresIn ?? "1h";
|
|
169
|
-
this.clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
170
|
-
this.signingKey = signingKey;
|
|
171
|
-
warnIfRealKindeDomain(this.issuer);
|
|
172
|
-
}
|
|
173
|
-
get jwksUri() {
|
|
174
|
-
return `${this.issuer}/.well-known/jwks`;
|
|
175
|
-
}
|
|
176
|
-
get keyId() {
|
|
177
|
-
return this.signingKey.kid;
|
|
178
|
-
}
|
|
179
|
-
get accessTokenLifetime() {
|
|
180
|
-
return toSeconds(this.accessTokenExpiresIn);
|
|
181
|
-
}
|
|
182
|
-
async verify(token) {
|
|
183
|
-
const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
|
|
184
|
-
issuer: this.issuer,
|
|
185
|
-
algorithms: ["RS256"]
|
|
186
|
-
});
|
|
187
|
-
return payload;
|
|
188
|
-
}
|
|
189
|
-
jwks() {
|
|
190
|
-
return { keys: [{ ...this.signingKey.publicJwk }] };
|
|
191
|
-
}
|
|
192
|
-
async token(options = {}) {
|
|
193
|
-
const now = this.clock();
|
|
194
|
-
const payload = {
|
|
195
|
-
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
196
|
-
aud: [...options.audience ?? this.audience],
|
|
197
|
-
auth_time: options.authTime ?? now,
|
|
198
|
-
azp: options.clientId ?? this.clientId,
|
|
199
|
-
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
200
|
-
iat: now,
|
|
201
|
-
iss: this.issuer,
|
|
202
|
-
jti: randomUUID(),
|
|
203
|
-
scp: [...options.scopes ?? DEFAULT_SCOPES],
|
|
204
|
-
sub: options.subject ?? stableId("kp", "default-test-user")
|
|
205
|
-
};
|
|
206
|
-
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
207
|
-
if (options.roles !== void 0) payload.roles = options.roles.map(toKindeRole);
|
|
208
|
-
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
209
|
-
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
210
|
-
Object.assign(payload, options.claims ?? {});
|
|
211
|
-
return this.signAccess(payload, options.invalid, now);
|
|
212
|
-
}
|
|
213
|
-
async m2mToken(options = {}) {
|
|
214
|
-
const now = this.clock();
|
|
215
|
-
const requested = [...options.scopes ?? []];
|
|
216
|
-
const granted = [...options.grantedScopes ?? requested];
|
|
217
|
-
const payload = {
|
|
218
|
-
aud: [...options.audience ?? this.audience],
|
|
219
|
-
azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
|
|
220
|
-
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
221
|
-
gty: ["client_credentials"],
|
|
222
|
-
iat: now,
|
|
223
|
-
iss: this.issuer,
|
|
224
|
-
jti: randomUUID(),
|
|
225
|
-
scope: granted.join(" "),
|
|
226
|
-
scp: requested,
|
|
227
|
-
v: "2"
|
|
228
|
-
};
|
|
229
|
-
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
230
|
-
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
231
|
-
Object.assign(payload, options.claims ?? {});
|
|
232
|
-
return this.signAccess(payload, options.invalid, now);
|
|
233
|
-
}
|
|
234
|
-
async tokenFor(scenario, overrides = {}) {
|
|
235
|
-
if (scenario.kind === "unauthenticated") {
|
|
236
|
-
for (const observer of this.observers) observer.anonymous?.();
|
|
237
|
-
return null;
|
|
238
|
-
}
|
|
239
|
-
return this.token({
|
|
240
|
-
subject: scenario.user.id,
|
|
241
|
-
organizationCode: scenario.organization?.code ?? null,
|
|
242
|
-
roles: scenario.roles.length > 0 ? scenario.roles : void 0,
|
|
243
|
-
permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
|
|
244
|
-
...overrides,
|
|
245
|
-
claims: { ...scenario.claims, ...overrides.claims ?? {} }
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
async idTokenFor(scenario, options = {}) {
|
|
249
|
-
if (scenario.kind === "unauthenticated") return null;
|
|
250
|
-
const { user, organization } = scenario;
|
|
251
|
-
const now = this.clock();
|
|
252
|
-
const authTime = options.authTime ?? now;
|
|
253
|
-
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
254
|
-
const clientId = options.clientId ?? this.clientId;
|
|
255
|
-
const payload = {
|
|
256
|
-
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
257
|
-
aud: [clientId],
|
|
258
|
-
auth_time: authTime,
|
|
259
|
-
azp: clientId,
|
|
260
|
-
email: user.email,
|
|
261
|
-
email_verified: user.emailVerified,
|
|
262
|
-
exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
|
|
263
|
-
family_name: user.familyName,
|
|
264
|
-
given_name: user.givenName,
|
|
265
|
-
iat: now,
|
|
266
|
-
iss: this.issuer,
|
|
267
|
-
jti: randomUUID(),
|
|
268
|
-
name: name || null,
|
|
269
|
-
nonce: options.nonce,
|
|
270
|
-
org_codes: organization ? [organization.code] : void 0,
|
|
271
|
-
picture: user.picture,
|
|
272
|
-
rat: authTime,
|
|
273
|
-
sub: user.id,
|
|
274
|
-
updated_at: now,
|
|
275
|
-
...user.claims
|
|
276
|
-
};
|
|
277
|
-
for (const key of Object.keys(payload)) {
|
|
278
|
-
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
279
|
-
}
|
|
280
|
-
const token = await this.sign(payload);
|
|
281
|
-
for (const observer of this.observers) observer.idToken?.(payload, token);
|
|
282
|
-
return token;
|
|
283
|
-
}
|
|
284
|
-
async headersFor(scenario, overrides = {}) {
|
|
285
|
-
const token = await this.tokenFor(scenario, overrides);
|
|
286
|
-
return token ? { authorization: `Bearer ${token}` } : {};
|
|
287
|
-
}
|
|
288
|
-
principalFor(scenario) {
|
|
289
|
-
if (scenario.kind === "unauthenticated") return null;
|
|
290
|
-
return scenarioPrincipal(scenario, this.issuer);
|
|
291
|
-
}
|
|
292
|
-
async signPayload(payload, invalid2) {
|
|
293
|
-
return this.sign(payload, invalid2);
|
|
294
|
-
}
|
|
295
|
-
async sign(payload, invalid2) {
|
|
296
|
-
if (invalid2 === "unsigned") {
|
|
297
|
-
const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
298
|
-
return `${header}.${base64url.encode(JSON.stringify(payload))}.`;
|
|
299
|
-
}
|
|
300
|
-
const key = invalid2 === "unknown-key" ? await this.stranger() : this.signingKey;
|
|
301
|
-
const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
|
|
302
|
-
return invalid2 === "bad-signature" ? tamperSignature(jwt) : jwt;
|
|
303
|
-
}
|
|
304
|
-
stranger() {
|
|
305
|
-
this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
|
|
306
|
-
return this.strangerKey;
|
|
307
|
-
}
|
|
308
|
-
};
|
|
309
|
-
function principalFromClaims(claims) {
|
|
310
|
-
const roles = Array.isArray(claims.roles) ? claims.roles.map(
|
|
311
|
-
(role) => typeof role === "string" ? role : String(role.key ?? "")
|
|
312
|
-
) : [];
|
|
313
|
-
const permissions = Array.isArray(claims.permissions) ? claims.permissions.map(String) : [];
|
|
314
|
-
const machine = Array.isArray(claims.gty) && claims.gty.includes("client_credentials");
|
|
315
|
-
return {
|
|
316
|
-
type: machine ? "machine" : "user",
|
|
317
|
-
subject: String((machine ? claims.azp : claims.sub) ?? ""),
|
|
318
|
-
issuer: String(claims.iss ?? ""),
|
|
319
|
-
organization: typeof claims.org_code === "string" ? { code: claims.org_code } : null,
|
|
320
|
-
roles: roles.filter(Boolean),
|
|
321
|
-
permissions,
|
|
322
|
-
claims: { ...claims }
|
|
323
|
-
};
|
|
324
|
-
}
|
|
325
|
-
function scenarioPrincipal(scenario, issuer) {
|
|
326
|
-
return {
|
|
327
|
-
type: "user",
|
|
328
|
-
subject: scenario.user.id,
|
|
329
|
-
issuer,
|
|
330
|
-
organization: scenario.organization ? { code: scenario.organization.code } : null,
|
|
331
|
-
roles: [...scenario.roles],
|
|
332
|
-
permissions: [...scenario.permissions],
|
|
333
|
-
claims: { ...scenario.claims }
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
function applyInvalidClaims(payload, invalid2, now) {
|
|
337
|
-
const next = { ...payload };
|
|
338
|
-
switch (invalid2) {
|
|
339
|
-
case "expired":
|
|
340
|
-
next.iat = now - 7200;
|
|
341
|
-
next.exp = now - 3600;
|
|
342
|
-
break;
|
|
343
|
-
case "future-iat":
|
|
344
|
-
next.iat = now + 3600;
|
|
345
|
-
next.exp = now + 7200;
|
|
346
|
-
break;
|
|
347
|
-
case "wrong-issuer":
|
|
348
|
-
next.iss = WRONG_ISSUER;
|
|
349
|
-
break;
|
|
350
|
-
case "wrong-audience":
|
|
351
|
-
next.aud = [WRONG_AUDIENCE];
|
|
352
|
-
break;
|
|
353
|
-
case "missing-subject":
|
|
354
|
-
delete next.sub;
|
|
355
|
-
break;
|
|
356
|
-
case "missing-organization":
|
|
357
|
-
delete next.org_code;
|
|
358
|
-
break;
|
|
359
|
-
case "missing-permissions":
|
|
360
|
-
next.permissions = [];
|
|
361
|
-
break;
|
|
362
|
-
default:
|
|
363
|
-
break;
|
|
364
|
-
}
|
|
365
|
-
return next;
|
|
366
|
-
}
|
|
367
|
-
async function createSigningKey(prefix) {
|
|
368
|
-
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
|
369
|
-
const jwk = await exportJWK(publicKey);
|
|
370
|
-
const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
|
|
371
|
-
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
372
|
-
}
|
|
373
|
-
function tamperSignature(jwt) {
|
|
374
|
-
const [header, payload, signature] = jwt.split(".");
|
|
375
|
-
const bytes = base64url.decode(signature);
|
|
376
|
-
bytes[0] = (bytes[0] ?? 0) ^ 255;
|
|
377
|
-
return `${header}.${payload}.${base64url.encode(bytes)}`;
|
|
378
|
-
}
|
|
379
|
-
function toArray(value) {
|
|
380
|
-
if (value === void 0) return [];
|
|
381
|
-
return Array.isArray(value) ? [...value] : [value];
|
|
382
|
-
}
|
|
383
|
-
function trimSlash(value) {
|
|
384
|
-
return value.replace(/\/+$/, "");
|
|
385
|
-
}
|
|
386
|
-
function warnIfRealKindeDomain(issuer) {
|
|
387
|
-
if (/^https:\/\/[^/]+\.kinde\.com$/i.test(issuer)) {
|
|
388
|
-
process.emitWarning(
|
|
389
|
-
`kinde-testkit issuer is set to ${issuer}, which looks like a real Kinde domain. Test tokens are signed with a local key and will never verify against Kinde's JWKS.`,
|
|
390
|
-
{ code: "KINDE_TESTKIT_REAL_ISSUER" }
|
|
391
|
-
);
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
var defaultTestkit = null;
|
|
395
|
-
function getDefaultTestkit() {
|
|
396
|
-
defaultTestkit ??= KindeTestkit.create({
|
|
397
|
-
issuer: process.env.KINDE_TESTKIT_ISSUER ?? DEFAULT_ISSUER,
|
|
398
|
-
audience: process.env.KINDE_TESTKIT_AUDIENCE?.split(",").filter(Boolean)
|
|
399
|
-
});
|
|
400
|
-
return defaultTestkit;
|
|
401
|
-
}
|
|
402
|
-
async function createKindeToken(options = {}) {
|
|
403
|
-
return (await getDefaultTestkit()).token(options);
|
|
404
|
-
}
|
|
2
|
+
DEFAULT_CLIENT_ID,
|
|
3
|
+
DEFAULT_SCOPES,
|
|
4
|
+
INVALID_TOKEN_KINDS,
|
|
5
|
+
KindeTestkit,
|
|
6
|
+
TestkitError,
|
|
7
|
+
createKindeOrganization,
|
|
8
|
+
createKindeUser,
|
|
9
|
+
createMembership,
|
|
10
|
+
slug,
|
|
11
|
+
stableId,
|
|
12
|
+
titleCase
|
|
13
|
+
} from "./chunk-BPPG4G52.js";
|
|
405
14
|
|
|
406
15
|
// src/certificate.ts
|
|
407
|
-
import { createHash
|
|
16
|
+
import { createHash, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
|
|
408
17
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
409
18
|
import { join, resolve } from "path";
|
|
410
19
|
var CERT_FILE = "localhost-cert.pem";
|
|
@@ -434,7 +43,7 @@ function ensureLocalCertificate(directory = ".kinde-testkit") {
|
|
|
434
43
|
function createLocalCertificate() {
|
|
435
44
|
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
436
45
|
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
437
|
-
const keyId =
|
|
46
|
+
const keyId = createHash("sha1").update(subjectPublicKeyBits(spki)).digest();
|
|
438
47
|
const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
|
|
439
48
|
const now = Date.now();
|
|
440
49
|
const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
|
|
@@ -982,6 +591,34 @@ var Directory = class {
|
|
|
982
591
|
for (const key of permissions) this.ensurePermission(key);
|
|
983
592
|
return membership;
|
|
984
593
|
}
|
|
594
|
+
/**
|
|
595
|
+
* Makes sure a user exists with exactly these roles and permissions in the organization, creating
|
|
596
|
+
* the user, organization and membership when they are missing. Used by authenticateAs() in browser
|
|
597
|
+
* tests, so a test can sign in as any identity without adding it to the seed. reset() removes it.
|
|
598
|
+
*/
|
|
599
|
+
ensureIdentity(input) {
|
|
600
|
+
const email = input.email.trim().toLowerCase();
|
|
601
|
+
let user = findUser(this.seed.users, email);
|
|
602
|
+
if (!user) {
|
|
603
|
+
user = createKindeUser({ email, givenName: input.givenName ?? null, familyName: input.familyName ?? null });
|
|
604
|
+
this.seed.users.push(user);
|
|
605
|
+
}
|
|
606
|
+
if (!input.organization) return { user, organization: null };
|
|
607
|
+
let organization = this.organization(input.organization);
|
|
608
|
+
if (!organization) {
|
|
609
|
+
organization = createKindeOrganization({ code: input.organization, name: input.organizationName ?? input.organization });
|
|
610
|
+
this.seed.organizations.push(organization);
|
|
611
|
+
}
|
|
612
|
+
const roles = input.roles ?? [];
|
|
613
|
+
const permissions = input.permissions ?? [];
|
|
614
|
+
const index = this.seed.memberships.findIndex((m) => m.userId === user.id && m.organizationCode === organization.code);
|
|
615
|
+
const membership = createMembership({ userId: user.id, organizationCode: organization.code, roles, permissions });
|
|
616
|
+
if (index >= 0) this.seed.memberships[index] = membership;
|
|
617
|
+
else this.seed.memberships.push(membership);
|
|
618
|
+
for (const key of roles) this.ensureRole(key);
|
|
619
|
+
for (const key of permissions) this.ensurePermission(key);
|
|
620
|
+
return { user, organization };
|
|
621
|
+
}
|
|
985
622
|
removeMembership(userId, organizationCode) {
|
|
986
623
|
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
987
624
|
if (index < 0) return false;
|
|
@@ -1026,6 +663,7 @@ var Directory = class {
|
|
|
1026
663
|
};
|
|
1027
664
|
|
|
1028
665
|
// src/failures.ts
|
|
666
|
+
var MALFORMED_KINDS = ["invalid-json", "empty", "html", "unexpected-json"];
|
|
1029
667
|
var MAX_DELAY_MS = 6e4;
|
|
1030
668
|
var FailureInjector = class {
|
|
1031
669
|
rules = [];
|
|
@@ -1044,6 +682,7 @@ var FailureInjector = class {
|
|
|
1044
682
|
hang: rule.hang ?? false,
|
|
1045
683
|
remaining: rule.times ?? null,
|
|
1046
684
|
retryAfter: rule.retryAfter ?? 1,
|
|
685
|
+
malformed: rule.malformed ?? null,
|
|
1047
686
|
hits: 0
|
|
1048
687
|
};
|
|
1049
688
|
this.rules.push(active);
|
|
@@ -1075,6 +714,18 @@ function failureBody(status) {
|
|
|
1075
714
|
const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
|
|
1076
715
|
return { error, error_description: `kinde-testkit injected a ${status} response.` };
|
|
1077
716
|
}
|
|
717
|
+
function malformedBody(kind) {
|
|
718
|
+
switch (kind) {
|
|
719
|
+
case "invalid-json":
|
|
720
|
+
return { contentType: "application/json", body: '{"access_token":"eyJhbGciOiJSUzI1NiJ9.' };
|
|
721
|
+
case "empty":
|
|
722
|
+
return { contentType: "application/json", body: "" };
|
|
723
|
+
case "html":
|
|
724
|
+
return { contentType: "text/html; charset=utf-8", body: "<!doctype html><html><body><h1>Bad gateway</h1></body></html>" };
|
|
725
|
+
case "unexpected-json":
|
|
726
|
+
return { contentType: "application/json", body: JSON.stringify({ message: "kinde-testkit sent a JSON body in a shape your client does not expect." }) };
|
|
727
|
+
}
|
|
728
|
+
}
|
|
1078
729
|
function matches(rule, method, path) {
|
|
1079
730
|
if (rule.method && rule.method !== method.toUpperCase()) return false;
|
|
1080
731
|
if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
|
|
@@ -1087,8 +738,12 @@ function validate(rule) {
|
|
|
1087
738
|
} else if (rule.path.startsWith("/testkit/")) {
|
|
1088
739
|
problems.push("Failures cannot target /testkit/ control endpoints.");
|
|
1089
740
|
}
|
|
1090
|
-
if (rule.
|
|
1091
|
-
problems.push(
|
|
741
|
+
if (rule.malformed !== void 0 && !MALFORMED_KINDS.includes(rule.malformed)) {
|
|
742
|
+
problems.push(`"malformed" must be one of ${MALFORMED_KINDS.join(", ")}.`);
|
|
743
|
+
}
|
|
744
|
+
const lowest = rule.malformed ? 200 : 400;
|
|
745
|
+
if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < lowest || rule.status > 599)) {
|
|
746
|
+
problems.push(rule.malformed ? '"status" must be between 200 and 599.' : '"status" must be an HTTP error status between 400 and 599.');
|
|
1092
747
|
}
|
|
1093
748
|
if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
|
|
1094
749
|
problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
|
|
@@ -1099,8 +754,8 @@ function validate(rule) {
|
|
|
1099
754
|
if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
|
|
1100
755
|
problems.push('"retryAfter" must be a whole number of seconds.');
|
|
1101
756
|
}
|
|
1102
|
-
if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
|
|
1103
|
-
problems.push('Set at least one of "status", "delayMs" or "
|
|
757
|
+
if (rule.status === void 0 && !rule.delayMs && !rule.hang && !rule.malformed) {
|
|
758
|
+
problems.push('Set at least one of "status", "delayMs", "hang" or "malformed".');
|
|
1104
759
|
}
|
|
1105
760
|
return problems;
|
|
1106
761
|
}
|
|
@@ -1413,7 +1068,7 @@ var ActivityLog = class {
|
|
|
1413
1068
|
injected: entry.injected
|
|
1414
1069
|
});
|
|
1415
1070
|
}
|
|
1416
|
-
token(kind, claims,
|
|
1071
|
+
token(kind, claims, invalid, token) {
|
|
1417
1072
|
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
1418
1073
|
push(this.tokenLog, {
|
|
1419
1074
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -1422,7 +1077,7 @@ var ActivityLog = class {
|
|
|
1422
1077
|
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
1423
1078
|
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
1424
1079
|
roles,
|
|
1425
|
-
invalid:
|
|
1080
|
+
invalid: invalid ?? null,
|
|
1426
1081
|
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
1427
1082
|
claims,
|
|
1428
1083
|
token
|
|
@@ -1456,7 +1111,9 @@ var COVERAGE_GROUPS = [
|
|
|
1456
1111
|
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
1457
1112
|
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
1458
1113
|
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
1459
|
-
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
|
|
1114
|
+
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." },
|
|
1115
|
+
{ id: "identity.social", label: "Social sign-in", hint: 'Sign in with a social connection, such as signInAs(email, { connection: "google" }).' },
|
|
1116
|
+
{ id: "identity.mfa", label: "Multi-factor sign-in", hint: 'Sign in with { mfa: "passed" }.' }
|
|
1460
1117
|
]
|
|
1461
1118
|
},
|
|
1462
1119
|
{
|
|
@@ -1493,6 +1150,7 @@ var COVERAGE_GROUPS = [
|
|
|
1493
1150
|
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
1494
1151
|
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
1495
1152
|
{ id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." },
|
|
1153
|
+
{ id: "session.sign-in-refused", label: "Sign-in cancelled or failed", hint: `Sign in with { providerResult: "cancelled" } or { mfa: "failed" } and check the app's error handling.` },
|
|
1496
1154
|
{ id: "session.device-approved", label: "Device sign-in", hint: "Run the device authorization flow and approve it with POST /testkit/device." }
|
|
1497
1155
|
]
|
|
1498
1156
|
},
|
|
@@ -1530,7 +1188,8 @@ var COVERAGE_GROUPS = [
|
|
|
1530
1188
|
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
1531
1189
|
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
1532
1190
|
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
1533
|
-
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
|
|
1191
|
+
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." },
|
|
1192
|
+
{ id: "outage.malformed", label: "Malformed answer", hint: "Inject a malformed response, such as invalid JSON from the token endpoint." }
|
|
1534
1193
|
]
|
|
1535
1194
|
}
|
|
1536
1195
|
];
|
|
@@ -1557,17 +1216,17 @@ var CoverageRecorder = class {
|
|
|
1557
1216
|
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
1558
1217
|
}
|
|
1559
1218
|
/** Called for every access token the testkit signs. */
|
|
1560
|
-
observeAccessToken(payload,
|
|
1219
|
+
observeAccessToken(payload, invalid) {
|
|
1561
1220
|
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
1562
1221
|
this.hit("m2m.token");
|
|
1563
1222
|
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
1564
1223
|
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
1565
|
-
if (
|
|
1224
|
+
if (invalid) this.hit("m2m.invalid");
|
|
1566
1225
|
return;
|
|
1567
1226
|
}
|
|
1568
|
-
if (
|
|
1569
|
-
if (
|
|
1570
|
-
if (
|
|
1227
|
+
if (invalid === "missing-organization") return this.hit("organization.missing");
|
|
1228
|
+
if (invalid === "missing-permissions") return this.hit("permission.none");
|
|
1229
|
+
if (invalid) return this.hit(`token.${invalid}`);
|
|
1571
1230
|
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
1572
1231
|
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
1573
1232
|
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
@@ -1753,6 +1412,25 @@ function layout(title, body) {
|
|
|
1753
1412
|
function displayName(user) {
|
|
1754
1413
|
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
1755
1414
|
}
|
|
1415
|
+
var SOCIAL_CONNECTIONS = ["google", "github", "microsoft", "apple", "facebook", "gitlab", "linkedin", "slack", "x"];
|
|
1416
|
+
function select(id, label, options) {
|
|
1417
|
+
return `<label for="${id}">${label}</label><select id="${id}" name="${id}" style="width:100%;height:38px;padding:0 10px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit">${options.map(([value, text]) => `<option value="${value}">${escapeHtml(text)}</option>`).join("")}</select>`;
|
|
1418
|
+
}
|
|
1419
|
+
function testOptions() {
|
|
1420
|
+
return `<h2>Test options</h2>${select("connection", "Sign in with", [
|
|
1421
|
+
["email", "Email"],
|
|
1422
|
+
...SOCIAL_CONNECTIONS.map((c) => [c, c === "x" ? "X" : c[0].toUpperCase() + c.slice(1)])
|
|
1423
|
+
])}${select("provider_result", "Provider result", [
|
|
1424
|
+
["success", "Signed in"],
|
|
1425
|
+
["cancelled", "User cancelled"],
|
|
1426
|
+
["error", "Provider error"]
|
|
1427
|
+
])}${select("mfa", "Multi-factor authentication", [
|
|
1428
|
+
["none", "Not required"],
|
|
1429
|
+
["passed", "Passed"],
|
|
1430
|
+
["failed", "Wrong code"],
|
|
1431
|
+
["cancelled", "Cancelled"]
|
|
1432
|
+
])}`;
|
|
1433
|
+
}
|
|
1756
1434
|
function renderSignIn(options) {
|
|
1757
1435
|
const users = options.users.map(({ user, organizations }) => {
|
|
1758
1436
|
const value = escapeHtml(user.email ?? user.id);
|
|
@@ -1764,16 +1442,17 @@ function renderSignIn(options) {
|
|
|
1764
1442
|
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
1765
1443
|
return layout(
|
|
1766
1444
|
"Sign in",
|
|
1767
|
-
`<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}</form>`
|
|
1445
|
+
`<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}${testOptions()}</form>`
|
|
1768
1446
|
);
|
|
1769
1447
|
}
|
|
1770
1448
|
function renderOrganizationPicker(options) {
|
|
1449
|
+
const carried = Object.entries(options.carry ?? {}).map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`).join("");
|
|
1771
1450
|
const choices = options.organizations.map(
|
|
1772
1451
|
(org) => `<button class="option" type="submit" name="org" value="${escapeHtml(org.code)}"><span><strong>${escapeHtml(org.name)}</strong><small>${escapeHtml(org.code)}</small></span></button>`
|
|
1773
1452
|
).join("");
|
|
1774
1453
|
return layout(
|
|
1775
1454
|
"Choose an organization",
|
|
1776
|
-
`<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}"
|
|
1455
|
+
`<h1>Choose an organization</h1><p>${escapeHtml(options.user.email ?? options.user.id)} belongs to more than one organization.</p><form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><input type="hidden" name="user" value="${escapeHtml(options.user.email ?? options.user.id)}">${carried}<div class="list" style="margin-top:20px">${choices}</div></form>`
|
|
1777
1456
|
);
|
|
1778
1457
|
}
|
|
1779
1458
|
function renderMessage(title, message) {
|
|
@@ -1794,7 +1473,7 @@ function renderDeviceConfirm(options) {
|
|
|
1794
1473
|
}
|
|
1795
1474
|
|
|
1796
1475
|
// src/oauth.ts
|
|
1797
|
-
import { createHash as
|
|
1476
|
+
import { createHash as createHash2, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
|
|
1798
1477
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
1799
1478
|
var DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
1800
1479
|
var USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
|
|
@@ -1903,6 +1582,17 @@ var AuthorizationServer = class {
|
|
|
1903
1582
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
1904
1583
|
}
|
|
1905
1584
|
const encoded = encodeRequest(request);
|
|
1585
|
+
const connection = (form2.connection || "email").trim().toLowerCase();
|
|
1586
|
+
const providerResult = form2.provider_result || "success";
|
|
1587
|
+
const mfa = form2.mfa || "none";
|
|
1588
|
+
if (!/^[a-z0-9_-]{1,40}$/.test(connection) || !["success", "cancelled", "error"].includes(providerResult) || !["none", "passed", "failed", "cancelled"].includes(mfa)) {
|
|
1589
|
+
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "The test options on the sign-in form are not valid." }));
|
|
1590
|
+
}
|
|
1591
|
+
if (connection !== "email" && providerResult !== "success") {
|
|
1592
|
+
this.observe("session.sign-in-refused");
|
|
1593
|
+
return providerResult === "cancelled" ? redirectWithError(res, request, "access_denied", `The user cancelled sign-in with ${connection}.`) : redirectWithError(res, request, "server_error", `${connection} returned an error during sign-in.`);
|
|
1594
|
+
}
|
|
1595
|
+
const carry = { connection, provider_result: providerResult, mfa };
|
|
1906
1596
|
const ref = (form2.user || form2.email || "").trim();
|
|
1907
1597
|
if (!ref) {
|
|
1908
1598
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
|
|
@@ -1924,6 +1614,21 @@ var AuthorizationServer = class {
|
|
|
1924
1614
|
})
|
|
1925
1615
|
);
|
|
1926
1616
|
}
|
|
1617
|
+
if (mfa === "failed") {
|
|
1618
|
+
this.observe("session.sign-in-refused");
|
|
1619
|
+
return sendHtml(
|
|
1620
|
+
res,
|
|
1621
|
+
401,
|
|
1622
|
+
renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "The verification code is not correct." })
|
|
1623
|
+
);
|
|
1624
|
+
}
|
|
1625
|
+
if (mfa === "cancelled") {
|
|
1626
|
+
this.observe("session.sign-in-refused");
|
|
1627
|
+
return redirectWithError(res, request, "access_denied", "The user cancelled multi-factor authentication.");
|
|
1628
|
+
}
|
|
1629
|
+
if (connection !== "email") this.observe("identity.social");
|
|
1630
|
+
if (mfa === "passed") this.observe("identity.mfa");
|
|
1631
|
+
const authMethods = [connection, ...mfa === "passed" ? ["mfa"] : []];
|
|
1927
1632
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
1928
1633
|
const wanted = request.orgCode ?? form2.org ?? null;
|
|
1929
1634
|
let organizationCode = null;
|
|
@@ -1951,7 +1656,8 @@ var AuthorizationServer = class {
|
|
|
1951
1656
|
renderOrganizationPicker({
|
|
1952
1657
|
request: encoded,
|
|
1953
1658
|
user,
|
|
1954
|
-
organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
1659
|
+
organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null),
|
|
1660
|
+
carry
|
|
1955
1661
|
})
|
|
1956
1662
|
);
|
|
1957
1663
|
}
|
|
@@ -1973,6 +1679,7 @@ var AuthorizationServer = class {
|
|
|
1973
1679
|
audience: request.audience,
|
|
1974
1680
|
nonce: request.nonce,
|
|
1975
1681
|
authTime: Math.floor(Date.now() / 1e3),
|
|
1682
|
+
authMethods,
|
|
1976
1683
|
codeChallenge: request.codeChallenge,
|
|
1977
1684
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
1978
1685
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
@@ -2253,7 +1960,7 @@ var AuthorizationServer = class {
|
|
|
2253
1960
|
}
|
|
2254
1961
|
if (pending.codeChallenge) {
|
|
2255
1962
|
const verifier = form2.code_verifier ?? "";
|
|
2256
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1963
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash2("sha256").update(verifier).digest("base64url");
|
|
2257
1964
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
2258
1965
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
2259
1966
|
}
|
|
@@ -2284,6 +1991,7 @@ var AuthorizationServer = class {
|
|
|
2284
1991
|
clientId: grant.clientId,
|
|
2285
1992
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
2286
1993
|
authTime: grant.authTime,
|
|
1994
|
+
authMethods: grant.authMethods,
|
|
2287
1995
|
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
2288
1996
|
}),
|
|
2289
1997
|
expires_in: this.testkit.accessTokenLifetime,
|
|
@@ -2294,7 +2002,8 @@ var AuthorizationServer = class {
|
|
|
2294
2002
|
body.id_token = await this.testkit.idTokenFor(scenario, {
|
|
2295
2003
|
clientId: grant.clientId,
|
|
2296
2004
|
nonce: grant.nonce ?? void 0,
|
|
2297
|
-
authTime: grant.authTime
|
|
2005
|
+
authTime: grant.authTime,
|
|
2006
|
+
authMethods: grant.authMethods
|
|
2298
2007
|
});
|
|
2299
2008
|
}
|
|
2300
2009
|
if (grant.scope.includes("offline")) {
|
|
@@ -3217,10 +2926,10 @@ async function startKindeTestkit(options = {}) {
|
|
|
3217
2926
|
const coverage = new CoverageRecorder();
|
|
3218
2927
|
const activity = new ActivityLog();
|
|
3219
2928
|
testkit.observe({
|
|
3220
|
-
accessToken(payload,
|
|
3221
|
-
coverage.observeAccessToken(payload,
|
|
2929
|
+
accessToken(payload, invalid, token) {
|
|
2930
|
+
coverage.observeAccessToken(payload, invalid);
|
|
3222
2931
|
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
3223
|
-
activity.token(m2m ? "m2m" : "access", payload,
|
|
2932
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid, token);
|
|
3224
2933
|
},
|
|
3225
2934
|
idToken(payload, token) {
|
|
3226
2935
|
coverage.hit("identity.id-token");
|
|
@@ -3302,6 +3011,13 @@ async function handle(req, res, context) {
|
|
|
3302
3011
|
if (failure.delayMs > 0) coverage.hit("outage.slow");
|
|
3303
3012
|
if (failure.hang) return;
|
|
3304
3013
|
if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
|
|
3014
|
+
if (failure.malformed) {
|
|
3015
|
+
coverage.hit("outage.malformed");
|
|
3016
|
+
const { contentType, body } = malformedBody(failure.malformed);
|
|
3017
|
+
res.writeHead(failure.status ?? 200, { "content-type": contentType, "cache-control": "no-store" });
|
|
3018
|
+
res.end(body);
|
|
3019
|
+
return;
|
|
3020
|
+
}
|
|
3305
3021
|
if (failure.status !== null) {
|
|
3306
3022
|
const headers = {};
|
|
3307
3023
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
@@ -3369,6 +3085,23 @@ async function handle(req, res, context) {
|
|
|
3369
3085
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
3370
3086
|
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
3371
3087
|
}
|
|
3088
|
+
if (method === "POST" && pathname === "/testkit/identities") {
|
|
3089
|
+
const input = await readJson(req);
|
|
3090
|
+
if (typeof input.email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.email)) {
|
|
3091
|
+
throw new TestkitError("INVALID_REQUEST", "An identity needs an email address.");
|
|
3092
|
+
}
|
|
3093
|
+
const strings2 = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : void 0;
|
|
3094
|
+
const { user, organization } = context.directory.ensureIdentity({
|
|
3095
|
+
email: input.email,
|
|
3096
|
+
givenName: typeof input.givenName === "string" ? input.givenName : null,
|
|
3097
|
+
familyName: typeof input.familyName === "string" ? input.familyName : null,
|
|
3098
|
+
organization: typeof input.organization === "string" ? input.organization : null,
|
|
3099
|
+
organizationName: typeof input.organizationName === "string" ? input.organizationName : void 0,
|
|
3100
|
+
roles: strings2(input.roles),
|
|
3101
|
+
permissions: strings2(input.permissions)
|
|
3102
|
+
});
|
|
3103
|
+
return sendJson4(res, 200, { user: { id: user.id, email: user.email }, organization: organization?.code ?? null });
|
|
3104
|
+
}
|
|
3372
3105
|
if (method === "POST" && pathname === "/testkit/device") {
|
|
3373
3106
|
const input = await readJson(req);
|
|
3374
3107
|
try {
|
|
@@ -3534,9 +3267,9 @@ async function issueToken(testkit, seed, body) {
|
|
|
3534
3267
|
throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
|
|
3535
3268
|
}
|
|
3536
3269
|
const input = body;
|
|
3537
|
-
const
|
|
3538
|
-
if (
|
|
3539
|
-
throw new TestkitError("INVALID_REQUEST", `"${
|
|
3270
|
+
const invalid = optionalString(input, "invalid");
|
|
3271
|
+
if (invalid !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid)) {
|
|
3272
|
+
throw new TestkitError("INVALID_REQUEST", `"${invalid}" is not a known invalid token kind.`, [
|
|
3540
3273
|
`Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
|
|
3541
3274
|
]);
|
|
3542
3275
|
}
|
|
@@ -3553,7 +3286,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
3553
3286
|
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
3554
3287
|
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
3555
3288
|
expiresIn,
|
|
3556
|
-
invalid
|
|
3289
|
+
invalid
|
|
3557
3290
|
});
|
|
3558
3291
|
}
|
|
3559
3292
|
const permissions = optionalStrings(input, "permissions");
|
|
@@ -3568,7 +3301,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
3568
3301
|
if (roles) scenario.roles = roles;
|
|
3569
3302
|
return await testkit.tokenFor(scenario, {
|
|
3570
3303
|
expiresIn,
|
|
3571
|
-
invalid
|
|
3304
|
+
invalid,
|
|
3572
3305
|
featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
|
|
3573
3306
|
});
|
|
3574
3307
|
}
|
|
@@ -3579,7 +3312,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
3579
3312
|
roles,
|
|
3580
3313
|
scopes: optionalStrings(input, "scopes"),
|
|
3581
3314
|
expiresIn,
|
|
3582
|
-
invalid
|
|
3315
|
+
invalid
|
|
3583
3316
|
};
|
|
3584
3317
|
if (typeof input.claims === "object" && input.claims !== null) {
|
|
3585
3318
|
options.claims = input.claims;
|
|
@@ -3659,22 +3392,6 @@ function sendError(res, error) {
|
|
|
3659
3392
|
}
|
|
3660
3393
|
|
|
3661
3394
|
export {
|
|
3662
|
-
createKindeUser,
|
|
3663
|
-
createKindeOrganization,
|
|
3664
|
-
createMembership,
|
|
3665
|
-
toKindeRole,
|
|
3666
|
-
resetFactories,
|
|
3667
|
-
TestkitError,
|
|
3668
|
-
DEFAULT_ISSUER,
|
|
3669
|
-
DEFAULT_CLIENT_ID,
|
|
3670
|
-
DEFAULT_M2M_CLIENT_ID,
|
|
3671
|
-
DEFAULT_SCOPES,
|
|
3672
|
-
DEFAULT_AUTH_METHODS,
|
|
3673
|
-
INVALID_TOKEN_KINDS,
|
|
3674
|
-
KindeTestkit,
|
|
3675
|
-
principalFromClaims,
|
|
3676
|
-
getDefaultTestkit,
|
|
3677
|
-
createKindeToken,
|
|
3678
3395
|
ensureLocalCertificate,
|
|
3679
3396
|
createLocalCertificate,
|
|
3680
3397
|
resolveSeed,
|
|
@@ -3698,4 +3415,4 @@ export {
|
|
|
3698
3415
|
loadSeedFile,
|
|
3699
3416
|
startKindeTestkit
|
|
3700
3417
|
};
|
|
3701
|
-
//# sourceMappingURL=chunk-
|
|
3418
|
+
//# sourceMappingURL=chunk-CY75AADD.js.map
|