kinde-testkit 0.7.0 → 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 +15 -0
- package/README.md +97 -9
- package/dist/chunk-BPPG4G52.js +427 -0
- package/dist/chunk-BPPG4G52.js.map +1 -0
- package/dist/{chunk-JTAB2S44.js → chunk-CY75AADD.js} +175 -454
- 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-2QJ7DTNL.js → chunk-YJPE5HAM.js} +5 -3
- package/dist/{chunk-2QJ7DTNL.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 +142 -0
- package/dist/cypress-support.js +21 -6
- package/dist/cypress-support.js.map +1 -1
- package/dist/cypress.cjs +142 -14
- 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-estfqypp.d.cts → handle-DRPxm36j.d.cts} +1 -1
- package/dist/{handle-E_BhdHx8.d.ts → handle-Pjt9fSUq.d.ts} +3 -2
- package/dist/index.cjs +145 -14
- 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 +142 -14
- 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-CTBJXMac.d.cts → server-CLRn67qI.d.cts} +26 -0
- package/dist/{server-B9fBcnyQ.d.ts → server-CuHAHsaN.d.ts} +3 -56
- 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-JTAB2S44.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)));
|
|
@@ -898,7 +507,8 @@ var Directory = class {
|
|
|
898
507
|
isPasswordResetRequested: false,
|
|
899
508
|
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
900
509
|
totalSignIns: 0,
|
|
901
|
-
lastSignedIn: null
|
|
510
|
+
lastSignedIn: null,
|
|
511
|
+
lastOrganizationSignIns: {}
|
|
902
512
|
};
|
|
903
513
|
this.userMeta.set(user.id, meta);
|
|
904
514
|
}
|
|
@@ -911,7 +521,7 @@ var Directory = class {
|
|
|
911
521
|
const meta = this.meta(user);
|
|
912
522
|
meta.totalSignIns += 1;
|
|
913
523
|
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
914
|
-
|
|
524
|
+
if (organizationCode) meta.lastOrganizationSignIns[organizationCode] = meta.lastSignedIn;
|
|
915
525
|
}
|
|
916
526
|
createUser(input) {
|
|
917
527
|
const user = createKindeUser({
|
|
@@ -981,6 +591,34 @@ var Directory = class {
|
|
|
981
591
|
for (const key of permissions) this.ensurePermission(key);
|
|
982
592
|
return membership;
|
|
983
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
|
+
}
|
|
984
622
|
removeMembership(userId, organizationCode) {
|
|
985
623
|
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
986
624
|
if (index < 0) return false;
|
|
@@ -1025,6 +663,7 @@ var Directory = class {
|
|
|
1025
663
|
};
|
|
1026
664
|
|
|
1027
665
|
// src/failures.ts
|
|
666
|
+
var MALFORMED_KINDS = ["invalid-json", "empty", "html", "unexpected-json"];
|
|
1028
667
|
var MAX_DELAY_MS = 6e4;
|
|
1029
668
|
var FailureInjector = class {
|
|
1030
669
|
rules = [];
|
|
@@ -1043,6 +682,7 @@ var FailureInjector = class {
|
|
|
1043
682
|
hang: rule.hang ?? false,
|
|
1044
683
|
remaining: rule.times ?? null,
|
|
1045
684
|
retryAfter: rule.retryAfter ?? 1,
|
|
685
|
+
malformed: rule.malformed ?? null,
|
|
1046
686
|
hits: 0
|
|
1047
687
|
};
|
|
1048
688
|
this.rules.push(active);
|
|
@@ -1074,6 +714,18 @@ function failureBody(status) {
|
|
|
1074
714
|
const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
|
|
1075
715
|
return { error, error_description: `kinde-testkit injected a ${status} response.` };
|
|
1076
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
|
+
}
|
|
1077
729
|
function matches(rule, method, path) {
|
|
1078
730
|
if (rule.method && rule.method !== method.toUpperCase()) return false;
|
|
1079
731
|
if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
|
|
@@ -1086,8 +738,12 @@ function validate(rule) {
|
|
|
1086
738
|
} else if (rule.path.startsWith("/testkit/")) {
|
|
1087
739
|
problems.push("Failures cannot target /testkit/ control endpoints.");
|
|
1088
740
|
}
|
|
1089
|
-
if (rule.
|
|
1090
|
-
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.');
|
|
1091
747
|
}
|
|
1092
748
|
if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
|
|
1093
749
|
problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
|
|
@@ -1098,8 +754,8 @@ function validate(rule) {
|
|
|
1098
754
|
if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
|
|
1099
755
|
problems.push('"retryAfter" must be a whole number of seconds.');
|
|
1100
756
|
}
|
|
1101
|
-
if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
|
|
1102
|
-
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".');
|
|
1103
759
|
}
|
|
1104
760
|
return problems;
|
|
1105
761
|
}
|
|
@@ -1412,7 +1068,7 @@ var ActivityLog = class {
|
|
|
1412
1068
|
injected: entry.injected
|
|
1413
1069
|
});
|
|
1414
1070
|
}
|
|
1415
|
-
token(kind, claims,
|
|
1071
|
+
token(kind, claims, invalid, token) {
|
|
1416
1072
|
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
1417
1073
|
push(this.tokenLog, {
|
|
1418
1074
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -1421,7 +1077,7 @@ var ActivityLog = class {
|
|
|
1421
1077
|
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
1422
1078
|
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
1423
1079
|
roles,
|
|
1424
|
-
invalid:
|
|
1080
|
+
invalid: invalid ?? null,
|
|
1425
1081
|
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
1426
1082
|
claims,
|
|
1427
1083
|
token
|
|
@@ -1455,7 +1111,9 @@ var COVERAGE_GROUPS = [
|
|
|
1455
1111
|
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
1456
1112
|
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
1457
1113
|
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
1458
|
-
{ 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" }.' }
|
|
1459
1117
|
]
|
|
1460
1118
|
},
|
|
1461
1119
|
{
|
|
@@ -1492,6 +1150,7 @@ var COVERAGE_GROUPS = [
|
|
|
1492
1150
|
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
1493
1151
|
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
1494
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.` },
|
|
1495
1154
|
{ id: "session.device-approved", label: "Device sign-in", hint: "Run the device authorization flow and approve it with POST /testkit/device." }
|
|
1496
1155
|
]
|
|
1497
1156
|
},
|
|
@@ -1529,7 +1188,8 @@ var COVERAGE_GROUPS = [
|
|
|
1529
1188
|
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
1530
1189
|
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
1531
1190
|
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
1532
|
-
{ 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." }
|
|
1533
1193
|
]
|
|
1534
1194
|
}
|
|
1535
1195
|
];
|
|
@@ -1556,17 +1216,17 @@ var CoverageRecorder = class {
|
|
|
1556
1216
|
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
1557
1217
|
}
|
|
1558
1218
|
/** Called for every access token the testkit signs. */
|
|
1559
|
-
observeAccessToken(payload,
|
|
1219
|
+
observeAccessToken(payload, invalid) {
|
|
1560
1220
|
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
1561
1221
|
this.hit("m2m.token");
|
|
1562
1222
|
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
1563
1223
|
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
1564
|
-
if (
|
|
1224
|
+
if (invalid) this.hit("m2m.invalid");
|
|
1565
1225
|
return;
|
|
1566
1226
|
}
|
|
1567
|
-
if (
|
|
1568
|
-
if (
|
|
1569
|
-
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}`);
|
|
1570
1230
|
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
1571
1231
|
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
1572
1232
|
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
@@ -1752,6 +1412,25 @@ function layout(title, body) {
|
|
|
1752
1412
|
function displayName(user) {
|
|
1753
1413
|
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
1754
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
|
+
}
|
|
1755
1434
|
function renderSignIn(options) {
|
|
1756
1435
|
const users = options.users.map(({ user, organizations }) => {
|
|
1757
1436
|
const value = escapeHtml(user.email ?? user.id);
|
|
@@ -1763,16 +1442,17 @@ function renderSignIn(options) {
|
|
|
1763
1442
|
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
1764
1443
|
return layout(
|
|
1765
1444
|
"Sign in",
|
|
1766
|
-
`<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>`
|
|
1767
1446
|
);
|
|
1768
1447
|
}
|
|
1769
1448
|
function renderOrganizationPicker(options) {
|
|
1449
|
+
const carried = Object.entries(options.carry ?? {}).map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`).join("");
|
|
1770
1450
|
const choices = options.organizations.map(
|
|
1771
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>`
|
|
1772
1452
|
).join("");
|
|
1773
1453
|
return layout(
|
|
1774
1454
|
"Choose an organization",
|
|
1775
|
-
`<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>`
|
|
1776
1456
|
);
|
|
1777
1457
|
}
|
|
1778
1458
|
function renderMessage(title, message) {
|
|
@@ -1793,7 +1473,7 @@ function renderDeviceConfirm(options) {
|
|
|
1793
1473
|
}
|
|
1794
1474
|
|
|
1795
1475
|
// src/oauth.ts
|
|
1796
|
-
import { createHash as
|
|
1476
|
+
import { createHash as createHash2, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
|
|
1797
1477
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
1798
1478
|
var DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
1799
1479
|
var USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
|
|
@@ -1902,6 +1582,17 @@ var AuthorizationServer = class {
|
|
|
1902
1582
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
1903
1583
|
}
|
|
1904
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 };
|
|
1905
1596
|
const ref = (form2.user || form2.email || "").trim();
|
|
1906
1597
|
if (!ref) {
|
|
1907
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." }));
|
|
@@ -1923,6 +1614,21 @@ var AuthorizationServer = class {
|
|
|
1923
1614
|
})
|
|
1924
1615
|
);
|
|
1925
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"] : []];
|
|
1926
1632
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
1927
1633
|
const wanted = request.orgCode ?? form2.org ?? null;
|
|
1928
1634
|
let organizationCode = null;
|
|
@@ -1950,7 +1656,8 @@ var AuthorizationServer = class {
|
|
|
1950
1656
|
renderOrganizationPicker({
|
|
1951
1657
|
request: encoded,
|
|
1952
1658
|
user,
|
|
1953
|
-
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
|
|
1954
1661
|
})
|
|
1955
1662
|
);
|
|
1956
1663
|
}
|
|
@@ -1972,6 +1679,7 @@ var AuthorizationServer = class {
|
|
|
1972
1679
|
audience: request.audience,
|
|
1973
1680
|
nonce: request.nonce,
|
|
1974
1681
|
authTime: Math.floor(Date.now() / 1e3),
|
|
1682
|
+
authMethods,
|
|
1975
1683
|
codeChallenge: request.codeChallenge,
|
|
1976
1684
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
1977
1685
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
@@ -2252,7 +1960,7 @@ var AuthorizationServer = class {
|
|
|
2252
1960
|
}
|
|
2253
1961
|
if (pending.codeChallenge) {
|
|
2254
1962
|
const verifier = form2.code_verifier ?? "";
|
|
2255
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier :
|
|
1963
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash2("sha256").update(verifier).digest("base64url");
|
|
2256
1964
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
2257
1965
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
2258
1966
|
}
|
|
@@ -2283,6 +1991,7 @@ var AuthorizationServer = class {
|
|
|
2283
1991
|
clientId: grant.clientId,
|
|
2284
1992
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
2285
1993
|
authTime: grant.authTime,
|
|
1994
|
+
authMethods: grant.authMethods,
|
|
2286
1995
|
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
2287
1996
|
}),
|
|
2288
1997
|
expires_in: this.testkit.accessTokenLifetime,
|
|
@@ -2293,7 +2002,8 @@ var AuthorizationServer = class {
|
|
|
2293
2002
|
body.id_token = await this.testkit.idTokenFor(scenario, {
|
|
2294
2003
|
clientId: grant.clientId,
|
|
2295
2004
|
nonce: grant.nonce ?? void 0,
|
|
2296
|
-
authTime: grant.authTime
|
|
2005
|
+
authTime: grant.authTime,
|
|
2006
|
+
authMethods: grant.authMethods
|
|
2297
2007
|
});
|
|
2298
2008
|
}
|
|
2299
2009
|
if (grant.scope.includes("offline")) {
|
|
@@ -2928,12 +2638,14 @@ var ManagementApi = class {
|
|
|
2928
2638
|
username: null,
|
|
2929
2639
|
last_name: user.familyName,
|
|
2930
2640
|
first_name: user.givenName,
|
|
2641
|
+
full_name: [user.givenName, user.familyName].filter(Boolean).join(" ") || null,
|
|
2931
2642
|
is_suspended: meta.isSuspended,
|
|
2932
2643
|
picture: user.picture,
|
|
2933
2644
|
total_sign_ins: meta.totalSignIns,
|
|
2934
2645
|
failed_sign_ins: 0,
|
|
2935
2646
|
last_signed_in: meta.lastSignedIn,
|
|
2936
2647
|
created_on: meta.createdOn,
|
|
2648
|
+
last_organization_sign_ins: Object.entries(meta.lastOrganizationSignIns).map(([org_code, last_signed_in]) => ({ org_code, last_signed_in })),
|
|
2937
2649
|
organizations: this.organizationsOf(user),
|
|
2938
2650
|
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
2939
2651
|
};
|
|
@@ -2953,7 +2665,8 @@ var ManagementApi = class {
|
|
|
2953
2665
|
handle: meta.handle,
|
|
2954
2666
|
is_default: false,
|
|
2955
2667
|
external_id: meta.externalId,
|
|
2956
|
-
is_auto_membership_enabled: false
|
|
2668
|
+
is_auto_membership_enabled: false,
|
|
2669
|
+
created_on: meta.createdOn
|
|
2957
2670
|
};
|
|
2958
2671
|
}
|
|
2959
2672
|
organizationEvent(org) {
|
|
@@ -2964,7 +2677,7 @@ var ManagementApi = class {
|
|
|
2964
2677
|
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
2965
2678
|
}
|
|
2966
2679
|
permissionItem(permission) {
|
|
2967
|
-
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
2680
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, is_organization_role_assignable: false };
|
|
2968
2681
|
}
|
|
2969
2682
|
};
|
|
2970
2683
|
function paginate(items, query) {
|
|
@@ -3213,10 +2926,10 @@ async function startKindeTestkit(options = {}) {
|
|
|
3213
2926
|
const coverage = new CoverageRecorder();
|
|
3214
2927
|
const activity = new ActivityLog();
|
|
3215
2928
|
testkit.observe({
|
|
3216
|
-
accessToken(payload,
|
|
3217
|
-
coverage.observeAccessToken(payload,
|
|
2929
|
+
accessToken(payload, invalid, token) {
|
|
2930
|
+
coverage.observeAccessToken(payload, invalid);
|
|
3218
2931
|
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
3219
|
-
activity.token(m2m ? "m2m" : "access", payload,
|
|
2932
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid, token);
|
|
3220
2933
|
},
|
|
3221
2934
|
idToken(payload, token) {
|
|
3222
2935
|
coverage.hit("identity.id-token");
|
|
@@ -3298,6 +3011,13 @@ async function handle(req, res, context) {
|
|
|
3298
3011
|
if (failure.delayMs > 0) coverage.hit("outage.slow");
|
|
3299
3012
|
if (failure.hang) return;
|
|
3300
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
|
+
}
|
|
3301
3021
|
if (failure.status !== null) {
|
|
3302
3022
|
const headers = {};
|
|
3303
3023
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
@@ -3365,6 +3085,23 @@ async function handle(req, res, context) {
|
|
|
3365
3085
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
3366
3086
|
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
3367
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
|
+
}
|
|
3368
3105
|
if (method === "POST" && pathname === "/testkit/device") {
|
|
3369
3106
|
const input = await readJson(req);
|
|
3370
3107
|
try {
|
|
@@ -3530,9 +3267,9 @@ async function issueToken(testkit, seed, body) {
|
|
|
3530
3267
|
throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
|
|
3531
3268
|
}
|
|
3532
3269
|
const input = body;
|
|
3533
|
-
const
|
|
3534
|
-
if (
|
|
3535
|
-
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.`, [
|
|
3536
3273
|
`Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
|
|
3537
3274
|
]);
|
|
3538
3275
|
}
|
|
@@ -3549,7 +3286,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
3549
3286
|
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
3550
3287
|
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
3551
3288
|
expiresIn,
|
|
3552
|
-
invalid
|
|
3289
|
+
invalid
|
|
3553
3290
|
});
|
|
3554
3291
|
}
|
|
3555
3292
|
const permissions = optionalStrings(input, "permissions");
|
|
@@ -3564,7 +3301,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
3564
3301
|
if (roles) scenario.roles = roles;
|
|
3565
3302
|
return await testkit.tokenFor(scenario, {
|
|
3566
3303
|
expiresIn,
|
|
3567
|
-
invalid
|
|
3304
|
+
invalid,
|
|
3568
3305
|
featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
|
|
3569
3306
|
});
|
|
3570
3307
|
}
|
|
@@ -3575,7 +3312,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
3575
3312
|
roles,
|
|
3576
3313
|
scopes: optionalStrings(input, "scopes"),
|
|
3577
3314
|
expiresIn,
|
|
3578
|
-
invalid
|
|
3315
|
+
invalid
|
|
3579
3316
|
};
|
|
3580
3317
|
if (typeof input.claims === "object" && input.claims !== null) {
|
|
3581
3318
|
options.claims = input.claims;
|
|
@@ -3655,22 +3392,6 @@ function sendError(res, error) {
|
|
|
3655
3392
|
}
|
|
3656
3393
|
|
|
3657
3394
|
export {
|
|
3658
|
-
createKindeUser,
|
|
3659
|
-
createKindeOrganization,
|
|
3660
|
-
createMembership,
|
|
3661
|
-
toKindeRole,
|
|
3662
|
-
resetFactories,
|
|
3663
|
-
TestkitError,
|
|
3664
|
-
DEFAULT_ISSUER,
|
|
3665
|
-
DEFAULT_CLIENT_ID,
|
|
3666
|
-
DEFAULT_M2M_CLIENT_ID,
|
|
3667
|
-
DEFAULT_SCOPES,
|
|
3668
|
-
DEFAULT_AUTH_METHODS,
|
|
3669
|
-
INVALID_TOKEN_KINDS,
|
|
3670
|
-
KindeTestkit,
|
|
3671
|
-
principalFromClaims,
|
|
3672
|
-
getDefaultTestkit,
|
|
3673
|
-
createKindeToken,
|
|
3674
3395
|
ensureLocalCertificate,
|
|
3675
3396
|
createLocalCertificate,
|
|
3676
3397
|
resolveSeed,
|
|
@@ -3694,4 +3415,4 @@ export {
|
|
|
3694
3415
|
loadSeedFile,
|
|
3695
3416
|
startKindeTestkit
|
|
3696
3417
|
};
|
|
3697
|
-
//# sourceMappingURL=chunk-
|
|
3418
|
+
//# sourceMappingURL=chunk-CY75AADD.js.map
|