kinde-testkit 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +242 -12
- package/dist/chunk-33AHOLUN.js +183 -0
- package/dist/chunk-33AHOLUN.js.map +1 -0
- package/dist/chunk-GCOZVCZY.js +3430 -0
- package/dist/chunk-GCOZVCZY.js.map +1 -0
- package/dist/chunk-U2D47SCY.js +72 -0
- package/dist/chunk-U2D47SCY.js.map +1 -0
- package/dist/cli.js +178 -2849
- package/dist/cli.js.map +1 -0
- package/dist/cypress-support.js +119 -0
- package/dist/cypress-support.js.map +1 -0
- package/dist/cypress.cjs +4251 -0
- package/dist/cypress.d.cts +24 -0
- package/dist/cypress.d.ts +25 -0
- package/dist/cypress.js +23 -0
- package/dist/cypress.js.map +1 -0
- package/dist/handle-BERQZCyH.d.cts +32 -0
- package/dist/handle-Dh0UpIzG.d.ts +33 -0
- package/dist/index.cjs +2046 -101
- package/dist/index.d.cts +38 -463
- package/dist/index.d.ts +39 -463
- package/dist/index.js +90 -2822
- package/dist/index.js.map +1 -1
- package/dist/jest.cjs +4320 -0
- package/dist/jest.d.cts +17 -0
- package/dist/jest.d.ts +18 -0
- package/dist/jest.js +23 -0
- package/dist/jest.js.map +1 -0
- package/dist/playwright.d.ts +2 -54
- package/dist/server-BiODgeoB.d.ts +185 -0
- package/dist/server-ciWIscoQ.d.cts +579 -0
- package/dist/vitest.d.ts +7 -403
- package/dist/vitest.js +6 -2677
- package/dist/vitest.js.map +1 -1
- package/dist/webhooks-DJyCsbdF.d.ts +397 -0
- package/package.json +36 -4
- package/dist/index.cjs.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,2824 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
formatSpan,
|
|
4
|
+
inspectToken,
|
|
5
|
+
parseEnvFile,
|
|
6
|
+
runDoctor
|
|
7
|
+
} from "./chunk-33AHOLUN.js";
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_COVERAGE_DIRECTORY,
|
|
10
|
+
TestkitError,
|
|
11
|
+
clearCoverageDirectory,
|
|
12
|
+
ensureLocalCertificate,
|
|
13
|
+
findSeedFile,
|
|
14
|
+
formatCoverageReport,
|
|
15
|
+
loadSeedFile,
|
|
16
|
+
readCoverageDirectory,
|
|
17
|
+
startKindeTestkit
|
|
18
|
+
} from "./chunk-GCOZVCZY.js";
|
|
2
19
|
|
|
3
20
|
// src/cli.ts
|
|
4
|
-
import { spawnSync } from "child_process";
|
|
5
|
-
import { existsSync
|
|
6
|
-
import { resolve
|
|
7
|
-
import { parseArgs } from "util";
|
|
8
|
-
|
|
9
|
-
// src/errors.ts
|
|
10
|
-
var TestkitError = class extends Error {
|
|
11
|
-
code;
|
|
12
|
-
details;
|
|
13
|
-
constructor(code, message, details = []) {
|
|
14
|
-
super(details.length > 0 ? `${message}
|
|
15
|
-
|
|
16
|
-
${details.map((d) => ` - ${d}`).join("\n")}` : message);
|
|
17
|
-
this.name = "TestkitError";
|
|
18
|
-
this.code = code;
|
|
19
|
-
this.details = details;
|
|
20
|
-
}
|
|
21
|
-
toString() {
|
|
22
|
-
return `${this.code}
|
|
23
|
-
|
|
24
|
-
${this.message}`;
|
|
25
|
-
}
|
|
26
|
-
};
|
|
27
|
-
|
|
28
|
-
// src/server.ts
|
|
29
|
-
import { createServer } from "http";
|
|
30
|
-
import { createServer as createHttpsServer } from "https";
|
|
31
|
-
|
|
32
|
-
// src/certificate.ts
|
|
33
|
-
import { createHash, generateKeyPairSync, randomBytes, sign, X509Certificate } from "crypto";
|
|
34
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
35
|
-
import { join, resolve } from "path";
|
|
36
|
-
var CERT_FILE = "localhost-cert.pem";
|
|
37
|
-
var KEY_FILE = "localhost-key.pem";
|
|
38
|
-
var VALID_DAYS = 825;
|
|
39
|
-
function ensureLocalCertificate(directory = ".kinde-testkit") {
|
|
40
|
-
const dir = resolve(directory);
|
|
41
|
-
const certPath = join(dir, CERT_FILE);
|
|
42
|
-
const keyPath = join(dir, KEY_FILE);
|
|
43
|
-
if (existsSync(certPath) && existsSync(keyPath)) {
|
|
44
|
-
const cert3 = readFileSync(certPath, "utf8");
|
|
45
|
-
const key2 = readFileSync(keyPath, "utf8");
|
|
46
|
-
try {
|
|
47
|
-
if (new Date(new X509Certificate(cert3).validTo).getTime() > Date.now() + 864e5) {
|
|
48
|
-
return { cert: cert3, key: key2, certPath, keyPath, created: false };
|
|
49
|
-
}
|
|
50
|
-
} catch {
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
const { cert: cert2, key } = createLocalCertificate();
|
|
54
|
-
mkdirSync(dir, { recursive: true });
|
|
55
|
-
writeFileSync(certPath, cert2);
|
|
56
|
-
writeFileSync(keyPath, key, { mode: 384 });
|
|
57
|
-
writeFileSync(join(dir, ".gitignore"), "*\n");
|
|
58
|
-
return { cert: cert2, key, certPath, keyPath, created: true };
|
|
59
|
-
}
|
|
60
|
-
function createLocalCertificate() {
|
|
61
|
-
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
62
|
-
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
63
|
-
const keyId = createHash("sha1").update(subjectPublicKeyBits(spki)).digest();
|
|
64
|
-
const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
|
|
65
|
-
const now = Date.now();
|
|
66
|
-
const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
|
|
67
|
-
const serial = randomBytes(16);
|
|
68
|
-
serial[0] &= 127;
|
|
69
|
-
const extensions = seq(
|
|
70
|
-
seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
|
|
71
|
-
seq(oid("2.5.29.14"), octets(octets(keyId))),
|
|
72
|
-
seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
|
|
73
|
-
seq(
|
|
74
|
-
oid("2.5.29.17"),
|
|
75
|
-
octets(
|
|
76
|
-
seq(
|
|
77
|
-
tlv(130, Buffer.from("localhost")),
|
|
78
|
-
tlv(135, Buffer.from([127, 0, 0, 1])),
|
|
79
|
-
tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
|
|
80
|
-
)
|
|
81
|
-
)
|
|
82
|
-
)
|
|
83
|
-
);
|
|
84
|
-
const tbs = seq(
|
|
85
|
-
tlv(160, integer(Buffer.from([2]))),
|
|
86
|
-
integer(serial),
|
|
87
|
-
algorithm,
|
|
88
|
-
name,
|
|
89
|
-
seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
|
|
90
|
-
name,
|
|
91
|
-
spki,
|
|
92
|
-
tlv(163, extensions)
|
|
93
|
-
);
|
|
94
|
-
const signature = sign("sha256", tbs, privateKey);
|
|
95
|
-
const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
|
|
96
|
-
return {
|
|
97
|
-
cert: pem("CERTIFICATE", der),
|
|
98
|
-
key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
function subjectPublicKeyBits(spki) {
|
|
102
|
-
const outer = readTlv(spki, 0);
|
|
103
|
-
const algorithm = readTlv(spki, outer.start);
|
|
104
|
-
const bits = readTlv(spki, algorithm.end);
|
|
105
|
-
return spki.subarray(bits.start + 1, bits.end);
|
|
106
|
-
}
|
|
107
|
-
function readTlv(buf, offset) {
|
|
108
|
-
let len = buf[offset + 1];
|
|
109
|
-
let header = 2;
|
|
110
|
-
if (len & 128) {
|
|
111
|
-
const n = len & 127;
|
|
112
|
-
len = 0;
|
|
113
|
-
for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
|
|
114
|
-
header += n;
|
|
115
|
-
}
|
|
116
|
-
return { start: offset + header, end: offset + header + len };
|
|
117
|
-
}
|
|
118
|
-
function tlv(tag, content) {
|
|
119
|
-
return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
|
|
120
|
-
}
|
|
121
|
-
function length(n) {
|
|
122
|
-
if (n < 128) return Buffer.from([n]);
|
|
123
|
-
const bytes = [];
|
|
124
|
-
while (n > 0) {
|
|
125
|
-
bytes.unshift(n & 255);
|
|
126
|
-
n >>= 8;
|
|
127
|
-
}
|
|
128
|
-
return Buffer.from([128 | bytes.length, ...bytes]);
|
|
129
|
-
}
|
|
130
|
-
function seq(...items) {
|
|
131
|
-
return tlv(48, Buffer.concat(items));
|
|
132
|
-
}
|
|
133
|
-
function set(...items) {
|
|
134
|
-
return tlv(49, Buffer.concat(items));
|
|
135
|
-
}
|
|
136
|
-
function octets(content) {
|
|
137
|
-
return tlv(4, content);
|
|
138
|
-
}
|
|
139
|
-
function integer(bytes) {
|
|
140
|
-
return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
|
|
141
|
-
}
|
|
142
|
-
function oid(dotted) {
|
|
143
|
-
const parts = dotted.split(".").map(Number);
|
|
144
|
-
const bytes = [parts[0] * 40 + parts[1]];
|
|
145
|
-
for (const part of parts.slice(2)) {
|
|
146
|
-
const chunk = [part & 127];
|
|
147
|
-
let value = part >> 7;
|
|
148
|
-
while (value > 0) {
|
|
149
|
-
chunk.unshift(value & 127 | 128);
|
|
150
|
-
value >>= 7;
|
|
151
|
-
}
|
|
152
|
-
bytes.push(...chunk);
|
|
153
|
-
}
|
|
154
|
-
return tlv(6, Buffer.from(bytes));
|
|
155
|
-
}
|
|
156
|
-
function utcTime(date) {
|
|
157
|
-
const iso = date.toISOString();
|
|
158
|
-
const value = `${iso.slice(2, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}${iso.slice(11, 13)}${iso.slice(14, 16)}${iso.slice(17, 19)}Z`;
|
|
159
|
-
return tlv(23, Buffer.from(value));
|
|
160
|
-
}
|
|
161
|
-
function pem(label, der) {
|
|
162
|
-
const body = der.toString("base64").match(/.{1,64}/g).join("\n");
|
|
163
|
-
return `-----BEGIN ${label}-----
|
|
164
|
-
${body}
|
|
165
|
-
-----END ${label}-----
|
|
166
|
-
`;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
// src/testkit.ts
|
|
170
|
-
import { randomUUID } from "crypto";
|
|
171
|
-
import {
|
|
172
|
-
SignJWT,
|
|
173
|
-
base64url,
|
|
174
|
-
calculateJwkThumbprint,
|
|
175
|
-
exportJWK,
|
|
176
|
-
generateKeyPair,
|
|
177
|
-
jwtVerify
|
|
178
|
-
} from "jose";
|
|
179
|
-
|
|
180
|
-
// src/ids.ts
|
|
181
|
-
import { createHash as createHash2 } from "crypto";
|
|
182
|
-
var counters = /* @__PURE__ */ new Map();
|
|
183
|
-
function stableId(prefix, seed) {
|
|
184
|
-
return `${prefix}_${createHash2("sha256").update(seed).digest("hex").slice(0, 16)}`;
|
|
185
|
-
}
|
|
186
|
-
function nextSequence(prefix) {
|
|
187
|
-
const next = (counters.get(prefix) ?? 0) + 1;
|
|
188
|
-
counters.set(prefix, next);
|
|
189
|
-
return next;
|
|
190
|
-
}
|
|
191
|
-
function slug(value) {
|
|
192
|
-
return value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
193
|
-
}
|
|
194
|
-
function titleCase(value) {
|
|
195
|
-
return value.replace(/^org_/, "").split(/[_\-\s]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
// src/factories.ts
|
|
199
|
-
function createKindeUser(options = {}) {
|
|
200
|
-
const email = options.email === void 0 ? `user-${nextSequence("user")}@example.test` : options.email;
|
|
201
|
-
const id = options.id ?? (email ? stableId("kp", email) : `kp_test_${nextSequence("kp")}`);
|
|
202
|
-
return {
|
|
203
|
-
id,
|
|
204
|
-
email,
|
|
205
|
-
emailVerified: options.emailVerified ?? email !== null,
|
|
206
|
-
givenName: options.givenName === void 0 ? null : options.givenName,
|
|
207
|
-
familyName: options.familyName === void 0 ? null : options.familyName,
|
|
208
|
-
picture: options.picture === void 0 ? null : options.picture,
|
|
209
|
-
claims: { ...options.claims ?? {} }
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
function createKindeOrganization(options = {}) {
|
|
213
|
-
const code = options.code ?? (options.name ? `org_${slug(options.name)}` : `org_test_${nextSequence("org")}`);
|
|
214
|
-
return {
|
|
215
|
-
code,
|
|
216
|
-
name: options.name ?? titleCase(code),
|
|
217
|
-
metadata: { ...options.metadata ?? {} }
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
function createMembership(options) {
|
|
221
|
-
return {
|
|
222
|
-
userId: options.userId,
|
|
223
|
-
organizationCode: options.organizationCode,
|
|
224
|
-
roles: unique(options.roles ?? []),
|
|
225
|
-
permissions: unique(options.permissions ?? [])
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
function toKindeRole(role) {
|
|
229
|
-
if (typeof role !== "string") return role;
|
|
230
|
-
return { id: stableId("role", role), key: role, name: titleCase(role) };
|
|
231
|
-
}
|
|
232
|
-
function unique(values) {
|
|
233
|
-
return [...new Set(values)];
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// src/duration.ts
|
|
237
|
-
var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
|
|
238
|
-
function toSeconds(value) {
|
|
239
|
-
if (typeof value === "number") {
|
|
240
|
-
if (!Number.isFinite(value) || value < 0) throw invalid(String(value));
|
|
241
|
-
return Math.floor(value);
|
|
242
|
-
}
|
|
243
|
-
const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
|
|
244
|
-
if (!match) {
|
|
245
|
-
if (/^\d+$/.test(value.trim())) return Number(value.trim());
|
|
246
|
-
throw invalid(value);
|
|
247
|
-
}
|
|
248
|
-
return Number(match[1]) * UNITS[match[2]];
|
|
249
|
-
}
|
|
250
|
-
function invalid(value) {
|
|
251
|
-
return new TestkitError(
|
|
252
|
-
"INVALID_DURATION",
|
|
253
|
-
`"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
|
|
254
|
-
);
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
// src/testkit.ts
|
|
258
|
-
var DEFAULT_ISSUER = "http://localhost:4400";
|
|
259
|
-
var DEFAULT_CLIENT_ID = "kinde_testkit_client";
|
|
260
|
-
var DEFAULT_M2M_CLIENT_ID = "kinde_testkit_m2m";
|
|
261
|
-
var DEFAULT_SCOPES = ["openid", "profile", "email", "offline"];
|
|
262
|
-
var DEFAULT_AUTH_METHODS = ["email"];
|
|
263
|
-
var INVALID_TOKEN_KINDS = [
|
|
264
|
-
"expired",
|
|
265
|
-
"wrong-issuer",
|
|
266
|
-
"wrong-audience",
|
|
267
|
-
"missing-subject",
|
|
268
|
-
"missing-organization",
|
|
269
|
-
"missing-permissions",
|
|
270
|
-
"future-iat",
|
|
271
|
-
"bad-signature",
|
|
272
|
-
"unknown-key",
|
|
273
|
-
"unsigned"
|
|
274
|
-
];
|
|
275
|
-
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
276
|
-
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
277
|
-
var KindeTestkit = class _KindeTestkit {
|
|
278
|
-
issuer;
|
|
279
|
-
audience;
|
|
280
|
-
clientId;
|
|
281
|
-
accessTokenExpiresIn;
|
|
282
|
-
idTokenExpiresIn;
|
|
283
|
-
clock;
|
|
284
|
-
signingKey;
|
|
285
|
-
strangerKey = null;
|
|
286
|
-
static async create(options = {}) {
|
|
287
|
-
return new _KindeTestkit(options, await createSigningKey("kinde-testkit"));
|
|
288
|
-
}
|
|
289
|
-
constructor(options, signingKey) {
|
|
290
|
-
this.issuer = trimSlash(options.issuer ?? DEFAULT_ISSUER);
|
|
291
|
-
this.audience = toArray(options.audience);
|
|
292
|
-
this.clientId = options.clientId ?? DEFAULT_CLIENT_ID;
|
|
293
|
-
this.accessTokenExpiresIn = options.accessTokenExpiresIn ?? "24h";
|
|
294
|
-
this.idTokenExpiresIn = options.idTokenExpiresIn ?? "1h";
|
|
295
|
-
this.clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
296
|
-
this.signingKey = signingKey;
|
|
297
|
-
warnIfRealKindeDomain(this.issuer);
|
|
298
|
-
}
|
|
299
|
-
get jwksUri() {
|
|
300
|
-
return `${this.issuer}/.well-known/jwks`;
|
|
301
|
-
}
|
|
302
|
-
get keyId() {
|
|
303
|
-
return this.signingKey.kid;
|
|
304
|
-
}
|
|
305
|
-
get accessTokenLifetime() {
|
|
306
|
-
return toSeconds(this.accessTokenExpiresIn);
|
|
307
|
-
}
|
|
308
|
-
async verify(token2) {
|
|
309
|
-
const { payload } = await jwtVerify(token2, this.signingKey.publicKey, {
|
|
310
|
-
issuer: this.issuer,
|
|
311
|
-
algorithms: ["RS256"]
|
|
312
|
-
});
|
|
313
|
-
return payload;
|
|
314
|
-
}
|
|
315
|
-
jwks() {
|
|
316
|
-
return { keys: [{ ...this.signingKey.publicJwk }] };
|
|
317
|
-
}
|
|
318
|
-
async token(options = {}) {
|
|
319
|
-
const now = this.clock();
|
|
320
|
-
const payload = {
|
|
321
|
-
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
322
|
-
aud: [...options.audience ?? this.audience],
|
|
323
|
-
auth_time: options.authTime ?? now,
|
|
324
|
-
azp: options.clientId ?? this.clientId,
|
|
325
|
-
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
326
|
-
iat: now,
|
|
327
|
-
iss: this.issuer,
|
|
328
|
-
jti: randomUUID(),
|
|
329
|
-
scp: [...options.scopes ?? DEFAULT_SCOPES],
|
|
330
|
-
sub: options.subject ?? stableId("kp", "default-test-user")
|
|
331
|
-
};
|
|
332
|
-
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
333
|
-
if (options.roles !== void 0) payload.roles = options.roles.map(toKindeRole);
|
|
334
|
-
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
335
|
-
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
336
|
-
Object.assign(payload, options.claims ?? {});
|
|
337
|
-
return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
|
|
338
|
-
}
|
|
339
|
-
async m2mToken(options = {}) {
|
|
340
|
-
const now = this.clock();
|
|
341
|
-
const requested = [...options.scopes ?? []];
|
|
342
|
-
const granted = [...options.grantedScopes ?? requested];
|
|
343
|
-
const payload = {
|
|
344
|
-
aud: [...options.audience ?? this.audience],
|
|
345
|
-
azp: options.clientId ?? DEFAULT_M2M_CLIENT_ID,
|
|
346
|
-
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
347
|
-
gty: ["client_credentials"],
|
|
348
|
-
iat: now,
|
|
349
|
-
iss: this.issuer,
|
|
350
|
-
jti: randomUUID(),
|
|
351
|
-
scope: granted.join(" "),
|
|
352
|
-
scp: requested,
|
|
353
|
-
v: "2"
|
|
354
|
-
};
|
|
355
|
-
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
356
|
-
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
357
|
-
Object.assign(payload, options.claims ?? {});
|
|
358
|
-
return this.sign(applyInvalidClaims(payload, options.invalid, now), options.invalid);
|
|
359
|
-
}
|
|
360
|
-
async tokenFor(scenario, overrides = {}) {
|
|
361
|
-
if (scenario.kind === "unauthenticated") return null;
|
|
362
|
-
return this.token({
|
|
363
|
-
subject: scenario.user.id,
|
|
364
|
-
organizationCode: scenario.organization?.code ?? null,
|
|
365
|
-
roles: scenario.roles.length > 0 ? scenario.roles : void 0,
|
|
366
|
-
permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
|
|
367
|
-
...overrides,
|
|
368
|
-
claims: { ...scenario.claims, ...overrides.claims ?? {} }
|
|
369
|
-
});
|
|
370
|
-
}
|
|
371
|
-
async idTokenFor(scenario, options = {}) {
|
|
372
|
-
if (scenario.kind === "unauthenticated") return null;
|
|
373
|
-
const { user, organization } = scenario;
|
|
374
|
-
const now = this.clock();
|
|
375
|
-
const authTime = options.authTime ?? now;
|
|
376
|
-
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
377
|
-
const clientId = options.clientId ?? this.clientId;
|
|
378
|
-
const payload = {
|
|
379
|
-
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
380
|
-
aud: [clientId],
|
|
381
|
-
auth_time: authTime,
|
|
382
|
-
azp: clientId,
|
|
383
|
-
email: user.email,
|
|
384
|
-
email_verified: user.emailVerified,
|
|
385
|
-
exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
|
|
386
|
-
family_name: user.familyName,
|
|
387
|
-
given_name: user.givenName,
|
|
388
|
-
iat: now,
|
|
389
|
-
iss: this.issuer,
|
|
390
|
-
jti: randomUUID(),
|
|
391
|
-
name: name || null,
|
|
392
|
-
nonce: options.nonce,
|
|
393
|
-
org_codes: organization ? [organization.code] : void 0,
|
|
394
|
-
picture: user.picture,
|
|
395
|
-
rat: authTime,
|
|
396
|
-
sub: user.id,
|
|
397
|
-
updated_at: now,
|
|
398
|
-
...user.claims
|
|
399
|
-
};
|
|
400
|
-
for (const key of Object.keys(payload)) {
|
|
401
|
-
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
402
|
-
}
|
|
403
|
-
return this.sign(payload);
|
|
404
|
-
}
|
|
405
|
-
async headersFor(scenario, overrides = {}) {
|
|
406
|
-
const token2 = await this.tokenFor(scenario, overrides);
|
|
407
|
-
return token2 ? { authorization: `Bearer ${token2}` } : {};
|
|
408
|
-
}
|
|
409
|
-
principalFor(scenario) {
|
|
410
|
-
if (scenario.kind === "unauthenticated") return null;
|
|
411
|
-
return scenarioPrincipal(scenario, this.issuer);
|
|
412
|
-
}
|
|
413
|
-
async signPayload(payload, invalid2) {
|
|
414
|
-
return this.sign(payload, invalid2);
|
|
415
|
-
}
|
|
416
|
-
async sign(payload, invalid2) {
|
|
417
|
-
if (invalid2 === "unsigned") {
|
|
418
|
-
const header = base64url.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
419
|
-
return `${header}.${base64url.encode(JSON.stringify(payload))}.`;
|
|
420
|
-
}
|
|
421
|
-
const key = invalid2 === "unknown-key" ? await this.stranger() : this.signingKey;
|
|
422
|
-
const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
|
|
423
|
-
return invalid2 === "bad-signature" ? tamperSignature(jwt) : jwt;
|
|
424
|
-
}
|
|
425
|
-
stranger() {
|
|
426
|
-
this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
|
|
427
|
-
return this.strangerKey;
|
|
428
|
-
}
|
|
429
|
-
};
|
|
430
|
-
function scenarioPrincipal(scenario, issuer) {
|
|
431
|
-
return {
|
|
432
|
-
type: "user",
|
|
433
|
-
subject: scenario.user.id,
|
|
434
|
-
issuer,
|
|
435
|
-
organization: scenario.organization ? { code: scenario.organization.code } : null,
|
|
436
|
-
roles: [...scenario.roles],
|
|
437
|
-
permissions: [...scenario.permissions],
|
|
438
|
-
claims: { ...scenario.claims }
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
function applyInvalidClaims(payload, invalid2, now) {
|
|
442
|
-
const next = { ...payload };
|
|
443
|
-
switch (invalid2) {
|
|
444
|
-
case "expired":
|
|
445
|
-
next.iat = now - 7200;
|
|
446
|
-
next.exp = now - 3600;
|
|
447
|
-
break;
|
|
448
|
-
case "future-iat":
|
|
449
|
-
next.iat = now + 3600;
|
|
450
|
-
next.exp = now + 7200;
|
|
451
|
-
break;
|
|
452
|
-
case "wrong-issuer":
|
|
453
|
-
next.iss = WRONG_ISSUER;
|
|
454
|
-
break;
|
|
455
|
-
case "wrong-audience":
|
|
456
|
-
next.aud = [WRONG_AUDIENCE];
|
|
457
|
-
break;
|
|
458
|
-
case "missing-subject":
|
|
459
|
-
delete next.sub;
|
|
460
|
-
break;
|
|
461
|
-
case "missing-organization":
|
|
462
|
-
delete next.org_code;
|
|
463
|
-
break;
|
|
464
|
-
case "missing-permissions":
|
|
465
|
-
next.permissions = [];
|
|
466
|
-
break;
|
|
467
|
-
default:
|
|
468
|
-
break;
|
|
469
|
-
}
|
|
470
|
-
return next;
|
|
471
|
-
}
|
|
472
|
-
async function createSigningKey(prefix) {
|
|
473
|
-
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
|
474
|
-
const jwk = await exportJWK(publicKey);
|
|
475
|
-
const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
|
|
476
|
-
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
477
|
-
}
|
|
478
|
-
function tamperSignature(jwt) {
|
|
479
|
-
const [header, payload, signature] = jwt.split(".");
|
|
480
|
-
const bytes = base64url.decode(signature);
|
|
481
|
-
bytes[0] = (bytes[0] ?? 0) ^ 255;
|
|
482
|
-
return `${header}.${payload}.${base64url.encode(bytes)}`;
|
|
483
|
-
}
|
|
484
|
-
function toArray(value) {
|
|
485
|
-
if (value === void 0) return [];
|
|
486
|
-
return Array.isArray(value) ? [...value] : [value];
|
|
487
|
-
}
|
|
488
|
-
function trimSlash(value) {
|
|
489
|
-
return value.replace(/\/+$/, "");
|
|
490
|
-
}
|
|
491
|
-
function warnIfRealKindeDomain(issuer) {
|
|
492
|
-
if (/^https:\/\/[^/]+\.kinde\.com$/i.test(issuer)) {
|
|
493
|
-
process.emitWarning(
|
|
494
|
-
`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.`,
|
|
495
|
-
{ code: "KINDE_TESTKIT_REAL_ISSUER" }
|
|
496
|
-
);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
// src/login-page.ts
|
|
501
|
-
var STYLE = `
|
|
502
|
-
:root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--warn:#8a5a00;--warn-bg:#fff6e0}
|
|
503
|
-
@media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--warn:#f0c46a;--warn-bg:#2a2210}}
|
|
504
|
-
*{box-sizing:border-box}
|
|
505
|
-
body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;padding:24px}
|
|
506
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
507
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
508
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
509
|
-
p{margin:0;color:var(--muted)}
|
|
510
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
511
|
-
form{margin:0}
|
|
512
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
513
|
-
input[type=email]{width:100%;height:42px;padding:0 12px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit}
|
|
514
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
515
|
-
.primary{margin-top:12px;width:100%;height:42px;border:0;border-radius:8px;background:var(--accent);color:var(--accent-ink);font-family:inherit;font-size:15px;font-weight:600;cursor:pointer}
|
|
516
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
517
|
-
.list{display:grid;gap:8px}
|
|
518
|
-
.option{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;padding:11px 12px;border:1px solid var(--line);border-radius:8px;background:transparent;color:var(--ink);font:inherit;cursor:pointer}
|
|
519
|
-
.option:hover{border-color:var(--muted)}
|
|
520
|
-
.option strong{display:block;font-weight:500}
|
|
521
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
522
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
523
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
524
|
-
`;
|
|
525
|
-
function escapeHtml(value) {
|
|
526
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
527
|
-
}
|
|
528
|
-
function layout(title, body) {
|
|
529
|
-
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body><main><div class="brand">kinde-testkit</div>${body}</main></body></html>`;
|
|
530
|
-
}
|
|
531
|
-
function displayName(user) {
|
|
532
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
533
|
-
}
|
|
534
|
-
function renderSignIn(options) {
|
|
535
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
536
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
537
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
538
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
539
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
540
|
-
return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag}</span></button>`;
|
|
541
|
-
}).join("");
|
|
542
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
543
|
-
return layout(
|
|
544
|
-
"Sign in",
|
|
545
|
-
`<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>`
|
|
546
|
-
);
|
|
547
|
-
}
|
|
548
|
-
function renderOrganizationPicker(options) {
|
|
549
|
-
const choices = options.organizations.map(
|
|
550
|
-
(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>`
|
|
551
|
-
).join("");
|
|
552
|
-
return layout(
|
|
553
|
-
"Choose an organization",
|
|
554
|
-
`<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)}"><div class="list" style="margin-top:20px">${choices}</div></form>`
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
function renderMessage(title, message) {
|
|
558
|
-
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
// src/seed.ts
|
|
562
|
-
function roleRecord(key, extra = {}) {
|
|
563
|
-
return {
|
|
564
|
-
id: stableId("role", key),
|
|
565
|
-
key,
|
|
566
|
-
name: extra.name ?? titleCase(key),
|
|
567
|
-
description: extra.description ?? null,
|
|
568
|
-
isDefault: extra.isDefault ?? false,
|
|
569
|
-
permissions: [...extra.permissions ?? []]
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
function permissionRecord(key, extra = {}) {
|
|
573
|
-
return {
|
|
574
|
-
id: stableId("perm", key),
|
|
575
|
-
key,
|
|
576
|
-
name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
|
|
577
|
-
description: extra.description ?? null
|
|
578
|
-
};
|
|
579
|
-
}
|
|
580
|
-
function effectivePermissions(seed, membership) {
|
|
581
|
-
if (!membership) return [];
|
|
582
|
-
const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
|
|
583
|
-
return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
|
|
584
|
-
}
|
|
585
|
-
function resolveSeed(input) {
|
|
586
|
-
const problems = [];
|
|
587
|
-
if (!isRecord(input)) {
|
|
588
|
-
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
589
|
-
}
|
|
590
|
-
const rawUsers = listOf(input.users, "users", problems);
|
|
591
|
-
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
592
|
-
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
593
|
-
const rawApplications = listOf(input.applications, "applications", problems);
|
|
594
|
-
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
595
|
-
const rawRoles = listOf(input.roles, "roles", problems);
|
|
596
|
-
const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
|
|
597
|
-
const rawPlans = listOf(input.plans, "plans", problems);
|
|
598
|
-
const rawPermissions = listOf(input.permissions, "permissions", problems);
|
|
599
|
-
const webhooks = [];
|
|
600
|
-
rawWebhooks.forEach((raw, index) => {
|
|
601
|
-
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
602
|
-
problems.push(`webhooks[${index}] needs an http or https "url".`);
|
|
603
|
-
return;
|
|
604
|
-
}
|
|
605
|
-
if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
|
|
606
|
-
problems.push(`webhooks[${index}].events must be a list of event type names.`);
|
|
607
|
-
return;
|
|
608
|
-
}
|
|
609
|
-
webhooks.push({ url: raw.url, events: raw.events });
|
|
610
|
-
});
|
|
611
|
-
const users = [];
|
|
612
|
-
rawUsers.forEach((raw, index) => {
|
|
613
|
-
if (!isRecord(raw) || typeof raw.id !== "string" || raw.id.length === 0) {
|
|
614
|
-
problems.push(`users[${index}] needs a string "id".`);
|
|
615
|
-
return;
|
|
616
|
-
}
|
|
617
|
-
if (users.some((user) => user.id === raw.id)) {
|
|
618
|
-
problems.push(`users[${index}] repeats the id "${raw.id}".`);
|
|
619
|
-
return;
|
|
620
|
-
}
|
|
621
|
-
users.push(createKindeUser(raw));
|
|
622
|
-
});
|
|
623
|
-
const organizations = [];
|
|
624
|
-
rawOrganizations.forEach((raw, index) => {
|
|
625
|
-
if (!isRecord(raw) || typeof raw.code !== "string" || raw.code.length === 0) {
|
|
626
|
-
problems.push(`organizations[${index}] needs a string "code".`);
|
|
627
|
-
return;
|
|
628
|
-
}
|
|
629
|
-
if (organizations.some((org) => org.code === raw.code)) {
|
|
630
|
-
problems.push(`organizations[${index}] repeats the code "${raw.code}".`);
|
|
631
|
-
return;
|
|
632
|
-
}
|
|
633
|
-
organizations.push(createKindeOrganization(raw));
|
|
634
|
-
});
|
|
635
|
-
const memberships = [];
|
|
636
|
-
rawMemberships.forEach((raw, index) => {
|
|
637
|
-
if (!isRecord(raw) || typeof raw.user !== "string" || typeof raw.organization !== "string") {
|
|
638
|
-
problems.push(`memberships[${index}] needs string "user" and "organization" fields.`);
|
|
639
|
-
return;
|
|
640
|
-
}
|
|
641
|
-
const user = findUser(users, raw.user);
|
|
642
|
-
if (!user) problems.push(`memberships[${index}] points to an unknown user "${raw.user}".`);
|
|
643
|
-
if (!organizations.some((org) => org.code === raw.organization)) {
|
|
644
|
-
problems.push(`memberships[${index}] points to an unknown organization "${raw.organization}".`);
|
|
645
|
-
}
|
|
646
|
-
for (const field of ["roles", "permissions"]) {
|
|
647
|
-
const value = raw[field];
|
|
648
|
-
if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
|
|
649
|
-
problems.push(`memberships[${index}].${field} must be a list of strings.`);
|
|
650
|
-
}
|
|
651
|
-
}
|
|
652
|
-
if (!user) return;
|
|
653
|
-
if (memberships.some((m) => m.userId === user.id && m.organizationCode === raw.organization)) {
|
|
654
|
-
problems.push(`memberships[${index}] repeats ${user.id} in ${raw.organization}.`);
|
|
655
|
-
return;
|
|
656
|
-
}
|
|
657
|
-
memberships.push(
|
|
658
|
-
createMembership({
|
|
659
|
-
userId: user.id,
|
|
660
|
-
organizationCode: raw.organization,
|
|
661
|
-
roles: raw.roles,
|
|
662
|
-
permissions: raw.permissions
|
|
663
|
-
})
|
|
664
|
-
);
|
|
665
|
-
});
|
|
666
|
-
const applications = [];
|
|
667
|
-
rawApplications.forEach((raw, index) => {
|
|
668
|
-
if (!isRecord(raw) || typeof raw.clientId !== "string" || raw.clientId.length === 0) {
|
|
669
|
-
problems.push(`applications[${index}] needs a string "clientId".`);
|
|
670
|
-
return;
|
|
671
|
-
}
|
|
672
|
-
if (applications.some((app) => app.clientId === raw.clientId)) {
|
|
673
|
-
problems.push(`applications[${index}] repeats the clientId "${raw.clientId}".`);
|
|
674
|
-
return;
|
|
675
|
-
}
|
|
676
|
-
if (raw.clientSecret !== void 0 && typeof raw.clientSecret !== "string") {
|
|
677
|
-
problems.push(`applications[${index}].clientSecret must be a string.`);
|
|
678
|
-
}
|
|
679
|
-
if (raw.organization !== void 0 && !organizations.some((org) => org.code === raw.organization)) {
|
|
680
|
-
problems.push(`applications[${index}] points to an unknown organization "${String(raw.organization)}".`);
|
|
681
|
-
}
|
|
682
|
-
for (const field of ["scopes", "permissions"]) {
|
|
683
|
-
const value = raw[field];
|
|
684
|
-
if (value !== void 0 && (!Array.isArray(value) || value.some((v) => typeof v !== "string"))) {
|
|
685
|
-
problems.push(`applications[${index}].${field} must be a list of strings.`);
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
const audience = raw.audience;
|
|
689
|
-
applications.push({
|
|
690
|
-
clientId: raw.clientId,
|
|
691
|
-
clientSecret: typeof raw.clientSecret === "string" ? raw.clientSecret : null,
|
|
692
|
-
name: typeof raw.name === "string" ? raw.name : raw.clientId,
|
|
693
|
-
organizationCode: typeof raw.organization === "string" ? raw.organization : null,
|
|
694
|
-
scopes: Array.isArray(raw.scopes) ? raw.scopes : null,
|
|
695
|
-
permissions: Array.isArray(raw.permissions) ? raw.permissions : null,
|
|
696
|
-
audience: typeof audience === "string" ? [audience] : Array.isArray(audience) ? audience : null
|
|
697
|
-
});
|
|
698
|
-
});
|
|
699
|
-
if (problems.length > 0) {
|
|
700
|
-
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
701
|
-
}
|
|
702
|
-
const permissions = [];
|
|
703
|
-
rawPermissions.forEach((raw, index) => {
|
|
704
|
-
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
705
|
-
problems.push(`permissions[${index}] needs a string "key".`);
|
|
706
|
-
return;
|
|
707
|
-
}
|
|
708
|
-
if (permissions.some((p) => p.key === raw.key)) {
|
|
709
|
-
problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
|
|
710
|
-
return;
|
|
711
|
-
}
|
|
712
|
-
permissions.push(
|
|
713
|
-
permissionRecord(raw.key, {
|
|
714
|
-
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
715
|
-
description: typeof raw.description === "string" ? raw.description : void 0
|
|
716
|
-
})
|
|
717
|
-
);
|
|
718
|
-
});
|
|
719
|
-
const roles = [];
|
|
720
|
-
rawRoles.forEach((raw, index) => {
|
|
721
|
-
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
722
|
-
problems.push(`roles[${index}] needs a string "key".`);
|
|
723
|
-
return;
|
|
724
|
-
}
|
|
725
|
-
if (roles.some((r) => r.key === raw.key)) {
|
|
726
|
-
problems.push(`roles[${index}] repeats the key "${raw.key}".`);
|
|
727
|
-
return;
|
|
728
|
-
}
|
|
729
|
-
if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
|
|
730
|
-
problems.push(`roles[${index}].permissions must be a list of permission keys.`);
|
|
731
|
-
return;
|
|
732
|
-
}
|
|
733
|
-
roles.push(
|
|
734
|
-
roleRecord(raw.key, {
|
|
735
|
-
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
736
|
-
description: typeof raw.description === "string" ? raw.description : void 0,
|
|
737
|
-
isDefault: raw.isDefault === true,
|
|
738
|
-
permissions: raw.permissions ?? []
|
|
739
|
-
})
|
|
740
|
-
);
|
|
741
|
-
});
|
|
742
|
-
if (problems.length > 0) {
|
|
743
|
-
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
744
|
-
}
|
|
745
|
-
const featureFlags = [];
|
|
746
|
-
rawFlags.forEach((raw, index) => {
|
|
747
|
-
if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
|
|
748
|
-
problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
|
|
749
|
-
return;
|
|
750
|
-
}
|
|
751
|
-
const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
|
|
752
|
-
featureFlags.push({
|
|
753
|
-
id: stableId("flag", raw.key),
|
|
754
|
-
key: raw.key,
|
|
755
|
-
name: typeof raw.name === "string" ? raw.name : raw.key,
|
|
756
|
-
type,
|
|
757
|
-
value: raw.value,
|
|
758
|
-
organizations: isRecord(raw.organizations) ? raw.organizations : {}
|
|
759
|
-
});
|
|
760
|
-
});
|
|
761
|
-
const plans = [];
|
|
762
|
-
rawPlans.forEach((raw, index) => {
|
|
763
|
-
if (!isRecord(raw) || typeof raw.key !== "string") {
|
|
764
|
-
problems.push(`plans[${index}] needs a string "key".`);
|
|
765
|
-
return;
|
|
766
|
-
}
|
|
767
|
-
const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
|
|
768
|
-
plans.push({
|
|
769
|
-
key: raw.key,
|
|
770
|
-
name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
|
|
771
|
-
subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
|
|
772
|
-
subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
773
|
-
entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
|
|
774
|
-
id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
|
|
775
|
-
featureKey: e.featureKey,
|
|
776
|
-
featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
|
|
777
|
-
priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
|
|
778
|
-
fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
|
|
779
|
-
unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
|
|
780
|
-
limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
|
|
781
|
-
limitMin: typeof e.limitMin === "number" ? e.limitMin : null
|
|
782
|
-
}))
|
|
783
|
-
});
|
|
784
|
-
});
|
|
785
|
-
const userProperties = {};
|
|
786
|
-
rawUsers.forEach((raw) => {
|
|
787
|
-
if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
|
|
788
|
-
userProperties[raw.id] = raw.properties;
|
|
789
|
-
}
|
|
790
|
-
});
|
|
791
|
-
if (problems.length > 0) {
|
|
792
|
-
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
793
|
-
}
|
|
794
|
-
const usedRoles = new Set(memberships.flatMap((m) => m.roles));
|
|
795
|
-
for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
|
|
796
|
-
const usedPermissions = /* @__PURE__ */ new Set([
|
|
797
|
-
...memberships.flatMap((m) => m.permissions),
|
|
798
|
-
...roles.flatMap((r) => r.permissions),
|
|
799
|
-
...applications.flatMap((a) => a.permissions ?? [])
|
|
800
|
-
]);
|
|
801
|
-
for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
|
|
802
|
-
return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
|
|
803
|
-
}
|
|
804
|
-
function findUser(users, ref) {
|
|
805
|
-
const needle = ref.toLowerCase();
|
|
806
|
-
return users.find((user) => user.id === ref || user.email?.toLowerCase() === needle);
|
|
807
|
-
}
|
|
808
|
-
function seedScenario(seed, ref) {
|
|
809
|
-
const user = findUser(seed.users, ref.user);
|
|
810
|
-
if (!user) {
|
|
811
|
-
throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${ref.user}".`, [
|
|
812
|
-
`Known users: ${seed.users.map((u) => u.email ?? u.id).join(", ") || "none"}`
|
|
813
|
-
]);
|
|
814
|
-
}
|
|
815
|
-
const userMemberships = seed.memberships.filter((m) => m.userId === user.id);
|
|
816
|
-
let membership;
|
|
817
|
-
if (ref.organization) {
|
|
818
|
-
if (!seed.organizations.some((org) => org.code === ref.organization)) {
|
|
819
|
-
throw new TestkitError(
|
|
820
|
-
"SEED_UNKNOWN_ORGANIZATION",
|
|
821
|
-
`No seeded organization has the code "${ref.organization}".`
|
|
822
|
-
);
|
|
823
|
-
}
|
|
824
|
-
membership = userMemberships.find((m) => m.organizationCode === ref.organization);
|
|
825
|
-
if (!membership) {
|
|
826
|
-
throw new TestkitError(
|
|
827
|
-
"SEED_NO_MEMBERSHIP",
|
|
828
|
-
`${user.email ?? user.id} is not a member of ${ref.organization}, so Kinde would not issue a token for that organization.`,
|
|
829
|
-
[`Member of: ${userMemberships.map((m) => m.organizationCode).join(", ") || "no organizations"}`]
|
|
830
|
-
);
|
|
831
|
-
}
|
|
832
|
-
} else if (userMemberships.length === 1) {
|
|
833
|
-
membership = userMemberships[0];
|
|
834
|
-
} else if (userMemberships.length > 1) {
|
|
835
|
-
throw new TestkitError(
|
|
836
|
-
"INVALID_REQUEST",
|
|
837
|
-
`${user.email ?? user.id} belongs to ${userMemberships.length} organizations. Choose the active one.`,
|
|
838
|
-
[`Organizations: ${userMemberships.map((m) => m.organizationCode).join(", ")}`]
|
|
839
|
-
);
|
|
840
|
-
}
|
|
841
|
-
const organization = membership ? seed.organizations.find((org) => org.code === membership.organizationCode) ?? null : null;
|
|
842
|
-
return {
|
|
843
|
-
kind: "authenticated",
|
|
844
|
-
user,
|
|
845
|
-
organization,
|
|
846
|
-
roles: [...membership?.roles ?? []],
|
|
847
|
-
permissions: effectivePermissions(seed, membership),
|
|
848
|
-
claims: {}
|
|
849
|
-
};
|
|
850
|
-
}
|
|
851
|
-
function listOf(value, field, problems) {
|
|
852
|
-
if (value === void 0) return [];
|
|
853
|
-
if (!Array.isArray(value)) {
|
|
854
|
-
problems.push(`"${field}" must be a list.`);
|
|
855
|
-
return [];
|
|
856
|
-
}
|
|
857
|
-
return value;
|
|
858
|
-
}
|
|
859
|
-
function isRecord(value) {
|
|
860
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
861
|
-
}
|
|
862
|
-
function featureFlagsFor(seed, organizationCode) {
|
|
863
|
-
if (seed.featureFlags.length === 0) return void 0;
|
|
864
|
-
const claim = {};
|
|
865
|
-
for (const flag of seed.featureFlags) {
|
|
866
|
-
const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
|
|
867
|
-
claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
|
|
868
|
-
}
|
|
869
|
-
return claim;
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
// src/oauth.ts
|
|
873
|
-
import { createHash as createHash3, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
|
|
874
|
-
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
875
|
-
var OAuthError = class extends Error {
|
|
876
|
-
constructor(status, error, description) {
|
|
877
|
-
super(description);
|
|
878
|
-
this.status = status;
|
|
879
|
-
this.error = error;
|
|
880
|
-
}
|
|
881
|
-
status;
|
|
882
|
-
error;
|
|
883
|
-
};
|
|
884
|
-
var AuthorizationServer = class {
|
|
885
|
-
constructor(testkit, seed, emit = () => void 0, directory) {
|
|
886
|
-
this.testkit = testkit;
|
|
887
|
-
this.seed = seed;
|
|
888
|
-
this.emit = emit;
|
|
889
|
-
this.directory = directory;
|
|
890
|
-
}
|
|
891
|
-
testkit;
|
|
892
|
-
seed;
|
|
893
|
-
emit;
|
|
894
|
-
directory;
|
|
895
|
-
codes = /* @__PURE__ */ new Map();
|
|
896
|
-
refreshTokens = /* @__PURE__ */ new Map();
|
|
897
|
-
signedUpUsers = /* @__PURE__ */ new Map();
|
|
898
|
-
async handle(req, res, url, readBody) {
|
|
899
|
-
const method = req.method ?? "GET";
|
|
900
|
-
switch (`${method} ${url.pathname}`) {
|
|
901
|
-
case "GET /oauth2/auth":
|
|
902
|
-
this.authorize(res, url.searchParams);
|
|
903
|
-
return true;
|
|
904
|
-
case "POST /oauth2/auth/login":
|
|
905
|
-
this.login(res, await readBody());
|
|
906
|
-
return true;
|
|
907
|
-
case "POST /oauth2/token":
|
|
908
|
-
await this.token(req, res, await readBody());
|
|
909
|
-
return true;
|
|
910
|
-
case "GET /oauth2/v2/user_profile":
|
|
911
|
-
await this.profile(req, res);
|
|
912
|
-
return true;
|
|
913
|
-
case "POST /oauth2/revoke":
|
|
914
|
-
this.revoke(res, await readBody());
|
|
915
|
-
return true;
|
|
916
|
-
case "GET /logout":
|
|
917
|
-
this.logout(res, url.searchParams);
|
|
918
|
-
return true;
|
|
919
|
-
default:
|
|
920
|
-
return false;
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
authorize(res, params) {
|
|
924
|
-
let request2;
|
|
925
|
-
try {
|
|
926
|
-
request2 = parseAuthorizeRequest(params);
|
|
927
|
-
} catch (error) {
|
|
928
|
-
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
929
|
-
}
|
|
930
|
-
if (params.get("prompt") === "none") {
|
|
931
|
-
return redirectWithError(res, request2, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
932
|
-
}
|
|
933
|
-
sendHtml(
|
|
934
|
-
res,
|
|
935
|
-
200,
|
|
936
|
-
renderSignIn({
|
|
937
|
-
request: encodeRequest(request2),
|
|
938
|
-
users: this.loginPageUsers(),
|
|
939
|
-
loginHint: request2.loginHint ?? void 0,
|
|
940
|
-
requiredOrganization: request2.orgCode ?? void 0
|
|
941
|
-
})
|
|
942
|
-
);
|
|
943
|
-
}
|
|
944
|
-
login(res, form) {
|
|
945
|
-
let request2;
|
|
946
|
-
try {
|
|
947
|
-
request2 = decodeRequest(form.request ?? "");
|
|
948
|
-
} catch {
|
|
949
|
-
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
950
|
-
}
|
|
951
|
-
const encoded = encodeRequest(request2);
|
|
952
|
-
const ref = (form.user || form.email || "").trim();
|
|
953
|
-
if (!ref) {
|
|
954
|
-
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
|
|
955
|
-
}
|
|
956
|
-
const user = this.resolveUser(ref);
|
|
957
|
-
if (!user) {
|
|
958
|
-
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
959
|
-
}
|
|
960
|
-
if (this.directory?.isSuspended(user.id)) {
|
|
961
|
-
return sendHtml(
|
|
962
|
-
res,
|
|
963
|
-
403,
|
|
964
|
-
renderSignIn({
|
|
965
|
-
request: encoded,
|
|
966
|
-
users: this.loginPageUsers(),
|
|
967
|
-
requiredOrganization: request2.orgCode ?? void 0,
|
|
968
|
-
error: `${user.email ?? user.id} is suspended and cannot sign in.`
|
|
969
|
-
})
|
|
970
|
-
);
|
|
971
|
-
}
|
|
972
|
-
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
973
|
-
const wanted = request2.orgCode ?? form.org ?? null;
|
|
974
|
-
let organizationCode = null;
|
|
975
|
-
if (wanted) {
|
|
976
|
-
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
977
|
-
return sendHtml(
|
|
978
|
-
res,
|
|
979
|
-
403,
|
|
980
|
-
renderSignIn({
|
|
981
|
-
request: encoded,
|
|
982
|
-
users: this.loginPageUsers(),
|
|
983
|
-
requiredOrganization: request2.orgCode ?? void 0,
|
|
984
|
-
error: `${user.email ?? user.id} is not a member of ${wanted}.`
|
|
985
|
-
})
|
|
986
|
-
);
|
|
987
|
-
}
|
|
988
|
-
organizationCode = wanted;
|
|
989
|
-
} else if (memberships.length === 1) {
|
|
990
|
-
organizationCode = memberships[0].organizationCode;
|
|
991
|
-
} else if (memberships.length > 1) {
|
|
992
|
-
return sendHtml(
|
|
993
|
-
res,
|
|
994
|
-
200,
|
|
995
|
-
renderOrganizationPicker({
|
|
996
|
-
request: encoded,
|
|
997
|
-
user,
|
|
998
|
-
organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
999
|
-
})
|
|
1000
|
-
);
|
|
1001
|
-
}
|
|
1002
|
-
const membership = memberships.find((m) => m.organizationCode === organizationCode);
|
|
1003
|
-
const scenario = {
|
|
1004
|
-
kind: "authenticated",
|
|
1005
|
-
user,
|
|
1006
|
-
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
1007
|
-
roles: [...membership?.roles ?? []],
|
|
1008
|
-
permissions: effectivePermissions(this.seed, membership),
|
|
1009
|
-
claims: {}
|
|
1010
|
-
};
|
|
1011
|
-
const code = randomToken();
|
|
1012
|
-
this.codes.set(code, {
|
|
1013
|
-
clientId: request2.clientId,
|
|
1014
|
-
redirectUri: request2.redirectUri,
|
|
1015
|
-
scenario,
|
|
1016
|
-
scope: request2.scope,
|
|
1017
|
-
audience: request2.audience,
|
|
1018
|
-
nonce: request2.nonce,
|
|
1019
|
-
authTime: Math.floor(Date.now() / 1e3),
|
|
1020
|
-
codeChallenge: request2.codeChallenge,
|
|
1021
|
-
codeChallengeMethod: request2.codeChallengeMethod,
|
|
1022
|
-
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
1023
|
-
});
|
|
1024
|
-
this.directory?.recordSignIn(user, organizationCode);
|
|
1025
|
-
this.emit("user.authenticated", user);
|
|
1026
|
-
const target = new URL(request2.redirectUri);
|
|
1027
|
-
target.searchParams.set("code", code);
|
|
1028
|
-
if (request2.state !== null) target.searchParams.set("state", request2.state);
|
|
1029
|
-
redirect(res, target.toString());
|
|
1030
|
-
}
|
|
1031
|
-
async token(req, res, form) {
|
|
1032
|
-
try {
|
|
1033
|
-
const clientId = clientIdFrom(req, form);
|
|
1034
|
-
const grantType = form.grant_type;
|
|
1035
|
-
if (grantType === "client_credentials") {
|
|
1036
|
-
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form), form));
|
|
1037
|
-
}
|
|
1038
|
-
let grant;
|
|
1039
|
-
if (grantType === "authorization_code") {
|
|
1040
|
-
grant = this.redeemCode(form, clientId);
|
|
1041
|
-
} else if (grantType === "refresh_token") {
|
|
1042
|
-
grant = this.redeemRefreshToken(form, clientId);
|
|
1043
|
-
} else {
|
|
1044
|
-
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
1045
|
-
}
|
|
1046
|
-
sendJson(res, 200, await this.issueTokens(grant));
|
|
1047
|
-
} catch (error) {
|
|
1048
|
-
if (error instanceof OAuthError) {
|
|
1049
|
-
return sendJson(res, error.status, { error: error.error, error_description: error.message });
|
|
1050
|
-
}
|
|
1051
|
-
throw error;
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
async clientCredentials(clientId, clientSecret, form) {
|
|
1055
|
-
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
1056
|
-
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
1057
|
-
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
1058
|
-
}
|
|
1059
|
-
const requested = (form.scope ?? "").split(/\s+/).filter(Boolean);
|
|
1060
|
-
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1061
|
-
const audience = (form.audience ?? "").split(/\s+/).filter(Boolean);
|
|
1062
|
-
return {
|
|
1063
|
-
access_token: await this.testkit.m2mToken({
|
|
1064
|
-
clientId,
|
|
1065
|
-
organizationCode: app?.organizationCode ?? null,
|
|
1066
|
-
scopes: requested,
|
|
1067
|
-
grantedScopes: granted,
|
|
1068
|
-
audience: audience.length > 0 ? audience : app?.audience ?? void 0,
|
|
1069
|
-
permissions: app?.permissions ?? void 0
|
|
1070
|
-
}),
|
|
1071
|
-
expires_in: this.testkit.accessTokenLifetime,
|
|
1072
|
-
scope: granted.join(" "),
|
|
1073
|
-
token_type: "bearer"
|
|
1074
|
-
};
|
|
1075
|
-
}
|
|
1076
|
-
reset() {
|
|
1077
|
-
this.codes.clear();
|
|
1078
|
-
this.refreshTokens.clear();
|
|
1079
|
-
this.signedUpUsers.clear();
|
|
1080
|
-
}
|
|
1081
|
-
redeemCode(form, clientId) {
|
|
1082
|
-
const code = form.code ?? "";
|
|
1083
|
-
const pending = this.codes.get(code);
|
|
1084
|
-
this.codes.delete(code);
|
|
1085
|
-
if (!pending || pending.expiresAt < Date.now()) {
|
|
1086
|
-
throw new OAuthError(400, "invalid_grant", "The authorization code is unknown, expired or already used.");
|
|
1087
|
-
}
|
|
1088
|
-
if (pending.clientId !== clientId) {
|
|
1089
|
-
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
1090
|
-
}
|
|
1091
|
-
if (form.redirect_uri !== pending.redirectUri) {
|
|
1092
|
-
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
1093
|
-
}
|
|
1094
|
-
if (pending.codeChallenge) {
|
|
1095
|
-
const verifier = form.code_verifier ?? "";
|
|
1096
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash3("sha256").update(verifier).digest("base64url");
|
|
1097
|
-
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
1098
|
-
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
1099
|
-
}
|
|
1100
|
-
}
|
|
1101
|
-
return pending;
|
|
1102
|
-
}
|
|
1103
|
-
redeemRefreshToken(form, clientId) {
|
|
1104
|
-
const token2 = form.refresh_token ?? "";
|
|
1105
|
-
const grant = this.refreshTokens.get(token2);
|
|
1106
|
-
this.refreshTokens.delete(token2);
|
|
1107
|
-
if (!grant) {
|
|
1108
|
-
throw new OAuthError(400, "invalid_grant", "The refresh token is unknown, revoked or already used.");
|
|
1109
|
-
}
|
|
1110
|
-
if (grant.clientId !== clientId) {
|
|
1111
|
-
throw new OAuthError(400, "invalid_grant", "The refresh token was issued to a different client.");
|
|
1112
|
-
}
|
|
1113
|
-
return grant;
|
|
1114
|
-
}
|
|
1115
|
-
async issueTokens(grant) {
|
|
1116
|
-
const { scenario } = grant;
|
|
1117
|
-
const body = {
|
|
1118
|
-
access_token: await this.testkit.token({
|
|
1119
|
-
subject: scenario.user.id,
|
|
1120
|
-
organizationCode: scenario.organization?.code ?? null,
|
|
1121
|
-
roles: scenario.roles.length > 0 ? scenario.roles : void 0,
|
|
1122
|
-
permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
|
|
1123
|
-
scopes: grant.scope,
|
|
1124
|
-
clientId: grant.clientId,
|
|
1125
|
-
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
1126
|
-
authTime: grant.authTime,
|
|
1127
|
-
featureFlags: featureFlagsFor(this.seed, scenario.organization?.code ?? null)
|
|
1128
|
-
}),
|
|
1129
|
-
expires_in: this.testkit.accessTokenLifetime,
|
|
1130
|
-
scope: grant.scope.join(" "),
|
|
1131
|
-
token_type: "bearer"
|
|
1132
|
-
};
|
|
1133
|
-
if (grant.scope.includes("openid")) {
|
|
1134
|
-
body.id_token = await this.testkit.idTokenFor(scenario, {
|
|
1135
|
-
clientId: grant.clientId,
|
|
1136
|
-
nonce: grant.nonce ?? void 0,
|
|
1137
|
-
authTime: grant.authTime
|
|
1138
|
-
});
|
|
1139
|
-
}
|
|
1140
|
-
if (grant.scope.includes("offline")) {
|
|
1141
|
-
const refreshToken = randomToken();
|
|
1142
|
-
this.refreshTokens.set(refreshToken, { ...grant, nonce: null });
|
|
1143
|
-
body.refresh_token = refreshToken;
|
|
1144
|
-
}
|
|
1145
|
-
return body;
|
|
1146
|
-
}
|
|
1147
|
-
async profile(req, res) {
|
|
1148
|
-
const header = req.headers.authorization ?? "";
|
|
1149
|
-
if (!header.startsWith("Bearer ")) {
|
|
1150
|
-
return sendJson(res, 401, { error: "invalid_token", error_description: "Send the access token as a Bearer token." });
|
|
1151
|
-
}
|
|
1152
|
-
let sub;
|
|
1153
|
-
try {
|
|
1154
|
-
sub = String((await this.testkit.verify(header.slice(7))).sub ?? "");
|
|
1155
|
-
} catch {
|
|
1156
|
-
return sendJson(res, 401, { error: "invalid_token", error_description: "The access token is not valid for this issuer." });
|
|
1157
|
-
}
|
|
1158
|
-
const user = this.seed.users.find((u) => u.id === sub) ?? this.signedUpUsers.get(sub);
|
|
1159
|
-
if (!user) {
|
|
1160
|
-
return sendJson(res, 404, { error: "not_found", error_description: `No user has the id ${sub}.` });
|
|
1161
|
-
}
|
|
1162
|
-
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
1163
|
-
sendJson(res, 200, {
|
|
1164
|
-
id: user.id,
|
|
1165
|
-
sub: user.id,
|
|
1166
|
-
provided_id: null,
|
|
1167
|
-
name: name || null,
|
|
1168
|
-
given_name: user.givenName,
|
|
1169
|
-
family_name: user.familyName,
|
|
1170
|
-
updated_at: Math.floor(Date.now() / 1e3),
|
|
1171
|
-
email: user.email,
|
|
1172
|
-
email_verified: user.emailVerified,
|
|
1173
|
-
picture: user.picture,
|
|
1174
|
-
preferred_username: null,
|
|
1175
|
-
phone: null
|
|
1176
|
-
});
|
|
1177
|
-
}
|
|
1178
|
-
revoke(res, form) {
|
|
1179
|
-
if (form.token) this.refreshTokens.delete(form.token);
|
|
1180
|
-
sendJson(res, 200, {});
|
|
1181
|
-
}
|
|
1182
|
-
logout(res, params) {
|
|
1183
|
-
const target = params.get("redirect");
|
|
1184
|
-
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
1185
|
-
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
1186
|
-
}
|
|
1187
|
-
resolveUser(ref) {
|
|
1188
|
-
const seeded = findUser(this.seed.users, ref);
|
|
1189
|
-
if (seeded) return seeded;
|
|
1190
|
-
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
1191
|
-
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
1192
|
-
if (!this.signedUpUsers.has(user.id)) {
|
|
1193
|
-
this.signedUpUsers.set(user.id, user);
|
|
1194
|
-
if (this.directory) this.seed.users.push(user);
|
|
1195
|
-
this.emit("user.created", user);
|
|
1196
|
-
}
|
|
1197
|
-
return this.signedUpUsers.get(user.id);
|
|
1198
|
-
}
|
|
1199
|
-
organization(code) {
|
|
1200
|
-
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
1201
|
-
}
|
|
1202
|
-
loginPageUsers() {
|
|
1203
|
-
return this.seed.users.map((user) => ({
|
|
1204
|
-
user,
|
|
1205
|
-
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
1206
|
-
}));
|
|
1207
|
-
}
|
|
1208
|
-
};
|
|
1209
|
-
function parseAuthorizeRequest(params) {
|
|
1210
|
-
const clientId = params.get("client_id");
|
|
1211
|
-
const redirectUri = params.get("redirect_uri");
|
|
1212
|
-
if (!clientId) throw new Error("client_id is missing.");
|
|
1213
|
-
if (!redirectUri || !isHttpUrl(redirectUri)) {
|
|
1214
|
-
throw new Error("redirect_uri must be an absolute http or https URL.");
|
|
1215
|
-
}
|
|
1216
|
-
if (params.get("response_type") !== "code") {
|
|
1217
|
-
throw new Error('response_type must be "code".');
|
|
1218
|
-
}
|
|
1219
|
-
const method = params.get("code_challenge_method");
|
|
1220
|
-
const challenge = params.get("code_challenge");
|
|
1221
|
-
if (challenge && method && method !== "S256" && method !== "plain") {
|
|
1222
|
-
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
1223
|
-
}
|
|
1224
|
-
return {
|
|
1225
|
-
clientId,
|
|
1226
|
-
redirectUri,
|
|
1227
|
-
state: params.get("state"),
|
|
1228
|
-
scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
|
|
1229
|
-
nonce: params.get("nonce"),
|
|
1230
|
-
audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
|
|
1231
|
-
orgCode: params.get("org_code"),
|
|
1232
|
-
loginHint: params.get("login_hint"),
|
|
1233
|
-
codeChallenge: challenge,
|
|
1234
|
-
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
1235
|
-
};
|
|
1236
|
-
}
|
|
1237
|
-
function encodeRequest(request2) {
|
|
1238
|
-
return Buffer.from(JSON.stringify(request2)).toString("base64url");
|
|
1239
|
-
}
|
|
1240
|
-
function decodeRequest(value) {
|
|
1241
|
-
const request2 = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
1242
|
-
if (!request2.clientId || !request2.redirectUri || !isHttpUrl(request2.redirectUri)) {
|
|
1243
|
-
throw new Error("invalid request");
|
|
1244
|
-
}
|
|
1245
|
-
return request2;
|
|
1246
|
-
}
|
|
1247
|
-
function clientIdFrom(req, form) {
|
|
1248
|
-
const header = req.headers.authorization ?? "";
|
|
1249
|
-
if (header.startsWith("Basic ")) {
|
|
1250
|
-
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1251
|
-
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
1252
|
-
if (id) return id;
|
|
1253
|
-
}
|
|
1254
|
-
if (form.client_id) return form.client_id;
|
|
1255
|
-
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
1256
|
-
}
|
|
1257
|
-
function clientSecretFrom(req, form) {
|
|
1258
|
-
const header = req.headers.authorization ?? "";
|
|
1259
|
-
if (header.startsWith("Basic ")) {
|
|
1260
|
-
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1261
|
-
const index = decoded.indexOf(":");
|
|
1262
|
-
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1263
|
-
}
|
|
1264
|
-
return form.client_secret ?? null;
|
|
1265
|
-
}
|
|
1266
|
-
function redirectWithError(res, request2, error, description) {
|
|
1267
|
-
const target = new URL(request2.redirectUri);
|
|
1268
|
-
target.searchParams.set("error", error);
|
|
1269
|
-
target.searchParams.set("error_description", description);
|
|
1270
|
-
if (request2.state !== null) target.searchParams.set("state", request2.state);
|
|
1271
|
-
redirect(res, target.toString());
|
|
1272
|
-
}
|
|
1273
|
-
function isHttpUrl(value) {
|
|
1274
|
-
try {
|
|
1275
|
-
const { protocol } = new URL(value);
|
|
1276
|
-
return protocol === "http:" || protocol === "https:";
|
|
1277
|
-
} catch {
|
|
1278
|
-
return false;
|
|
1279
|
-
}
|
|
1280
|
-
}
|
|
1281
|
-
function randomToken() {
|
|
1282
|
-
return randomBytes2(32).toString("base64url");
|
|
1283
|
-
}
|
|
1284
|
-
function safeEqual(a, b) {
|
|
1285
|
-
const left = Buffer.from(a);
|
|
1286
|
-
const right = Buffer.from(b);
|
|
1287
|
-
return left.length === right.length && timingSafeEqual(left, right);
|
|
1288
|
-
}
|
|
1289
|
-
function redirect(res, location) {
|
|
1290
|
-
res.writeHead(303, { location, "cache-control": "no-store" });
|
|
1291
|
-
res.end();
|
|
1292
|
-
}
|
|
1293
|
-
function sendHtml(res, status, html) {
|
|
1294
|
-
res.writeHead(status, {
|
|
1295
|
-
"content-type": "text/html; charset=utf-8",
|
|
1296
|
-
"cache-control": "no-store",
|
|
1297
|
-
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
1298
|
-
});
|
|
1299
|
-
res.end(html);
|
|
1300
|
-
}
|
|
1301
|
-
function sendJson(res, status, body) {
|
|
1302
|
-
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1303
|
-
res.end(JSON.stringify(body));
|
|
1304
|
-
}
|
|
1305
|
-
|
|
1306
|
-
// src/account.ts
|
|
1307
|
-
var DEFAULT_PAGE_SIZE = 10;
|
|
1308
|
-
var AccountApi = class {
|
|
1309
|
-
constructor(testkit, directory) {
|
|
1310
|
-
this.testkit = testkit;
|
|
1311
|
-
this.directory = directory;
|
|
1312
|
-
}
|
|
1313
|
-
testkit;
|
|
1314
|
-
directory;
|
|
1315
|
-
async handle(req, res, url) {
|
|
1316
|
-
if (!url.pathname.startsWith("/account_api/v1/")) return false;
|
|
1317
|
-
if ((req.method ?? "GET") !== "GET") {
|
|
1318
|
-
sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
|
|
1319
|
-
return true;
|
|
1320
|
-
}
|
|
1321
|
-
const header = req.headers.authorization ?? "";
|
|
1322
|
-
let token2;
|
|
1323
|
-
try {
|
|
1324
|
-
if (!header.startsWith("Bearer ")) throw new Error("missing");
|
|
1325
|
-
token2 = await this.testkit.verify(header.slice(7));
|
|
1326
|
-
} catch {
|
|
1327
|
-
sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
|
|
1328
|
-
return true;
|
|
1329
|
-
}
|
|
1330
|
-
if (typeof token2.sub !== "string" || Array.isArray(token2.gty) && token2.gty.includes("client_credentials")) {
|
|
1331
|
-
sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
|
|
1332
|
-
return true;
|
|
1333
|
-
}
|
|
1334
|
-
const userId = token2.sub;
|
|
1335
|
-
const orgCode = typeof token2.org_code === "string" ? token2.org_code : null;
|
|
1336
|
-
const path = url.pathname.slice("/account_api/v1/".length);
|
|
1337
|
-
const d = this.directory;
|
|
1338
|
-
const membership = orgCode ? d.membership(userId, orgCode) : void 0;
|
|
1339
|
-
if (path === "permissions") {
|
|
1340
|
-
const items = effectivePermissions(d.seed, membership).map((key) => {
|
|
1341
|
-
const p = d.ensurePermission(key);
|
|
1342
|
-
return { id: p.id, name: p.name, key: p.key };
|
|
1343
|
-
});
|
|
1344
|
-
sendPage(res, url, "permissions", items, { org_code: orgCode });
|
|
1345
|
-
return true;
|
|
1346
|
-
}
|
|
1347
|
-
if (path.startsWith("permission/")) {
|
|
1348
|
-
const key = decodeURIComponent(path.slice("permission/".length));
|
|
1349
|
-
sendJson2(res, 200, {
|
|
1350
|
-
data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
|
|
1351
|
-
});
|
|
1352
|
-
return true;
|
|
1353
|
-
}
|
|
1354
|
-
if (path === "roles") {
|
|
1355
|
-
const items = (membership?.roles ?? []).map((key) => {
|
|
1356
|
-
const r = d.ensureRole(key);
|
|
1357
|
-
return { id: r.id, name: r.name, key: r.key };
|
|
1358
|
-
});
|
|
1359
|
-
sendPage(res, url, "roles", items, { org_code: orgCode });
|
|
1360
|
-
return true;
|
|
1361
|
-
}
|
|
1362
|
-
if (path === "feature_flags") {
|
|
1363
|
-
const items = d.seed.featureFlags.map((flag) => ({
|
|
1364
|
-
id: flag.id,
|
|
1365
|
-
name: flag.name,
|
|
1366
|
-
key: flag.key,
|
|
1367
|
-
type: flag.type,
|
|
1368
|
-
value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
|
|
1369
|
-
}));
|
|
1370
|
-
sendPage(res, url, "feature_flags", items, {});
|
|
1371
|
-
return true;
|
|
1372
|
-
}
|
|
1373
|
-
if (path === "properties") {
|
|
1374
|
-
const values = d.seed.userProperties[userId] ?? {};
|
|
1375
|
-
const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
|
|
1376
|
-
sendPage(res, url, "properties", items, {});
|
|
1377
|
-
return true;
|
|
1378
|
-
}
|
|
1379
|
-
if (path === "entitlements" || path.startsWith("entitlement")) {
|
|
1380
|
-
const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
|
|
1381
|
-
const entitlements = (plan?.entitlements ?? []).map((e) => ({
|
|
1382
|
-
id: e.id,
|
|
1383
|
-
fixed_charge: e.fixedCharge,
|
|
1384
|
-
price_name: e.priceName,
|
|
1385
|
-
unit_amount: e.unitAmount,
|
|
1386
|
-
feature_key: e.featureKey,
|
|
1387
|
-
feature_name: e.featureName,
|
|
1388
|
-
entitlement_limit_max: e.limitMax,
|
|
1389
|
-
entitlement_limit_min: e.limitMin
|
|
1390
|
-
}));
|
|
1391
|
-
if (path === "entitlements") {
|
|
1392
|
-
const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
|
|
1393
|
-
sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
|
|
1394
|
-
return true;
|
|
1395
|
-
}
|
|
1396
|
-
const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
|
|
1397
|
-
const entitlement = entitlements.find((e) => e.feature_key === key);
|
|
1398
|
-
if (!entitlement) {
|
|
1399
|
-
sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
|
|
1400
|
-
} else {
|
|
1401
|
-
sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
|
|
1402
|
-
}
|
|
1403
|
-
return true;
|
|
1404
|
-
}
|
|
1405
|
-
if (path === "portal_link") {
|
|
1406
|
-
sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
|
|
1407
|
-
return true;
|
|
1408
|
-
}
|
|
1409
|
-
sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
|
|
1410
|
-
return true;
|
|
1411
|
-
}
|
|
1412
|
-
};
|
|
1413
|
-
function sendPage(res, url, field, items, extra) {
|
|
1414
|
-
const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
|
|
1415
|
-
const after = url.searchParams.get("starting_after");
|
|
1416
|
-
const start2 = after ? items.findIndex((item) => item.id === after) + 1 : 0;
|
|
1417
|
-
const page = items.slice(start2, start2 + size);
|
|
1418
|
-
const hasMore = start2 + size < items.length;
|
|
1419
|
-
sendJson2(res, 200, {
|
|
1420
|
-
data: { ...extra, [field]: page },
|
|
1421
|
-
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
1422
|
-
});
|
|
1423
|
-
}
|
|
1424
|
-
function errors(code, message) {
|
|
1425
|
-
return { errors: [{ code, message }] };
|
|
1426
|
-
}
|
|
1427
|
-
function sendJson2(res, status, body) {
|
|
1428
|
-
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1429
|
-
res.end(JSON.stringify(body));
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
// src/directory.ts
|
|
1433
|
-
import { randomBytes as randomBytes3 } from "crypto";
|
|
1434
|
-
var Directory = class {
|
|
1435
|
-
constructor(seed) {
|
|
1436
|
-
this.seed = seed;
|
|
1437
|
-
this.snapshot = JSON.stringify(seed);
|
|
1438
|
-
}
|
|
1439
|
-
seed;
|
|
1440
|
-
userMeta = /* @__PURE__ */ new Map();
|
|
1441
|
-
orgMeta = /* @__PURE__ */ new Map();
|
|
1442
|
-
snapshot;
|
|
1443
|
-
restore() {
|
|
1444
|
-
const original = JSON.parse(this.snapshot);
|
|
1445
|
-
for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
|
|
1446
|
-
this.seed[key].splice(0, this.seed[key].length, ...original[key]);
|
|
1447
|
-
}
|
|
1448
|
-
this.userMeta.clear();
|
|
1449
|
-
this.orgMeta.clear();
|
|
1450
|
-
}
|
|
1451
|
-
user(id) {
|
|
1452
|
-
return this.seed.users.find((user) => user.id === id);
|
|
1453
|
-
}
|
|
1454
|
-
meta(user) {
|
|
1455
|
-
let meta = this.userMeta.get(user.id);
|
|
1456
|
-
if (!meta) {
|
|
1457
|
-
meta = {
|
|
1458
|
-
providedId: null,
|
|
1459
|
-
isSuspended: false,
|
|
1460
|
-
isPasswordResetRequested: false,
|
|
1461
|
-
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1462
|
-
totalSignIns: 0,
|
|
1463
|
-
lastSignedIn: null
|
|
1464
|
-
};
|
|
1465
|
-
this.userMeta.set(user.id, meta);
|
|
1466
|
-
}
|
|
1467
|
-
return meta;
|
|
1468
|
-
}
|
|
1469
|
-
isSuspended(userId) {
|
|
1470
|
-
return this.userMeta.get(userId)?.isSuspended ?? false;
|
|
1471
|
-
}
|
|
1472
|
-
recordSignIn(user, organizationCode) {
|
|
1473
|
-
const meta = this.meta(user);
|
|
1474
|
-
meta.totalSignIns += 1;
|
|
1475
|
-
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
1476
|
-
void organizationCode;
|
|
1477
|
-
}
|
|
1478
|
-
createUser(input) {
|
|
1479
|
-
const user = createKindeUser({
|
|
1480
|
-
id: `kp_${randomBytes3(16).toString("hex")}`,
|
|
1481
|
-
email: input.email ?? null,
|
|
1482
|
-
givenName: input.givenName ?? null,
|
|
1483
|
-
familyName: input.familyName ?? null,
|
|
1484
|
-
picture: input.picture ?? null
|
|
1485
|
-
});
|
|
1486
|
-
this.seed.users.push(user);
|
|
1487
|
-
this.meta(user).providedId = input.providedId ?? null;
|
|
1488
|
-
return user;
|
|
1489
|
-
}
|
|
1490
|
-
deleteUser(id) {
|
|
1491
|
-
const index = this.seed.users.findIndex((user) => user.id === id);
|
|
1492
|
-
if (index < 0) return false;
|
|
1493
|
-
this.seed.users.splice(index, 1);
|
|
1494
|
-
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1495
|
-
if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
|
|
1496
|
-
}
|
|
1497
|
-
this.userMeta.delete(id);
|
|
1498
|
-
return true;
|
|
1499
|
-
}
|
|
1500
|
-
organization(code) {
|
|
1501
|
-
return this.seed.organizations.find((org) => org.code === code);
|
|
1502
|
-
}
|
|
1503
|
-
orgInfo(org) {
|
|
1504
|
-
let meta = this.orgMeta.get(org.code);
|
|
1505
|
-
if (!meta) {
|
|
1506
|
-
meta = {
|
|
1507
|
-
externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
|
|
1508
|
-
handle: slug(org.name),
|
|
1509
|
-
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1510
|
-
isAllowRegistrations: false
|
|
1511
|
-
};
|
|
1512
|
-
this.orgMeta.set(org.code, meta);
|
|
1513
|
-
}
|
|
1514
|
-
return meta;
|
|
1515
|
-
}
|
|
1516
|
-
createOrganization(input) {
|
|
1517
|
-
const org = createKindeOrganization({ code: `org_${randomBytes3(6).toString("hex").slice(0, 11)}`, name: input.name });
|
|
1518
|
-
this.seed.organizations.push(org);
|
|
1519
|
-
const meta = this.orgInfo(org);
|
|
1520
|
-
meta.externalId = input.externalId ?? null;
|
|
1521
|
-
if (input.handle) meta.handle = input.handle;
|
|
1522
|
-
return org;
|
|
1523
|
-
}
|
|
1524
|
-
deleteOrganization(code) {
|
|
1525
|
-
const index = this.seed.organizations.findIndex((org) => org.code === code);
|
|
1526
|
-
if (index < 0) return false;
|
|
1527
|
-
this.seed.organizations.splice(index, 1);
|
|
1528
|
-
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
1529
|
-
if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
|
|
1530
|
-
}
|
|
1531
|
-
this.orgMeta.delete(code);
|
|
1532
|
-
return true;
|
|
1533
|
-
}
|
|
1534
|
-
membership(userId, organizationCode) {
|
|
1535
|
-
return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1536
|
-
}
|
|
1537
|
-
addMembership(userId, organizationCode, roles = [], permissions = []) {
|
|
1538
|
-
const existing = this.membership(userId, organizationCode);
|
|
1539
|
-
if (existing) return existing;
|
|
1540
|
-
const membership = createMembership({ userId, organizationCode, roles, permissions });
|
|
1541
|
-
this.seed.memberships.push(membership);
|
|
1542
|
-
for (const key of roles) this.ensureRole(key);
|
|
1543
|
-
for (const key of permissions) this.ensurePermission(key);
|
|
1544
|
-
return membership;
|
|
1545
|
-
}
|
|
1546
|
-
removeMembership(userId, organizationCode) {
|
|
1547
|
-
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
1548
|
-
if (index < 0) return false;
|
|
1549
|
-
this.seed.memberships.splice(index, 1);
|
|
1550
|
-
return true;
|
|
1551
|
-
}
|
|
1552
|
-
role(idOrKey) {
|
|
1553
|
-
return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
|
|
1554
|
-
}
|
|
1555
|
-
permission(idOrKey) {
|
|
1556
|
-
return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
|
|
1557
|
-
}
|
|
1558
|
-
ensureRole(key, extra = {}) {
|
|
1559
|
-
const existing = this.role(key);
|
|
1560
|
-
if (existing) return existing;
|
|
1561
|
-
const role = roleRecord(key, extra);
|
|
1562
|
-
this.seed.roles.push(role);
|
|
1563
|
-
return role;
|
|
1564
|
-
}
|
|
1565
|
-
ensurePermission(key, extra = {}) {
|
|
1566
|
-
const existing = this.permission(key);
|
|
1567
|
-
if (existing) return existing;
|
|
1568
|
-
const permission = permissionRecord(key, extra);
|
|
1569
|
-
this.seed.permissions.push(permission);
|
|
1570
|
-
return permission;
|
|
1571
|
-
}
|
|
1572
|
-
deleteRole(id) {
|
|
1573
|
-
const role = this.role(id);
|
|
1574
|
-
if (!role) return void 0;
|
|
1575
|
-
this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
|
|
1576
|
-
for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
|
|
1577
|
-
return role;
|
|
1578
|
-
}
|
|
1579
|
-
deletePermission(id) {
|
|
1580
|
-
const permission = this.permission(id);
|
|
1581
|
-
if (!permission) return void 0;
|
|
1582
|
-
this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
|
|
1583
|
-
for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
|
|
1584
|
-
for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
|
|
1585
|
-
return permission;
|
|
1586
|
-
}
|
|
1587
|
-
};
|
|
1588
|
-
|
|
1589
|
-
// src/management.ts
|
|
1590
|
-
var OK = { code: "OK", message: "Success" };
|
|
1591
|
-
var DEFAULT_PAGE_SIZE2 = 10;
|
|
1592
|
-
var MAX_PAGE_SIZE = 500;
|
|
1593
|
-
var ManagementApi = class {
|
|
1594
|
-
constructor(testkit, directory, webhooks) {
|
|
1595
|
-
this.testkit = testkit;
|
|
1596
|
-
this.directory = directory;
|
|
1597
|
-
this.webhooks = webhooks;
|
|
1598
|
-
this.register();
|
|
1599
|
-
}
|
|
1600
|
-
testkit;
|
|
1601
|
-
directory;
|
|
1602
|
-
webhooks;
|
|
1603
|
-
routes = [];
|
|
1604
|
-
async handle(req, res, url, readBody) {
|
|
1605
|
-
if (!url.pathname.startsWith("/api/v1/")) return false;
|
|
1606
|
-
const method = req.method ?? "GET";
|
|
1607
|
-
const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
1608
|
-
if (!route) {
|
|
1609
|
-
sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
|
|
1610
|
-
return true;
|
|
1611
|
-
}
|
|
1612
|
-
const token2 = await this.authenticate(req.headers.authorization);
|
|
1613
|
-
if ("error" in token2) {
|
|
1614
|
-
sendJson3(res, 403, errors2(token2.code, token2.error));
|
|
1615
|
-
return true;
|
|
1616
|
-
}
|
|
1617
|
-
const granted = typeof token2.payload.scope === "string" ? token2.payload.scope.split(" ").filter(Boolean) : [];
|
|
1618
|
-
if (granted.length > 0 && !granted.includes(route.scope)) {
|
|
1619
|
-
sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
|
|
1620
|
-
return true;
|
|
1621
|
-
}
|
|
1622
|
-
const match = route.pattern.exec(url.pathname);
|
|
1623
|
-
const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
|
|
1624
|
-
const body = method === "GET" || method === "DELETE" ? {} : await readBody();
|
|
1625
|
-
const [status, payload] = await route.handler({ params, query: url.searchParams, body });
|
|
1626
|
-
sendJson3(res, status, payload);
|
|
1627
|
-
return true;
|
|
1628
|
-
}
|
|
1629
|
-
async authenticate(header) {
|
|
1630
|
-
if (!header?.startsWith("Bearer ")) {
|
|
1631
|
-
return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
|
|
1632
|
-
}
|
|
1633
|
-
let payload;
|
|
1634
|
-
try {
|
|
1635
|
-
payload = await this.testkit.verify(header.slice(7));
|
|
1636
|
-
} catch {
|
|
1637
|
-
return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
|
|
1638
|
-
}
|
|
1639
|
-
const audience = `${this.testkit.issuer}/api`;
|
|
1640
|
-
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
1641
|
-
if (!aud.includes(audience)) {
|
|
1642
|
-
return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
|
|
1643
|
-
}
|
|
1644
|
-
if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
|
|
1645
|
-
return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
|
|
1646
|
-
}
|
|
1647
|
-
return { payload };
|
|
1648
|
-
}
|
|
1649
|
-
route(method, path, scope, handler) {
|
|
1650
|
-
const keys = [];
|
|
1651
|
-
const pattern = new RegExp(
|
|
1652
|
-
`^${path.replace(/\{(\w+)\}/g, (_, key) => {
|
|
1653
|
-
keys.push(key);
|
|
1654
|
-
return "([^/]+)";
|
|
1655
|
-
})}$`
|
|
1656
|
-
);
|
|
1657
|
-
this.routes.push({ method, pattern, keys, scope, handler });
|
|
1658
|
-
}
|
|
1659
|
-
register() {
|
|
1660
|
-
const d = this.directory;
|
|
1661
|
-
this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
|
|
1662
|
-
let users = [...d.seed.users];
|
|
1663
|
-
const userId = query.get("user_id");
|
|
1664
|
-
const email = query.get("email")?.toLowerCase();
|
|
1665
|
-
if (userId) users = users.filter((u) => u.id === userId);
|
|
1666
|
-
if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
|
|
1667
|
-
const page = paginate(users, query);
|
|
1668
|
-
return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
|
|
1669
|
-
});
|
|
1670
|
-
this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
|
|
1671
|
-
const user = d.user(query.get("id") ?? "");
|
|
1672
|
-
return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
|
|
1673
|
-
});
|
|
1674
|
-
this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
|
|
1675
|
-
const profile = body.profile ?? {};
|
|
1676
|
-
const identities = Array.isArray(body.identities) ? body.identities : [];
|
|
1677
|
-
const emailIdentity = identities.find((i) => i.type === "email");
|
|
1678
|
-
const email = (emailIdentity?.details ?? {}).email;
|
|
1679
|
-
if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
|
|
1680
|
-
return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
|
|
1681
|
-
}
|
|
1682
|
-
const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
|
|
1683
|
-
if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
|
|
1684
|
-
const user = d.createUser({
|
|
1685
|
-
email: typeof email === "string" ? email : null,
|
|
1686
|
-
givenName: str(profile.given_name),
|
|
1687
|
-
familyName: str(profile.family_name),
|
|
1688
|
-
picture: str(profile.picture),
|
|
1689
|
-
providedId: str(body.provided_id)
|
|
1690
|
-
});
|
|
1691
|
-
if (orgCode) d.addMembership(user.id, orgCode);
|
|
1692
|
-
this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
|
|
1693
|
-
return [
|
|
1694
|
-
200,
|
|
1695
|
-
{ id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
|
|
1696
|
-
];
|
|
1697
|
-
});
|
|
1698
|
-
this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
|
|
1699
|
-
const user = d.user(query.get("id") ?? "");
|
|
1700
|
-
if (!user) return notFound("USER_INVALID", "No user has that id.");
|
|
1701
|
-
if (typeof body.given_name === "string") user.givenName = body.given_name;
|
|
1702
|
-
if (typeof body.family_name === "string") user.familyName = body.family_name;
|
|
1703
|
-
if (typeof body.picture === "string") user.picture = body.picture;
|
|
1704
|
-
const meta = d.meta(user);
|
|
1705
|
-
if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
|
|
1706
|
-
if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
|
|
1707
|
-
if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
|
|
1708
|
-
this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
|
|
1709
|
-
return [
|
|
1710
|
-
200,
|
|
1711
|
-
{
|
|
1712
|
-
id: user.id,
|
|
1713
|
-
given_name: user.givenName,
|
|
1714
|
-
family_name: user.familyName,
|
|
1715
|
-
email: user.email,
|
|
1716
|
-
is_suspended: meta.isSuspended,
|
|
1717
|
-
is_password_reset_requested: meta.isPasswordResetRequested,
|
|
1718
|
-
picture: user.picture
|
|
1719
|
-
}
|
|
1720
|
-
];
|
|
1721
|
-
});
|
|
1722
|
-
this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
|
|
1723
|
-
const id = query.get("id") ?? "";
|
|
1724
|
-
if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
|
|
1725
|
-
this.webhooks.emit("user.deleted", { user: { id } });
|
|
1726
|
-
return [200, OK];
|
|
1727
|
-
});
|
|
1728
|
-
this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
|
|
1729
|
-
const page = paginate(d.seed.organizations, query);
|
|
1730
|
-
return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
|
|
1731
|
-
});
|
|
1732
|
-
this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
|
|
1733
|
-
const org = d.organization(query.get("code") ?? "");
|
|
1734
|
-
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1735
|
-
const meta = d.orgInfo(org);
|
|
1736
|
-
return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
|
|
1737
|
-
});
|
|
1738
|
-
this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
|
|
1739
|
-
if (typeof body.name !== "string" || body.name.trim() === "") {
|
|
1740
|
-
return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
|
|
1741
|
-
}
|
|
1742
|
-
const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
|
|
1743
|
-
if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
|
|
1744
|
-
this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
|
|
1745
|
-
return [200, { ...OK, organization: { code: org.code } }];
|
|
1746
|
-
});
|
|
1747
|
-
this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
|
|
1748
|
-
const org = d.organization(params.org_code);
|
|
1749
|
-
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1750
|
-
const meta = d.orgInfo(org);
|
|
1751
|
-
if (typeof body.name === "string") org.name = body.name;
|
|
1752
|
-
if (typeof body.external_id === "string") meta.externalId = body.external_id;
|
|
1753
|
-
if (typeof body.handle === "string") meta.handle = body.handle;
|
|
1754
|
-
if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
|
|
1755
|
-
this.webhooks.emit("organization.updated", {
|
|
1756
|
-
organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
|
|
1757
|
-
});
|
|
1758
|
-
return [200, OK];
|
|
1759
|
-
});
|
|
1760
|
-
this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
|
|
1761
|
-
if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1762
|
-
this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
|
|
1763
|
-
return [200, OK];
|
|
1764
|
-
});
|
|
1765
|
-
this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
|
|
1766
|
-
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1767
|
-
const members = d.seed.memberships.filter((m) => m.organizationCode === params.org_code).map((m) => ({ membership: m, user: d.user(m.userId) })).filter((m) => m.user !== void 0);
|
|
1768
|
-
const page = paginate(members, query);
|
|
1769
|
-
return [
|
|
1770
|
-
200,
|
|
1771
|
-
{
|
|
1772
|
-
...OK,
|
|
1773
|
-
organization_users: page.items.map(({ membership, user }) => ({
|
|
1774
|
-
id: user.id,
|
|
1775
|
-
email: user.email,
|
|
1776
|
-
full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
|
|
1777
|
-
last_name: user.familyName,
|
|
1778
|
-
first_name: user.givenName,
|
|
1779
|
-
picture: user.picture,
|
|
1780
|
-
joined_on: d.meta(user).createdOn,
|
|
1781
|
-
last_accessed_on: d.meta(user).lastSignedIn,
|
|
1782
|
-
is_suspended: d.meta(user).isSuspended,
|
|
1783
|
-
roles: [...membership.roles]
|
|
1784
|
-
})),
|
|
1785
|
-
next_token: page.nextToken
|
|
1786
|
-
}
|
|
1787
|
-
];
|
|
1788
|
-
});
|
|
1789
|
-
this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
|
|
1790
|
-
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
1791
|
-
const users = Array.isArray(body.users) ? body.users : [];
|
|
1792
|
-
const added = [];
|
|
1793
|
-
const blocked = [];
|
|
1794
|
-
for (const entry of users) {
|
|
1795
|
-
const id = typeof entry.id === "string" ? entry.id : "";
|
|
1796
|
-
if (!d.user(id)) {
|
|
1797
|
-
blocked.push(id);
|
|
1798
|
-
continue;
|
|
1799
|
-
}
|
|
1800
|
-
d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
|
|
1801
|
-
added.push(id);
|
|
1802
|
-
}
|
|
1803
|
-
return [200, { ...OK, users_added: added, users_blocked: blocked }];
|
|
1804
|
-
});
|
|
1805
|
-
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
|
|
1806
|
-
return d.removeMembership(params.user_id, params.org_code) ? [200, OK] : notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1807
|
-
});
|
|
1808
|
-
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
|
|
1809
|
-
const membership = d.membership(params.user_id, params.org_code);
|
|
1810
|
-
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1811
|
-
const roles = membership.roles.map((key) => d.ensureRole(key));
|
|
1812
|
-
return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
|
|
1813
|
-
});
|
|
1814
|
-
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
|
|
1815
|
-
const membership = d.membership(params.user_id, params.org_code);
|
|
1816
|
-
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1817
|
-
const role = d.role(str(body.role_id) ?? "");
|
|
1818
|
-
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1819
|
-
if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
|
|
1820
|
-
return [200, OK];
|
|
1821
|
-
});
|
|
1822
|
-
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
|
|
1823
|
-
const membership = d.membership(params.user_id, params.org_code);
|
|
1824
|
-
const role = d.role(params.role_id);
|
|
1825
|
-
if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
|
|
1826
|
-
membership.roles = membership.roles.filter((key) => key !== role.key);
|
|
1827
|
-
return [200, OK];
|
|
1828
|
-
});
|
|
1829
|
-
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
|
|
1830
|
-
const membership = d.membership(params.user_id, params.org_code);
|
|
1831
|
-
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1832
|
-
const permissions = effectivePermissions(d.seed, membership).map((key) => {
|
|
1833
|
-
const permission = d.ensurePermission(key);
|
|
1834
|
-
const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
|
|
1835
|
-
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
|
|
1836
|
-
});
|
|
1837
|
-
return [200, { ...OK, permissions }];
|
|
1838
|
-
});
|
|
1839
|
-
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
|
|
1840
|
-
const membership = d.membership(params.user_id, params.org_code);
|
|
1841
|
-
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
1842
|
-
const permission = d.permission(str(body.permission_id) ?? "");
|
|
1843
|
-
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1844
|
-
if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
|
|
1845
|
-
return [200, OK];
|
|
1846
|
-
});
|
|
1847
|
-
this.route(
|
|
1848
|
-
"DELETE",
|
|
1849
|
-
"/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
|
|
1850
|
-
"delete:organization_user_permissions",
|
|
1851
|
-
({ params }) => {
|
|
1852
|
-
const membership = d.membership(params.user_id, params.org_code);
|
|
1853
|
-
const permission = d.permission(params.permission_id);
|
|
1854
|
-
if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
|
|
1855
|
-
membership.permissions = membership.permissions.filter((key) => key !== permission.key);
|
|
1856
|
-
return [200, OK];
|
|
1857
|
-
}
|
|
1858
|
-
);
|
|
1859
|
-
this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
|
|
1860
|
-
const page = paginate(d.seed.roles, query);
|
|
1861
|
-
return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
|
|
1862
|
-
});
|
|
1863
|
-
this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
|
|
1864
|
-
const key = str(body.key);
|
|
1865
|
-
if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
|
|
1866
|
-
if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
|
|
1867
|
-
const role = d.ensureRole(key, {
|
|
1868
|
-
name: str(body.name) ?? void 0,
|
|
1869
|
-
description: str(body.description) ?? void 0,
|
|
1870
|
-
isDefault: body.is_default_role === true
|
|
1871
|
-
});
|
|
1872
|
-
this.webhooks.emit("role.created", {
|
|
1873
|
-
role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
|
|
1874
|
-
});
|
|
1875
|
-
return [201, { ...OK, role: { id: role.id } }];
|
|
1876
|
-
});
|
|
1877
|
-
this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
|
|
1878
|
-
const role = d.role(params.role_id);
|
|
1879
|
-
return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
|
|
1880
|
-
});
|
|
1881
|
-
this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
|
|
1882
|
-
const role = d.deleteRole(params.role_id);
|
|
1883
|
-
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1884
|
-
this.webhooks.emit("role.deleted", { role: { id: role.id } });
|
|
1885
|
-
return [200, OK];
|
|
1886
|
-
});
|
|
1887
|
-
this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
|
|
1888
|
-
const role = d.role(params.role_id);
|
|
1889
|
-
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
1890
|
-
return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
|
|
1891
|
-
});
|
|
1892
|
-
this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
|
|
1893
|
-
const page = paginate(d.seed.permissions, query);
|
|
1894
|
-
return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
|
|
1895
|
-
});
|
|
1896
|
-
this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
|
|
1897
|
-
const key = str(body.key);
|
|
1898
|
-
if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
|
|
1899
|
-
if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
|
|
1900
|
-
const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
|
|
1901
|
-
this.webhooks.emit("permission.created", {
|
|
1902
|
-
permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
|
|
1903
|
-
});
|
|
1904
|
-
return [201, OK];
|
|
1905
|
-
});
|
|
1906
|
-
this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
|
|
1907
|
-
const permission = d.deletePermission(params.permission_id);
|
|
1908
|
-
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
1909
|
-
this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
|
|
1910
|
-
return [200, OK];
|
|
1911
|
-
});
|
|
1912
|
-
}
|
|
1913
|
-
userListItem(user) {
|
|
1914
|
-
const meta = this.directory.meta(user);
|
|
1915
|
-
return {
|
|
1916
|
-
id: user.id,
|
|
1917
|
-
provided_id: meta.providedId,
|
|
1918
|
-
email: user.email,
|
|
1919
|
-
phone: null,
|
|
1920
|
-
username: null,
|
|
1921
|
-
last_name: user.familyName,
|
|
1922
|
-
first_name: user.givenName,
|
|
1923
|
-
is_suspended: meta.isSuspended,
|
|
1924
|
-
picture: user.picture,
|
|
1925
|
-
total_sign_ins: meta.totalSignIns,
|
|
1926
|
-
failed_sign_ins: 0,
|
|
1927
|
-
last_signed_in: meta.lastSignedIn,
|
|
1928
|
-
created_on: meta.createdOn,
|
|
1929
|
-
organizations: this.organizationsOf(user),
|
|
1930
|
-
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
1931
|
-
};
|
|
1932
|
-
}
|
|
1933
|
-
userDetail(user) {
|
|
1934
|
-
const { email, ...rest } = this.userListItem(user);
|
|
1935
|
-
return { ...rest, preferred_email: email };
|
|
1936
|
-
}
|
|
1937
|
-
organizationsOf(user) {
|
|
1938
|
-
return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
|
|
1939
|
-
}
|
|
1940
|
-
organizationItem(org) {
|
|
1941
|
-
const meta = this.directory.orgInfo(org);
|
|
1942
|
-
return {
|
|
1943
|
-
code: org.code,
|
|
1944
|
-
name: org.name,
|
|
1945
|
-
handle: meta.handle,
|
|
1946
|
-
is_default: false,
|
|
1947
|
-
external_id: meta.externalId,
|
|
1948
|
-
is_auto_membership_enabled: false
|
|
1949
|
-
};
|
|
1950
|
-
}
|
|
1951
|
-
organizationEvent(org) {
|
|
1952
|
-
const meta = this.directory.orgInfo(org);
|
|
1953
|
-
return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
|
|
1954
|
-
}
|
|
1955
|
-
roleItem(role) {
|
|
1956
|
-
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
1957
|
-
}
|
|
1958
|
-
permissionItem(permission) {
|
|
1959
|
-
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
1960
|
-
}
|
|
1961
|
-
};
|
|
1962
|
-
function paginate(items, query) {
|
|
1963
|
-
const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
|
|
1964
|
-
const token2 = query.get("next_token");
|
|
1965
|
-
const offset = token2 ? Number(Buffer.from(token2, "base64url").toString("utf8")) || 0 : 0;
|
|
1966
|
-
const page = items.slice(offset, offset + size);
|
|
1967
|
-
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
1968
|
-
return { items: page, nextToken: next };
|
|
1969
|
-
}
|
|
1970
|
-
function errors2(code, message) {
|
|
1971
|
-
return { errors: [{ code, message }] };
|
|
1972
|
-
}
|
|
1973
|
-
function notFound(code, message) {
|
|
1974
|
-
return [404, errors2(code, message)];
|
|
1975
|
-
}
|
|
1976
|
-
function str(value) {
|
|
1977
|
-
return typeof value === "string" ? value : null;
|
|
1978
|
-
}
|
|
1979
|
-
function strings(value) {
|
|
1980
|
-
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
1981
|
-
}
|
|
1982
|
-
function sendJson3(res, status, body) {
|
|
1983
|
-
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1984
|
-
res.end(JSON.stringify(body));
|
|
1985
|
-
}
|
|
1986
|
-
|
|
1987
|
-
// src/failures.ts
|
|
1988
|
-
var MAX_DELAY_MS = 6e4;
|
|
1989
|
-
var FailureInjector = class {
|
|
1990
|
-
rules = [];
|
|
1991
|
-
nextId = 1;
|
|
1992
|
-
add(rule) {
|
|
1993
|
-
const problems = validate(rule);
|
|
1994
|
-
if (problems.length > 0) {
|
|
1995
|
-
throw new TestkitError("INVALID_REQUEST", "The failure rule is not valid.", problems);
|
|
1996
|
-
}
|
|
1997
|
-
const active = {
|
|
1998
|
-
id: `failure_${this.nextId++}`,
|
|
1999
|
-
path: rule.path,
|
|
2000
|
-
method: rule.method ? rule.method.toUpperCase() : null,
|
|
2001
|
-
status: rule.status ?? null,
|
|
2002
|
-
delayMs: rule.delayMs ?? 0,
|
|
2003
|
-
hang: rule.hang ?? false,
|
|
2004
|
-
remaining: rule.times ?? null,
|
|
2005
|
-
retryAfter: rule.retryAfter ?? 1,
|
|
2006
|
-
hits: 0
|
|
2007
|
-
};
|
|
2008
|
-
this.rules.push(active);
|
|
2009
|
-
return { ...active };
|
|
2010
|
-
}
|
|
2011
|
-
remove(id) {
|
|
2012
|
-
const before = this.rules.length;
|
|
2013
|
-
this.rules = this.rules.filter((rule) => rule.id !== id);
|
|
2014
|
-
return this.rules.length < before;
|
|
2015
|
-
}
|
|
2016
|
-
clear() {
|
|
2017
|
-
this.rules = [];
|
|
2018
|
-
}
|
|
2019
|
-
list() {
|
|
2020
|
-
return this.rules.map((rule) => ({ ...rule }));
|
|
2021
|
-
}
|
|
2022
|
-
take(method, path) {
|
|
2023
|
-
const rule = this.rules.find((r) => matches(r, method, path));
|
|
2024
|
-
if (!rule) return null;
|
|
2025
|
-
rule.hits += 1;
|
|
2026
|
-
if (rule.remaining !== null) {
|
|
2027
|
-
rule.remaining -= 1;
|
|
2028
|
-
if (rule.remaining <= 0) this.remove(rule.id);
|
|
2029
|
-
}
|
|
2030
|
-
return { ...rule };
|
|
2031
|
-
}
|
|
2032
|
-
};
|
|
2033
|
-
function failureBody(status) {
|
|
2034
|
-
const error = status === 429 ? "rate_limited" : status === 503 ? "temporarily_unavailable" : status >= 500 ? "server_error" : "injected_failure";
|
|
2035
|
-
return { error, error_description: `kinde-testkit injected a ${status} response.` };
|
|
2036
|
-
}
|
|
2037
|
-
function matches(rule, method, path) {
|
|
2038
|
-
if (rule.method && rule.method !== method.toUpperCase()) return false;
|
|
2039
|
-
if (rule.path.endsWith("*")) return path.startsWith(rule.path.slice(0, -1));
|
|
2040
|
-
return rule.path === path;
|
|
2041
|
-
}
|
|
2042
|
-
function validate(rule) {
|
|
2043
|
-
const problems = [];
|
|
2044
|
-
if (typeof rule.path !== "string" || !rule.path.startsWith("/")) {
|
|
2045
|
-
problems.push('"path" must start with "/", for example "/oauth2/token" or "/oauth2/*".');
|
|
2046
|
-
} else if (rule.path.startsWith("/testkit/")) {
|
|
2047
|
-
problems.push("Failures cannot target /testkit/ control endpoints.");
|
|
2048
|
-
}
|
|
2049
|
-
if (rule.status !== void 0 && (!Number.isInteger(rule.status) || rule.status < 400 || rule.status > 599)) {
|
|
2050
|
-
problems.push('"status" must be an HTTP error status between 400 and 599.');
|
|
2051
|
-
}
|
|
2052
|
-
if (rule.delayMs !== void 0 && (!Number.isFinite(rule.delayMs) || rule.delayMs < 0 || rule.delayMs > MAX_DELAY_MS)) {
|
|
2053
|
-
problems.push(`"delayMs" must be between 0 and ${MAX_DELAY_MS}.`);
|
|
2054
|
-
}
|
|
2055
|
-
if (rule.times !== void 0 && (!Number.isInteger(rule.times) || rule.times < 1)) {
|
|
2056
|
-
problems.push('"times" must be a whole number of 1 or more.');
|
|
2057
|
-
}
|
|
2058
|
-
if (rule.retryAfter !== void 0 && (!Number.isInteger(rule.retryAfter) || rule.retryAfter < 0)) {
|
|
2059
|
-
problems.push('"retryAfter" must be a whole number of seconds.');
|
|
2060
|
-
}
|
|
2061
|
-
if (rule.status === void 0 && !rule.delayMs && !rule.hang) {
|
|
2062
|
-
problems.push('Set at least one of "status", "delayMs" or "hang".');
|
|
2063
|
-
}
|
|
2064
|
-
return problems;
|
|
2065
|
-
}
|
|
2066
|
-
|
|
2067
|
-
// src/webhooks.ts
|
|
2068
|
-
import { randomBytes as randomBytes4 } from "crypto";
|
|
2069
|
-
var WEBHOOK_EVENT_TYPES = [
|
|
2070
|
-
"user.created",
|
|
2071
|
-
"user.updated",
|
|
2072
|
-
"user.deleted",
|
|
2073
|
-
"user.authenticated",
|
|
2074
|
-
"user.authentication_failed",
|
|
2075
|
-
"organization.created",
|
|
2076
|
-
"organization.updated",
|
|
2077
|
-
"organization.deleted",
|
|
2078
|
-
"role.created",
|
|
2079
|
-
"role.updated",
|
|
2080
|
-
"role.deleted",
|
|
2081
|
-
"permission.created",
|
|
2082
|
-
"permission.updated",
|
|
2083
|
-
"permission.deleted",
|
|
2084
|
-
"subscriber.created",
|
|
2085
|
-
"access_request.created"
|
|
2086
|
-
];
|
|
2087
|
-
var BILLING_EVENT_TYPES = [
|
|
2088
|
-
"customer.agreement_cancelled",
|
|
2089
|
-
"customer.agreement_created",
|
|
2090
|
-
"customer.invoice_overdue",
|
|
2091
|
-
"customer.meter_usage_updated",
|
|
2092
|
-
"customer.payment_failed",
|
|
2093
|
-
"customer.payment_succeeded",
|
|
2094
|
-
"customer.plan_assigned",
|
|
2095
|
-
"customer.plan_changed"
|
|
2096
|
-
];
|
|
2097
|
-
var DEFAULT_RETRY_DELAYS_MS = [0, 100, 500];
|
|
2098
|
-
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
2099
|
-
var MAX_DUPLICATES = 10;
|
|
2100
|
-
var WebhookDispatcher = class {
|
|
2101
|
-
constructor(testkit, seed, endpoints = [], options = {}) {
|
|
2102
|
-
this.testkit = testkit;
|
|
2103
|
-
this.seed = seed;
|
|
2104
|
-
this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
|
|
2105
|
-
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
2106
|
-
for (const endpoint of endpoints) this.addEndpoint(endpoint);
|
|
2107
|
-
this.seededEndpoints = [...this.endpoints];
|
|
2108
|
-
}
|
|
2109
|
-
testkit;
|
|
2110
|
-
seed;
|
|
2111
|
-
endpoints = [];
|
|
2112
|
-
seededEndpoints = [];
|
|
2113
|
-
log = [];
|
|
2114
|
-
nextEndpoint = 1;
|
|
2115
|
-
retryDelaysMs;
|
|
2116
|
-
timeoutMs;
|
|
2117
|
-
addEndpoint(input) {
|
|
2118
|
-
if (!isHttpUrl2(input.url)) {
|
|
2119
|
-
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
2120
|
-
}
|
|
2121
|
-
if (input.events !== void 0 && (!Array.isArray(input.events) || input.events.some((e) => typeof e !== "string"))) {
|
|
2122
|
-
throw new TestkitError("INVALID_REQUEST", "Webhook events must be a list of event type names.");
|
|
2123
|
-
}
|
|
2124
|
-
const endpoint = { id: `endpoint_${this.nextEndpoint++}`, url: input.url, events: input.events ?? null };
|
|
2125
|
-
this.endpoints.push(endpoint);
|
|
2126
|
-
return { ...endpoint };
|
|
2127
|
-
}
|
|
2128
|
-
removeEndpoint(id) {
|
|
2129
|
-
const before = this.endpoints.length;
|
|
2130
|
-
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
2131
|
-
return this.endpoints.length < before;
|
|
2132
|
-
}
|
|
2133
|
-
listEndpoints() {
|
|
2134
|
-
return this.endpoints.map((e) => ({ ...e }));
|
|
2135
|
-
}
|
|
2136
|
-
deliveries() {
|
|
2137
|
-
return this.log.map((d) => ({ ...d, attempts: [...d.attempts] }));
|
|
2138
|
-
}
|
|
2139
|
-
reset() {
|
|
2140
|
-
this.log = [];
|
|
2141
|
-
this.endpoints = [...this.seededEndpoints];
|
|
2142
|
-
}
|
|
2143
|
-
buildEvent(options) {
|
|
2144
|
-
if (typeof options.type !== "string" || !/^[a-z_]+\.[a-z_]+$/.test(options.type)) {
|
|
2145
|
-
throw new TestkitError("INVALID_REQUEST", `"${String(options.type)}" is not a webhook event type, such as user.created.`);
|
|
2146
|
-
}
|
|
2147
|
-
const now = /* @__PURE__ */ new Date();
|
|
2148
|
-
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
2149
|
-
const event = {
|
|
2150
|
-
data: options.data ?? this.buildData(options),
|
|
2151
|
-
event_id: `event_${randomBytes4(16).toString("hex")}`,
|
|
2152
|
-
event_timestamp: timestamp,
|
|
2153
|
-
source: options.source ?? "admin",
|
|
2154
|
-
timestamp,
|
|
2155
|
-
type: options.type
|
|
2156
|
-
};
|
|
2157
|
-
if (options.type === "user.authenticated" || options.type === "user.authentication_failed") {
|
|
2158
|
-
event.ip_address = options.ipAddress ?? "127.0.0.1";
|
|
2159
|
-
}
|
|
2160
|
-
return event;
|
|
2161
|
-
}
|
|
2162
|
-
async send(options) {
|
|
2163
|
-
const event = this.buildEvent(options);
|
|
2164
|
-
const copies = options.duplicate ?? 1;
|
|
2165
|
-
if (!Number.isInteger(copies) || copies < 1 || copies > MAX_DUPLICATES) {
|
|
2166
|
-
throw new TestkitError("INVALID_REQUEST", `"duplicate" must be a whole number from 1 to ${MAX_DUPLICATES}.`);
|
|
2167
|
-
}
|
|
2168
|
-
const targets = options.to ? [{ id: "direct", url: options.to, events: null }] : this.endpoints.filter((e) => e.events === null || e.events.includes(options.type));
|
|
2169
|
-
if (options.to && !isHttpUrl2(options.to)) {
|
|
2170
|
-
throw new TestkitError("INVALID_REQUEST", `"to" must be an http or https URL.`);
|
|
2171
|
-
}
|
|
2172
|
-
if (targets.length === 0) {
|
|
2173
|
-
throw new TestkitError(
|
|
2174
|
-
"INVALID_REQUEST",
|
|
2175
|
-
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
2176
|
-
);
|
|
2177
|
-
}
|
|
2178
|
-
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
2179
|
-
const signed = await this.testkit.signPayload(
|
|
2180
|
-
event,
|
|
2181
|
-
options.invalid === "stale" ? void 0 : options.invalid
|
|
2182
|
-
);
|
|
2183
|
-
const jobs = targets.flatMap((target) => {
|
|
2184
|
-
const webhookId = `wh_${randomBytes4(12).toString("hex")}`;
|
|
2185
|
-
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
2186
|
-
});
|
|
2187
|
-
return Promise.all(jobs);
|
|
2188
|
-
}
|
|
2189
|
-
async deliver(url, webhookId, body, event, copy) {
|
|
2190
|
-
const delivery = {
|
|
2191
|
-
webhookId,
|
|
2192
|
-
eventId: String(event.event_id),
|
|
2193
|
-
type: String(event.type),
|
|
2194
|
-
url,
|
|
2195
|
-
copy,
|
|
2196
|
-
delivered: false,
|
|
2197
|
-
attempts: [],
|
|
2198
|
-
payload: event
|
|
2199
|
-
};
|
|
2200
|
-
this.log.push(delivery);
|
|
2201
|
-
for (const [index, delay] of this.retryDelaysMs.entries()) {
|
|
2202
|
-
if (delay > 0) await sleep(delay);
|
|
2203
|
-
const started = Date.now();
|
|
2204
|
-
try {
|
|
2205
|
-
const response = await fetch(url, {
|
|
2206
|
-
method: "POST",
|
|
2207
|
-
headers: { "content-type": "application/jwt", "webhook-id": webhookId },
|
|
2208
|
-
body,
|
|
2209
|
-
signal: AbortSignal.timeout(this.timeoutMs)
|
|
2210
|
-
});
|
|
2211
|
-
await response.arrayBuffer().catch(() => void 0);
|
|
2212
|
-
delivery.attempts.push({ attempt: index + 1, status: response.status, error: null, durationMs: Date.now() - started });
|
|
2213
|
-
if (response.status === 200) {
|
|
2214
|
-
delivery.delivered = true;
|
|
2215
|
-
break;
|
|
2216
|
-
}
|
|
2217
|
-
} catch (error) {
|
|
2218
|
-
const name = error.name;
|
|
2219
|
-
delivery.attempts.push({
|
|
2220
|
-
attempt: index + 1,
|
|
2221
|
-
status: null,
|
|
2222
|
-
error: name === "TimeoutError" ? `No answer within ${this.timeoutMs}ms` : error.message,
|
|
2223
|
-
durationMs: Date.now() - started
|
|
2224
|
-
});
|
|
2225
|
-
}
|
|
2226
|
-
}
|
|
2227
|
-
return { ...delivery, attempts: [...delivery.attempts] };
|
|
2228
|
-
}
|
|
2229
|
-
buildData(options) {
|
|
2230
|
-
const [subject] = options.type.split(".");
|
|
2231
|
-
switch (subject) {
|
|
2232
|
-
case "user":
|
|
2233
|
-
return { user: this.userData(options) };
|
|
2234
|
-
case "organization":
|
|
2235
|
-
return { organization: this.organizationData(options) };
|
|
2236
|
-
case "role":
|
|
2237
|
-
return { role: this.namedData(options, "role") };
|
|
2238
|
-
case "permission":
|
|
2239
|
-
return { permission: this.namedData(options, "permission") };
|
|
2240
|
-
case "subscriber": {
|
|
2241
|
-
const user = this.requireUser(options);
|
|
2242
|
-
return {
|
|
2243
|
-
subscriber: {
|
|
2244
|
-
email: user.email,
|
|
2245
|
-
first_name: user.givenName,
|
|
2246
|
-
id: stableId("sub", user.id),
|
|
2247
|
-
last_name: user.familyName,
|
|
2248
|
-
user_id: user.id
|
|
2249
|
-
}
|
|
2250
|
-
};
|
|
2251
|
-
}
|
|
2252
|
-
case "access_request": {
|
|
2253
|
-
const user = this.requireUser(options);
|
|
2254
|
-
return {
|
|
2255
|
-
access_request: { email: user.email, first_name: user.givenName, last_name: user.familyName, user_id: user.id }
|
|
2256
|
-
};
|
|
2257
|
-
}
|
|
2258
|
-
default:
|
|
2259
|
-
throw new TestkitError(
|
|
2260
|
-
"INVALID_REQUEST",
|
|
2261
|
-
`kinde-testkit has no built-in payload for ${options.type}. Pass "data" with the event's data object.`
|
|
2262
|
-
);
|
|
2263
|
-
}
|
|
2264
|
-
}
|
|
2265
|
-
emit(type, data, source = "api") {
|
|
2266
|
-
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2267
|
-
void this.send({ type, data, source }).catch(() => void 0);
|
|
2268
|
-
}
|
|
2269
|
-
userEventData(user) {
|
|
2270
|
-
return this.userPayload(user);
|
|
2271
|
-
}
|
|
2272
|
-
emitForUser(type, user) {
|
|
2273
|
-
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
2274
|
-
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
2275
|
-
void this.send({ type, data, source: "user" }).catch(() => void 0);
|
|
2276
|
-
}
|
|
2277
|
-
userData(options) {
|
|
2278
|
-
const user = this.requireUser(options);
|
|
2279
|
-
if (options.type !== "user.created" && options.type !== "user.updated") return { id: user.id };
|
|
2280
|
-
return this.userPayload(user);
|
|
2281
|
-
}
|
|
2282
|
-
userPayload(user) {
|
|
2283
|
-
return {
|
|
2284
|
-
email: user.email,
|
|
2285
|
-
first_name: user.givenName,
|
|
2286
|
-
id: user.id,
|
|
2287
|
-
is_password_reset_requested: false,
|
|
2288
|
-
is_suspended: false,
|
|
2289
|
-
last_name: user.familyName,
|
|
2290
|
-
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => ({
|
|
2291
|
-
code: m.organizationCode,
|
|
2292
|
-
permissions: m.permissions.length > 0 ? m.permissions.map((key) => ({ id: stableId("perm", key), key })) : null,
|
|
2293
|
-
roles: m.roles.length > 0 ? m.roles.map((key) => ({ id: stableId("role", key), key })) : null
|
|
2294
|
-
})),
|
|
2295
|
-
phone: null,
|
|
2296
|
-
username: typeof user.claims.username === "string" ? user.claims.username : null
|
|
2297
|
-
};
|
|
2298
|
-
}
|
|
2299
|
-
organizationData(options) {
|
|
2300
|
-
if (!options.organization) {
|
|
2301
|
-
throw new TestkitError("INVALID_REQUEST", `${options.type} needs "organization", the organization code.`);
|
|
2302
|
-
}
|
|
2303
|
-
const org = this.seed.organizations.find((o) => o.code === options.organization);
|
|
2304
|
-
if (options.type === "organization.deleted") return { code: options.organization };
|
|
2305
|
-
const name = org?.name ?? titleCase(options.organization);
|
|
2306
|
-
const data = { code: options.organization, external_id: null, handle: slug(name), name };
|
|
2307
|
-
if (options.type === "organization.updated") data.is_allow_registrations = false;
|
|
2308
|
-
return data;
|
|
2309
|
-
}
|
|
2310
|
-
namedData(options, kind) {
|
|
2311
|
-
const key = kind === "role" ? options.role : options.permission;
|
|
2312
|
-
if (!key) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "${kind}", the ${kind} key.`);
|
|
2313
|
-
const id = stableId(kind === "role" ? "role" : "perm", key);
|
|
2314
|
-
if (options.type.endsWith(".deleted")) return { id };
|
|
2315
|
-
const data = { description: "", id, key, name: titleCase(key) };
|
|
2316
|
-
if (kind === "role") data.is_default_role = false;
|
|
2317
|
-
return data;
|
|
2318
|
-
}
|
|
2319
|
-
requireUser(options) {
|
|
2320
|
-
if (!options.user) throw new TestkitError("INVALID_REQUEST", `${options.type} needs "user", a seeded user's id or email.`);
|
|
2321
|
-
const user = findUser(this.seed.users, options.user);
|
|
2322
|
-
if (!user) throw new TestkitError("SEED_UNKNOWN_USER", `No seeded user matches "${options.user}".`);
|
|
2323
|
-
return user;
|
|
2324
|
-
}
|
|
2325
|
-
};
|
|
2326
|
-
function isHttpUrl2(value) {
|
|
2327
|
-
if (typeof value !== "string") return false;
|
|
2328
|
-
try {
|
|
2329
|
-
const { protocol } = new URL(value);
|
|
2330
|
-
return protocol === "http:" || protocol === "https:";
|
|
2331
|
-
} catch {
|
|
2332
|
-
return false;
|
|
2333
|
-
}
|
|
2334
|
-
}
|
|
2335
|
-
function sleep(ms) {
|
|
2336
|
-
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
2337
|
-
}
|
|
2338
|
-
|
|
2339
|
-
// src/server.ts
|
|
2340
|
-
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
2341
|
-
var MAX_BODY_BYTES = 64 * 1024;
|
|
2342
|
-
var JWKS_PATHS = /* @__PURE__ */ new Set(["/.well-known/jwks", "/.well-known/jwks.json"]);
|
|
2343
|
-
async function startKindeTestkit(options = {}) {
|
|
2344
|
-
const host = options.host ?? "127.0.0.1";
|
|
2345
|
-
if (!LOOPBACK_HOSTS.has(host) && !options.allowPublic) {
|
|
2346
|
-
throw new TestkitError(
|
|
2347
|
-
"PUBLIC_BIND_REFUSED",
|
|
2348
|
-
`kinde-testkit will not listen on ${host}. It signs tokens for any identity, so it stays on localhost unless you pass --allow-public (allowPublic: true in code).`
|
|
2349
|
-
);
|
|
2350
|
-
}
|
|
2351
|
-
const seed = resolveSeed(options.seed ?? {});
|
|
2352
|
-
const failures = new FailureInjector();
|
|
2353
|
-
let ready;
|
|
2354
|
-
const testkitReady = new Promise((resolve3) => ready = resolve3);
|
|
2355
|
-
const listener = (req, res) => {
|
|
2356
|
-
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
2357
|
-
};
|
|
2358
|
-
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
2359
|
-
const server = certificate ? createHttpsServer({ cert: certificate.cert, key: certificate.key }, listener) : createServer(listener);
|
|
2360
|
-
await new Promise((resolve3, reject) => {
|
|
2361
|
-
server.once("error", reject);
|
|
2362
|
-
server.listen(options.port ?? 4400, host, () => resolve3());
|
|
2363
|
-
});
|
|
2364
|
-
const { port } = server.address();
|
|
2365
|
-
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
2366
|
-
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
2367
|
-
const testkit = await KindeTestkit.create({
|
|
2368
|
-
issuer: options.issuer ?? options.seed?.issuer ?? url,
|
|
2369
|
-
audience: options.audience ?? options.seed?.audience,
|
|
2370
|
-
clientId: options.clientId ?? options.seed?.clientId
|
|
2371
|
-
});
|
|
2372
|
-
const directory = new Directory(seed);
|
|
2373
|
-
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
2374
|
-
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory);
|
|
2375
|
-
const management = new ManagementApi(testkit, directory, webhooks);
|
|
2376
|
-
const account = new AccountApi(testkit, directory);
|
|
2377
|
-
const reset2 = () => {
|
|
2378
|
-
auth.reset();
|
|
2379
|
-
failures.clear();
|
|
2380
|
-
webhooks.reset();
|
|
2381
|
-
directory.restore();
|
|
2382
|
-
};
|
|
2383
|
-
ready({ testkit, auth, seed, failures, webhooks, management, account, reset: reset2 });
|
|
2384
|
-
return {
|
|
2385
|
-
url,
|
|
2386
|
-
issuer: testkit.issuer,
|
|
2387
|
-
discoveryUrl: `${url}/.well-known/openid-configuration`,
|
|
2388
|
-
jwksUri: `${url}/.well-known/jwks`,
|
|
2389
|
-
testkit,
|
|
2390
|
-
seed,
|
|
2391
|
-
failures,
|
|
2392
|
-
webhooks,
|
|
2393
|
-
directory,
|
|
2394
|
-
certificatePath: certificate?.certPath ?? null,
|
|
2395
|
-
reset: reset2,
|
|
2396
|
-
close: () => new Promise((resolve3, reject) => {
|
|
2397
|
-
server.closeAllConnections();
|
|
2398
|
-
server.close((error) => error ? reject(error) : resolve3());
|
|
2399
|
-
})
|
|
2400
|
-
};
|
|
2401
|
-
}
|
|
2402
|
-
async function handle(req, res, context) {
|
|
2403
|
-
const { testkit, auth, seed, failures, webhooks } = context;
|
|
2404
|
-
const url = new URL(req.url ?? "/", "http://localhost");
|
|
2405
|
-
const { pathname } = url;
|
|
2406
|
-
const method = req.method ?? "GET";
|
|
2407
|
-
if (!pathname.startsWith("/testkit/")) {
|
|
2408
|
-
const failure = failures.take(method, pathname);
|
|
2409
|
-
if (failure) {
|
|
2410
|
-
if (failure.hang) return;
|
|
2411
|
-
if (failure.delayMs > 0) await new Promise((resolve3) => setTimeout(resolve3, failure.delayMs));
|
|
2412
|
-
if (failure.status !== null) {
|
|
2413
|
-
const headers = {};
|
|
2414
|
-
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
2415
|
-
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
2416
|
-
}
|
|
2417
|
-
}
|
|
2418
|
-
}
|
|
2419
|
-
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
2420
|
-
if (await context.management.handle(req, res, url, async () => await readJson(req))) return;
|
|
2421
|
-
if (await context.account.handle(req, res, url)) return;
|
|
2422
|
-
if (method === "GET" && pathname === "/testkit/portal") {
|
|
2423
|
-
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
2424
|
-
res.end(
|
|
2425
|
-
`<!doctype html><meta charset="utf-8"><title>Self-serve portal</title><body style="font:15px system-ui;padding:40px"><h1>Self-serve portal</h1><p>kinde-testkit does not emulate Kinde's self-serve portal. Your app linked here for <code>${escapeHtml(url.searchParams.get("subnav") ?? "profile")}</code>.</p>`
|
|
2426
|
-
);
|
|
2427
|
-
return;
|
|
2428
|
-
}
|
|
2429
|
-
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
2430
|
-
return sendJson4(res, 200, discovery(testkit));
|
|
2431
|
-
}
|
|
2432
|
-
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
2433
|
-
return sendJson4(res, 200, testkit.jwks());
|
|
2434
|
-
}
|
|
2435
|
-
if (method === "GET" && pathname === "/testkit/health") {
|
|
2436
|
-
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
2437
|
-
}
|
|
2438
|
-
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
2439
|
-
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
2440
|
-
return sendJson4(res, 200, seed.organizations);
|
|
2441
|
-
}
|
|
2442
|
-
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
2443
|
-
return sendJson4(res, 200, seed.memberships);
|
|
2444
|
-
}
|
|
2445
|
-
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
2446
|
-
if (method === "POST" && pathname === "/testkit/failures") {
|
|
2447
|
-
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
2448
|
-
}
|
|
2449
|
-
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
2450
|
-
failures.clear();
|
|
2451
|
-
return sendJson4(res, 200, { ok: true });
|
|
2452
|
-
}
|
|
2453
|
-
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
2454
|
-
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
2455
|
-
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
2456
|
-
}
|
|
2457
|
-
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
2458
|
-
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
2459
|
-
}
|
|
2460
|
-
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
2461
|
-
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
2462
|
-
}
|
|
2463
|
-
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
|
|
2464
|
-
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
|
|
2465
|
-
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
2466
|
-
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
2467
|
-
}
|
|
2468
|
-
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
2469
|
-
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
2470
|
-
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
2471
|
-
}
|
|
2472
|
-
if (method === "POST" && pathname === "/testkit/reset") {
|
|
2473
|
-
context.reset();
|
|
2474
|
-
return sendJson4(res, 200, { ok: true });
|
|
2475
|
-
}
|
|
2476
|
-
if (method === "POST" && pathname === "/testkit/token") {
|
|
2477
|
-
const body = await readJson(req);
|
|
2478
|
-
const accessToken = await issueToken(testkit, seed, body);
|
|
2479
|
-
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
2480
|
-
}
|
|
2481
|
-
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
2482
|
-
}
|
|
2483
|
-
function discovery(testkit) {
|
|
2484
|
-
const base = testkit.issuer;
|
|
2485
|
-
return {
|
|
2486
|
-
issuer: base,
|
|
2487
|
-
authorization_endpoint: `${base}/oauth2/auth`,
|
|
2488
|
-
token_endpoint: `${base}/oauth2/token`,
|
|
2489
|
-
userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
|
|
2490
|
-
end_session_endpoint: `${base}/logout`,
|
|
2491
|
-
revocation_endpoint: `${base}/oauth2/revoke`,
|
|
2492
|
-
jwks_uri: `${base}/.well-known/jwks`,
|
|
2493
|
-
response_types_supported: ["code"],
|
|
2494
|
-
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
2495
|
-
code_challenge_methods_supported: ["S256", "plain"],
|
|
2496
|
-
subject_types_supported: ["public"],
|
|
2497
|
-
id_token_signing_alg_values_supported: ["RS256"],
|
|
2498
|
-
scopes_supported: ["openid", "profile", "email", "offline"],
|
|
2499
|
-
token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic", "none"],
|
|
2500
|
-
claims_supported: ["aud", "exp", "iat", "iss", "sub", "org_code", "permissions", "roles", "scp"]
|
|
2501
|
-
};
|
|
2502
|
-
}
|
|
2503
|
-
async function issueToken(testkit, seed, body) {
|
|
2504
|
-
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
2505
|
-
throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
|
|
2506
|
-
}
|
|
2507
|
-
const input = body;
|
|
2508
|
-
const invalid2 = optionalString(input, "invalid");
|
|
2509
|
-
if (invalid2 !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid2)) {
|
|
2510
|
-
throw new TestkitError("INVALID_REQUEST", `"${invalid2}" is not a known invalid token kind.`, [
|
|
2511
|
-
`Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
|
|
2512
|
-
]);
|
|
2513
|
-
}
|
|
2514
|
-
const expiresIn = input.expiresIn;
|
|
2515
|
-
if (input.m2m === true) {
|
|
2516
|
-
const clientId = optionalString(input, "clientId");
|
|
2517
|
-
const app = clientId ? seed.applications.find((a) => a.clientId === clientId) : void 0;
|
|
2518
|
-
const scopes = optionalStrings(input, "scopes") ?? [];
|
|
2519
|
-
return testkit.m2mToken({
|
|
2520
|
-
clientId,
|
|
2521
|
-
organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? app?.organizationCode ?? null,
|
|
2522
|
-
scopes,
|
|
2523
|
-
grantedScopes: app?.scopes ? scopes.filter((scope) => app.scopes.includes(scope)) : scopes,
|
|
2524
|
-
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
2525
|
-
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
2526
|
-
expiresIn,
|
|
2527
|
-
invalid: invalid2
|
|
2528
|
-
});
|
|
2529
|
-
}
|
|
2530
|
-
const permissions = optionalStrings(input, "permissions");
|
|
2531
|
-
const roles = optionalStrings(input, "roles");
|
|
2532
|
-
const userRef = optionalString(input, "user");
|
|
2533
|
-
if (userRef) {
|
|
2534
|
-
const scenario = seedScenario(seed, {
|
|
2535
|
-
user: userRef,
|
|
2536
|
-
organization: optionalString(input, "organization") ?? null
|
|
2537
|
-
});
|
|
2538
|
-
if (permissions) scenario.permissions = permissions;
|
|
2539
|
-
if (roles) scenario.roles = roles;
|
|
2540
|
-
return await testkit.tokenFor(scenario, {
|
|
2541
|
-
expiresIn,
|
|
2542
|
-
invalid: invalid2,
|
|
2543
|
-
featureFlags: featureFlagsFor(seed, scenario.organization?.code ?? null)
|
|
2544
|
-
});
|
|
2545
|
-
}
|
|
2546
|
-
const options = {
|
|
2547
|
-
subject: optionalString(input, "subject"),
|
|
2548
|
-
organizationCode: optionalString(input, "organizationCode") ?? optionalString(input, "organization") ?? null,
|
|
2549
|
-
permissions,
|
|
2550
|
-
roles,
|
|
2551
|
-
scopes: optionalStrings(input, "scopes"),
|
|
2552
|
-
expiresIn,
|
|
2553
|
-
invalid: invalid2
|
|
2554
|
-
};
|
|
2555
|
-
if (typeof input.claims === "object" && input.claims !== null) {
|
|
2556
|
-
options.claims = input.claims;
|
|
2557
|
-
}
|
|
2558
|
-
return testkit.token(options);
|
|
2559
|
-
}
|
|
2560
|
-
function optionalString(input, field) {
|
|
2561
|
-
const value = input[field];
|
|
2562
|
-
if (value === void 0 || value === null) return void 0;
|
|
2563
|
-
if (typeof value !== "string") {
|
|
2564
|
-
throw new TestkitError("INVALID_REQUEST", `"${field}" must be a string.`);
|
|
2565
|
-
}
|
|
2566
|
-
return value;
|
|
2567
|
-
}
|
|
2568
|
-
function optionalStrings(input, field) {
|
|
2569
|
-
const value = input[field];
|
|
2570
|
-
if (value === void 0) return void 0;
|
|
2571
|
-
if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
|
|
2572
|
-
throw new TestkitError("INVALID_REQUEST", `"${field}" must be a list of strings.`);
|
|
2573
|
-
}
|
|
2574
|
-
return value;
|
|
2575
|
-
}
|
|
2576
|
-
async function readForm(req) {
|
|
2577
|
-
const text = await readText(req);
|
|
2578
|
-
if ((req.headers["content-type"] ?? "").includes("application/json")) {
|
|
2579
|
-
try {
|
|
2580
|
-
const parsed = JSON.parse(text || "{}");
|
|
2581
|
-
return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));
|
|
2582
|
-
} catch {
|
|
2583
|
-
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
2584
|
-
}
|
|
2585
|
-
}
|
|
2586
|
-
return Object.fromEntries(new URLSearchParams(text));
|
|
2587
|
-
}
|
|
2588
|
-
async function readJson(req) {
|
|
2589
|
-
const text = await readText(req);
|
|
2590
|
-
if (text.length === 0) return {};
|
|
2591
|
-
try {
|
|
2592
|
-
return JSON.parse(text);
|
|
2593
|
-
} catch {
|
|
2594
|
-
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
2595
|
-
}
|
|
2596
|
-
}
|
|
2597
|
-
async function readText(req) {
|
|
2598
|
-
const chunks = [];
|
|
2599
|
-
let size = 0;
|
|
2600
|
-
for await (const chunk of req) {
|
|
2601
|
-
size += chunk.length;
|
|
2602
|
-
if (size > MAX_BODY_BYTES) {
|
|
2603
|
-
throw new TestkitError("INVALID_REQUEST", "The request body is larger than 64 KB.");
|
|
2604
|
-
}
|
|
2605
|
-
chunks.push(chunk);
|
|
2606
|
-
}
|
|
2607
|
-
return Buffer.concat(chunks).toString("utf8").trim();
|
|
2608
|
-
}
|
|
2609
|
-
function sendJson4(res, status, body, headers = {}) {
|
|
2610
|
-
res.writeHead(status, {
|
|
2611
|
-
"content-type": "application/json; charset=utf-8",
|
|
2612
|
-
"cache-control": "no-store",
|
|
2613
|
-
...headers
|
|
2614
|
-
});
|
|
2615
|
-
res.end(JSON.stringify(body));
|
|
2616
|
-
}
|
|
2617
|
-
function sendError(res, error) {
|
|
2618
|
-
if (res.headersSent) {
|
|
2619
|
-
res.end();
|
|
2620
|
-
return;
|
|
2621
|
-
}
|
|
2622
|
-
if (error instanceof TestkitError) {
|
|
2623
|
-
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
2624
|
-
return;
|
|
2625
|
-
}
|
|
2626
|
-
sendJson4(res, 500, {
|
|
2627
|
-
error: "server_error",
|
|
2628
|
-
error_description: error instanceof Error ? error.message : String(error)
|
|
2629
|
-
});
|
|
2630
|
-
}
|
|
2631
|
-
|
|
2632
|
-
// src/inspect.ts
|
|
2633
|
-
import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, jwtVerify as jwtVerify2 } from "jose";
|
|
2634
|
-
async function inspectToken(token2, options = {}) {
|
|
2635
|
-
const checks = [];
|
|
2636
|
-
const trimmed = token2.trim();
|
|
2637
|
-
let header = null;
|
|
2638
|
-
let payload = null;
|
|
2639
|
-
if (trimmed.split(".").length !== 3) {
|
|
2640
|
-
checks.push({ name: "Format", status: "fail", detail: "A JWT has three parts separated by dots." });
|
|
2641
|
-
return { kind: "unknown", header, payload, checks };
|
|
2642
|
-
}
|
|
2643
|
-
try {
|
|
2644
|
-
header = decodeProtectedHeader(trimmed);
|
|
2645
|
-
payload = decodeJwt(trimmed);
|
|
2646
|
-
} catch {
|
|
2647
|
-
checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
|
|
2648
|
-
return { kind: "unknown", header, payload, checks };
|
|
2649
|
-
}
|
|
2650
|
-
checks.push({ name: "Format", status: "pass", detail: "Three base64url parts with JSON header and payload." });
|
|
2651
|
-
checks.push(
|
|
2652
|
-
header.alg === "RS256" ? { name: "Algorithm", status: "pass", detail: "RS256, the algorithm Kinde signs with." } : { name: "Algorithm", status: "fail", detail: `${String(header.alg)} is not RS256. Kinde tokens are always RS256.` }
|
|
2653
|
-
);
|
|
2654
|
-
const signer = typeof header.kid === "string" && header.kid.startsWith("kinde-testkit") ? "kinde-testkit" : "another issuer";
|
|
2655
|
-
checks.push({ name: "Key", status: "pass", detail: `kid ${String(header.kid ?? "missing")} (${signer}).` });
|
|
2656
|
-
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
2657
|
-
if (typeof payload.exp !== "number") {
|
|
2658
|
-
checks.push({ name: "Expiry", status: "fail", detail: "No exp claim." });
|
|
2659
|
-
} else if (payload.exp <= now) {
|
|
2660
|
-
checks.push({ name: "Expiry", status: "fail", detail: `Expired ${formatSpan(now - payload.exp)} ago.` });
|
|
2661
|
-
} else {
|
|
2662
|
-
checks.push({ name: "Expiry", status: "pass", detail: `Expires in ${formatSpan(payload.exp - now)}.` });
|
|
2663
|
-
}
|
|
2664
|
-
if (typeof payload.iat === "number" && payload.iat > now + 60) {
|
|
2665
|
-
checks.push({ name: "Issued at", status: "fail", detail: `iat is ${formatSpan(payload.iat - now)} in the future.` });
|
|
2666
|
-
}
|
|
2667
|
-
if (options.issuerUrl) {
|
|
2668
|
-
const issuer = options.issuerUrl.replace(/\/+$/, "");
|
|
2669
|
-
if (payload.iss !== issuer) {
|
|
2670
|
-
checks.push({ name: "Issuer", status: "fail", detail: `iss is ${String(payload.iss)}, not ${issuer}.` });
|
|
2671
|
-
} else {
|
|
2672
|
-
checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
|
|
2673
|
-
}
|
|
2674
|
-
try {
|
|
2675
|
-
await jwtVerify2(trimmed, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
|
|
2676
|
-
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
2677
|
-
} catch (error) {
|
|
2678
|
-
const code = error.code ?? "";
|
|
2679
|
-
if (code === "ERR_JWT_EXPIRED" || code === "ERR_JWT_CLAIM_VALIDATION_FAILED") {
|
|
2680
|
-
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
2681
|
-
} else {
|
|
2682
|
-
checks.push({ name: "Signature", status: "fail", detail: describeVerifyError(code, issuer) });
|
|
2683
|
-
}
|
|
2684
|
-
}
|
|
2685
|
-
} else {
|
|
2686
|
-
checks.push({ name: "Signature", status: "warn", detail: "Not checked. Pass --url to verify against a running issuer." });
|
|
2687
|
-
}
|
|
2688
|
-
return { kind: kindOf(payload), header, payload, checks };
|
|
2689
|
-
}
|
|
2690
|
-
function kindOf(payload) {
|
|
2691
|
-
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) return "m2m";
|
|
2692
|
-
if ("email" in payload || "org_codes" in payload || "at_hash" in payload || "nonce" in payload) return "id";
|
|
2693
|
-
if ("scp" in payload || "permissions" in payload || "org_code" in payload) return "access";
|
|
2694
|
-
return "unknown";
|
|
2695
|
-
}
|
|
2696
|
-
function describeVerifyError(code, issuer) {
|
|
2697
|
-
if (code === "ERR_JWKS_NO_MATCHING_KEY") return `No key in ${issuer}'s JWKS matches this token's kid.`;
|
|
2698
|
-
if (code === "ERR_JWS_SIGNATURE_VERIFICATION_FAILED") return "The signature does not match the token. It was changed after signing.";
|
|
2699
|
-
if (code === "ERR_JOSE_ALG_NOT_ALLOWED" || code === "ERR_JOSE_NOT_SUPPORTED") return "The token is not signed with RS256.";
|
|
2700
|
-
if (code === "ERR_JWKS_TIMEOUT" || code === "ERR_JOSE_GENERIC") return `Could not fetch keys from ${issuer}.`;
|
|
2701
|
-
return `Verification failed (${code || "unknown error"}).`;
|
|
2702
|
-
}
|
|
2703
|
-
function formatSpan(seconds) {
|
|
2704
|
-
const s = Math.max(0, Math.round(seconds));
|
|
2705
|
-
if (s < 60) return `${s}s`;
|
|
2706
|
-
if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
|
|
2707
|
-
if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor(s % 3600 / 60)}m`;
|
|
2708
|
-
return `${Math.floor(s / 86400)}d ${Math.floor(s % 86400 / 3600)}h`;
|
|
2709
|
-
}
|
|
2710
|
-
|
|
2711
|
-
// src/doctor.ts
|
|
2712
|
-
var SECRET_FORMAT = /^[a-zA-Z0-9]{40,60}$/;
|
|
2713
|
-
async function runDoctor(options) {
|
|
2714
|
-
const url = options.url.replace(/\/+$/, "");
|
|
2715
|
-
const checks = [];
|
|
2716
|
-
let issuer = null;
|
|
2717
|
-
try {
|
|
2718
|
-
const health = await (await fetch(`${url}/testkit/health`)).json();
|
|
2719
|
-
issuer = health.issuer ?? null;
|
|
2720
|
-
checks.push({ name: "Issuer running", status: "pass", detail: `${url} answers, issuer ${issuer}.` });
|
|
2721
|
-
} catch {
|
|
2722
|
-
checks.push({ name: "Issuer running", status: "fail", detail: `Nothing answers at ${url}. Start it with "kinde-testkit start".` });
|
|
2723
|
-
}
|
|
2724
|
-
if (issuer) {
|
|
2725
|
-
try {
|
|
2726
|
-
const discovery2 = await (await fetch(`${url}/.well-known/openid-configuration`)).json();
|
|
2727
|
-
checks.push(
|
|
2728
|
-
discovery2.issuer === issuer ? { name: "Discovery", status: "pass", detail: "The discovery document names the same issuer." } : { name: "Discovery", status: "fail", detail: `Discovery says ${String(discovery2.issuer)}, health says ${issuer}.` }
|
|
2729
|
-
);
|
|
2730
|
-
} catch {
|
|
2731
|
-
checks.push({ name: "Discovery", status: "fail", detail: "Could not read /.well-known/openid-configuration." });
|
|
2732
|
-
}
|
|
2733
|
-
try {
|
|
2734
|
-
const jwks = await (await fetch(`${url}/.well-known/jwks.json`)).json();
|
|
2735
|
-
const usable = (jwks.keys ?? []).filter((key) => key.kty === "RSA" && key.use === "sig");
|
|
2736
|
-
checks.push(
|
|
2737
|
-
usable.length > 0 ? { name: "JWKS", status: "pass", detail: `${usable.length} RS256 signing key at /.well-known/jwks.json.` } : { name: "JWKS", status: "fail", detail: "No RSA signing key at /.well-known/jwks.json." }
|
|
2738
|
-
);
|
|
2739
|
-
} catch {
|
|
2740
|
-
checks.push({ name: "JWKS", status: "fail", detail: "Could not read /.well-known/jwks.json." });
|
|
2741
|
-
}
|
|
2742
|
-
try {
|
|
2743
|
-
const users = await (await fetch(`${url}/testkit/users`)).json();
|
|
2744
|
-
checks.push(
|
|
2745
|
-
users.length > 0 ? { name: "Seed", status: "pass", detail: `${users.length} seeded ${users.length === 1 ? "user" : "users"}.` } : { name: "Seed", status: "warn", detail: "No seeded users. The sign-in page still accepts any email, but those users have no organization." }
|
|
2746
|
-
);
|
|
2747
|
-
} catch {
|
|
2748
|
-
checks.push({ name: "Seed", status: "warn", detail: "Could not read /testkit/users." });
|
|
2749
|
-
}
|
|
2750
|
-
}
|
|
2751
|
-
const env = options.env;
|
|
2752
|
-
const configured = env.KINDE_ISSUER_URL?.trim().replace(/\/+$/, "");
|
|
2753
|
-
if (!configured) {
|
|
2754
|
-
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: "Not set. Set it to the testkit's issuer for test runs." });
|
|
2755
|
-
} else if (/\.kinde\.com$/i.test(new URL(configured, "http://x").hostname)) {
|
|
2756
|
-
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} is a real Kinde domain. Tests would sign in against Kinde, not the testkit.` });
|
|
2757
|
-
} else if (issuer && configured !== issuer) {
|
|
2758
|
-
checks.push({ name: "KINDE_ISSUER_URL", status: "fail", detail: `${configured} does not match the testkit issuer ${issuer}. Token checks compare iss exactly.` });
|
|
2759
|
-
} else {
|
|
2760
|
-
checks.push({ name: "KINDE_ISSUER_URL", status: "pass", detail: `${configured}.` });
|
|
2761
|
-
}
|
|
2762
|
-
checks.push(
|
|
2763
|
-
env.KINDE_CLIENT_ID ? { name: "KINDE_CLIENT_ID", status: "pass", detail: "Set. The testkit accepts any client ID." } : { name: "KINDE_CLIENT_ID", status: "fail", detail: "Not set. Kinde's SDKs refuse to start without it." }
|
|
2764
|
-
);
|
|
2765
|
-
const secret = env.KINDE_CLIENT_SECRET;
|
|
2766
|
-
if (!secret) {
|
|
2767
|
-
checks.push({ name: "KINDE_CLIENT_SECRET", status: "warn", detail: "Not set. Server-side SDKs, such as the Next.js SDK, need it." });
|
|
2768
|
-
} else if (!SECRET_FORMAT.test(secret)) {
|
|
2769
|
-
checks.push({ name: "KINDE_CLIENT_SECRET", status: "fail", detail: "The Next.js SDK only accepts 40 to 60 letters and digits." });
|
|
2770
|
-
} else {
|
|
2771
|
-
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
2772
|
-
}
|
|
2773
|
-
if (issuer?.startsWith("https://")) {
|
|
2774
|
-
checks.push(
|
|
2775
|
-
env.NODE_EXTRA_CA_CERTS ? { name: "NODE_EXTRA_CA_CERTS", status: "pass", detail: `${env.NODE_EXTRA_CA_CERTS}.` } : {
|
|
2776
|
-
name: "NODE_EXTRA_CA_CERTS",
|
|
2777
|
-
status: "warn",
|
|
2778
|
-
detail: "The testkit serves HTTPS with a local certificate. Start your app with NODE_EXTRA_CA_CERTS set to it, or Node will refuse the connection."
|
|
2779
|
-
}
|
|
2780
|
-
);
|
|
2781
|
-
}
|
|
2782
|
-
const site = env.KINDE_SITE_URL;
|
|
2783
|
-
if (!site) {
|
|
2784
|
-
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
2785
|
-
} else if (!/^https?:\/\//.test(site)) {
|
|
2786
|
-
checks.push({ name: "KINDE_SITE_URL", status: "fail", detail: `${site} is not an http or https URL.` });
|
|
2787
|
-
} else {
|
|
2788
|
-
checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
|
|
2789
|
-
}
|
|
2790
|
-
return { url, checks, ok: checks.every((check) => check.status !== "fail") };
|
|
2791
|
-
}
|
|
2792
|
-
function parseEnvFile(text) {
|
|
2793
|
-
const values = {};
|
|
2794
|
-
for (const line of text.split(/\r?\n/)) {
|
|
2795
|
-
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
2796
|
-
if (!match) continue;
|
|
2797
|
-
let value = match[2];
|
|
2798
|
-
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
2799
|
-
value = value.slice(1, -1);
|
|
2800
|
-
} else {
|
|
2801
|
-
value = value.replace(/\s+#.*$/, "");
|
|
2802
|
-
}
|
|
2803
|
-
values[match[1]] = value;
|
|
2804
|
-
}
|
|
2805
|
-
return values;
|
|
2806
|
-
}
|
|
2807
|
-
|
|
2808
|
-
// src/cli.ts
|
|
21
|
+
import { spawnSync } from "child_process";
|
|
22
|
+
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
23
|
+
import { resolve } from "path";
|
|
24
|
+
import { parseArgs } from "util";
|
|
2809
25
|
var DEFAULT_URL = process.env.KINDE_TESTKIT_URL ?? "http://localhost:4400";
|
|
2810
|
-
var DEFAULT_SEED_FILE = "kinde-testkit.json";
|
|
2811
26
|
var HELP = `kinde-testkit: a local Kinde issuer for testing apps
|
|
2812
27
|
|
|
2813
28
|
Usage
|
|
2814
29
|
kinde-testkit start [options] Start the local issuer
|
|
30
|
+
kinde-testkit stop Stop a running issuer
|
|
31
|
+
kinde-testkit seed <file> Replace a running issuer's seed with a JSON, YAML, JS or TS file
|
|
2815
32
|
kinde-testkit token [options] Print a signed test access token
|
|
2816
33
|
kinde-testkit users [--json] List seeded users
|
|
2817
34
|
kinde-testkit organizations [--json] List seeded organizations
|
|
2818
35
|
kinde-testkit inspect [token] Decode a token and check it (reads stdin when no token)
|
|
36
|
+
kinde-testkit inspect --requests Show the latest requests the issuer answered
|
|
37
|
+
kinde-testkit coverage [options] Show which authentication scenarios your tests covered
|
|
2819
38
|
kinde-testkit doctor [options] Check your app's Kinde settings against the issuer
|
|
2820
39
|
kinde-testkit fail <path> [options] Make an endpoint fail, slow down or hang
|
|
2821
|
-
kinde-testkit reset Clear
|
|
40
|
+
kinde-testkit reset Clear sessions, failure rules, deliveries and API changes
|
|
2822
41
|
kinde-testkit webhook <type> [options] Send a signed webhook event
|
|
2823
42
|
kinde-testkit cert [--dir <dir>] Create the local HTTPS certificate and print its path
|
|
2824
43
|
|
|
@@ -2828,11 +47,13 @@ start
|
|
|
2828
47
|
--issuer <url> Issuer to put in tokens (default http://localhost:<port>)
|
|
2829
48
|
--audience <a,b> Audience values for access tokens
|
|
2830
49
|
--client-id <id> Value for azp
|
|
2831
|
-
--seed <file> Seed file (default ./kinde-testkit.json
|
|
50
|
+
--seed <file> Seed file: JSON, YAML, JS or TS (default ./kinde-testkit.json,
|
|
51
|
+
.yaml, .yml, .ts, .mts, .js or .mjs, the first that exists)
|
|
2832
52
|
--allow-public Allow binding to a non-loopback interface
|
|
2833
53
|
--webhook <url> Send webhooks to this URL (repeatable)
|
|
2834
54
|
--https Serve HTTPS with a local certificate (needed by @kinde/management-api-js)
|
|
2835
55
|
--cert-dir <dir> Where to keep that certificate (default ./.kinde-testkit)
|
|
56
|
+
--coverage Write authentication coverage to ./.kinde-testkit/coverage when it stops
|
|
2836
57
|
|
|
2837
58
|
token
|
|
2838
59
|
--url <url> Running issuer (default ${DEFAULT_URL})
|
|
@@ -2852,6 +73,15 @@ token
|
|
|
2852
73
|
|
|
2853
74
|
inspect
|
|
2854
75
|
--url <url> Also verify the issuer and signature against a running issuer
|
|
76
|
+
--requests List the latest requests instead of checking a token
|
|
77
|
+
--tokens List the latest issued tokens instead of checking a token
|
|
78
|
+
--json Print JSON
|
|
79
|
+
|
|
80
|
+
coverage
|
|
81
|
+
--url <url> Read a running issuer instead of the coverage folder
|
|
82
|
+
--dir <dir> Coverage folder (default ./${DEFAULT_COVERAGE_DIRECTORY.replace(/\\/g, "/")})
|
|
83
|
+
--min <n> Exit with an error when fewer than n scenarios are covered
|
|
84
|
+
--clear Delete the coverage folder, or clear a running issuer's coverage
|
|
2855
85
|
--json Print JSON
|
|
2856
86
|
|
|
2857
87
|
doctor
|
|
@@ -2906,6 +136,12 @@ async function main(argv) {
|
|
|
2906
136
|
return webhook(rest);
|
|
2907
137
|
case "cert":
|
|
2908
138
|
return cert(rest);
|
|
139
|
+
case "stop":
|
|
140
|
+
return stop(rest);
|
|
141
|
+
case "seed":
|
|
142
|
+
return seed(rest);
|
|
143
|
+
case "coverage":
|
|
144
|
+
return coverage(rest);
|
|
2909
145
|
case void 0:
|
|
2910
146
|
case "help":
|
|
2911
147
|
case "--help":
|
|
@@ -2930,21 +166,23 @@ async function start(args) {
|
|
|
2930
166
|
webhook: { type: "string", multiple: true },
|
|
2931
167
|
https: { type: "boolean" },
|
|
2932
168
|
"cert-dir": { type: "string" },
|
|
169
|
+
coverage: { type: "boolean" },
|
|
2933
170
|
json: { type: "boolean" }
|
|
2934
171
|
}
|
|
2935
172
|
});
|
|
2936
|
-
const seedPath = values.seed ?? (
|
|
2937
|
-
const
|
|
2938
|
-
if (
|
|
173
|
+
const seedPath = values.seed ?? findSeedFile();
|
|
174
|
+
const seed2 = seedPath ? await loadSeedFile(seedPath) : values.webhook ? {} : void 0;
|
|
175
|
+
if (seed2 && values.webhook) seed2.webhooks = [...seed2.webhooks ?? [], ...values.webhook.map((url) => ({ url }))];
|
|
2939
176
|
const running = await startKindeTestkit({
|
|
2940
177
|
port: values.port ? Number(values.port) : void 0,
|
|
2941
178
|
host: values.host,
|
|
2942
179
|
issuer: values.issuer,
|
|
2943
180
|
audience: values.audience ? csv(values.audience) : void 0,
|
|
2944
181
|
clientId: values["client-id"],
|
|
2945
|
-
seed,
|
|
182
|
+
seed: seed2,
|
|
2946
183
|
allowPublic: values["allow-public"],
|
|
2947
|
-
https: values.https ? { certDirectory: values["cert-dir"] } : void 0
|
|
184
|
+
https: values.https ? { certDirectory: values["cert-dir"] } : void 0,
|
|
185
|
+
coverage: values.coverage
|
|
2948
186
|
});
|
|
2949
187
|
if (values.json) {
|
|
2950
188
|
process.stdout.write(
|
|
@@ -2953,6 +191,7 @@ async function start(args) {
|
|
|
2953
191
|
issuer: running.issuer,
|
|
2954
192
|
discovery: running.discoveryUrl,
|
|
2955
193
|
jwks: running.jwksUri,
|
|
194
|
+
dashboard: `${running.url}/dashboard`,
|
|
2956
195
|
users: running.seed.users.length,
|
|
2957
196
|
organizations: running.seed.organizations.length
|
|
2958
197
|
})}
|
|
@@ -2971,8 +210,9 @@ async function start(args) {
|
|
|
2971
210
|
`JWKS: ${running.jwksUri}`,
|
|
2972
211
|
`Sign-in page: ${running.url}/oauth2/auth`,
|
|
2973
212
|
`Token: POST ${running.url}/testkit/token`,
|
|
213
|
+
`Dashboard: ${running.url}/dashboard`,
|
|
2974
214
|
"",
|
|
2975
|
-
`Seed: ${seedPath ?
|
|
215
|
+
`Seed: ${seedPath ? resolve(seedPath) : "none"}`,
|
|
2976
216
|
`Users: ${running.seed.users.length}`,
|
|
2977
217
|
`Organizations: ${running.seed.organizations.length}`,
|
|
2978
218
|
`Webhooks: ${running.webhooks.listEndpoints().map((e) => e.url).join(", ") || "none"}`,
|
|
@@ -2983,11 +223,11 @@ async function start(args) {
|
|
|
2983
223
|
].join("\n")
|
|
2984
224
|
);
|
|
2985
225
|
}
|
|
2986
|
-
const
|
|
226
|
+
const stop2 = () => {
|
|
2987
227
|
running.close().finally(() => process.exit(0));
|
|
2988
228
|
};
|
|
2989
|
-
process.once("SIGINT",
|
|
2990
|
-
process.once("SIGTERM",
|
|
229
|
+
process.once("SIGINT", stop2);
|
|
230
|
+
process.once("SIGTERM", stop2);
|
|
2991
231
|
}
|
|
2992
232
|
async function token(args) {
|
|
2993
233
|
const { values } = parseArgs({
|
|
@@ -3038,8 +278,31 @@ async function inspect(args) {
|
|
|
3038
278
|
const { values, positionals } = parseArgs({
|
|
3039
279
|
args,
|
|
3040
280
|
allowPositionals: true,
|
|
3041
|
-
options: { url: { type: "string" }, json: { type: "boolean" } }
|
|
281
|
+
options: { url: { type: "string" }, json: { type: "boolean" }, requests: { type: "boolean" }, tokens: { type: "boolean" } }
|
|
3042
282
|
});
|
|
283
|
+
if (values.requests) {
|
|
284
|
+
const entries = await request(values.url ?? DEFAULT_URL, "/testkit/requests");
|
|
285
|
+
if (values.json) return void process.stdout.write(`${JSON.stringify(entries, null, 2)}
|
|
286
|
+
`);
|
|
287
|
+
if (entries.length === 0) return void process.stdout.write("No requests yet.\n");
|
|
288
|
+
for (const e of entries) {
|
|
289
|
+
process.stdout.write(`${e.at.slice(11, 19)} ${String(e.status).padEnd(4)}${e.injected ? "injected " : ""}${e.method.padEnd(7)}${e.path} ${e.durationMs}ms
|
|
290
|
+
`);
|
|
291
|
+
}
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (values.tokens) {
|
|
295
|
+
const entries = await request(values.url ?? DEFAULT_URL, "/testkit/tokens");
|
|
296
|
+
if (values.json) return void process.stdout.write(`${JSON.stringify(entries, null, 2)}
|
|
297
|
+
`);
|
|
298
|
+
if (entries.length === 0) return void process.stdout.write("No tokens issued yet.\n");
|
|
299
|
+
for (const e of entries) {
|
|
300
|
+
const parts = [e.kind, e.subject ?? "no subject", e.organization ?? "no organization", e.permissions.join(",") || "no permissions"];
|
|
301
|
+
process.stdout.write(`${e.at.slice(11, 19)} ${parts.join(" ")}${e.invalid ? ` invalid: ${e.invalid}` : ""}
|
|
302
|
+
`);
|
|
303
|
+
}
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
3043
306
|
const raw = positionals[0] ?? (process.stdin.isTTY ? "" : await readStdin());
|
|
3044
307
|
const token2 = raw.trim().replace(/^Bearer\s+/i, "");
|
|
3045
308
|
if (!token2) {
|
|
@@ -3082,11 +345,11 @@ async function doctor(args) {
|
|
|
3082
345
|
json: { type: "boolean" }
|
|
3083
346
|
}
|
|
3084
347
|
});
|
|
3085
|
-
const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) =>
|
|
348
|
+
const files = values["env-file"] ?? [".env", ".env.local", ".env.test", ".env.test.local"].filter((file) => existsSync(file));
|
|
3086
349
|
const env = {};
|
|
3087
350
|
for (const file of files) {
|
|
3088
|
-
if (!
|
|
3089
|
-
Object.assign(env, parseEnvFile(
|
|
351
|
+
if (!existsSync(file)) throw new TestkitError("INVALID_REQUEST", `No env file at ${resolve(file)}.`);
|
|
352
|
+
Object.assign(env, parseEnvFile(readFileSync(file, "utf8")));
|
|
3090
353
|
}
|
|
3091
354
|
for (const [key, value] of Object.entries(process.env)) {
|
|
3092
355
|
if ((key.startsWith("KINDE_") || key === "NODE_EXTRA_CA_CERTS") && value !== void 0) env[key] = value;
|
|
@@ -3166,7 +429,79 @@ async function fail(args) {
|
|
|
3166
429
|
async function reset(args) {
|
|
3167
430
|
const { values } = parseArgs({ args, options: { url: { type: "string" } } });
|
|
3168
431
|
await request(values.url ?? DEFAULT_URL, "/testkit/reset", { method: "POST" });
|
|
3169
|
-
process.stdout.write("Cleared sign-in
|
|
432
|
+
process.stdout.write("Cleared sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.\n");
|
|
433
|
+
}
|
|
434
|
+
async function stop(args) {
|
|
435
|
+
const { values } = parseArgs({ args, options: { url: { type: "string" } } });
|
|
436
|
+
const url = values.url ?? DEFAULT_URL;
|
|
437
|
+
await request(url, "/testkit/stop", { method: "POST" });
|
|
438
|
+
process.stdout.write(`Stopped the issuer at ${url}.
|
|
439
|
+
`);
|
|
440
|
+
}
|
|
441
|
+
async function seed(args) {
|
|
442
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { url: { type: "string" }, json: { type: "boolean" } } });
|
|
443
|
+
const path = positionals[0] ?? findSeedFile();
|
|
444
|
+
if (!path) throw new TestkitError("INVALID_REQUEST", "Pass a seed file: kinde-testkit seed kinde-testkit.yaml");
|
|
445
|
+
const body = await loadSeedFile(path);
|
|
446
|
+
const result = await request(values.url ?? DEFAULT_URL, "/testkit/seed", {
|
|
447
|
+
method: "POST",
|
|
448
|
+
headers: { "content-type": "application/json" },
|
|
449
|
+
body: JSON.stringify(body)
|
|
450
|
+
});
|
|
451
|
+
if (values.json) return void process.stdout.write(`${JSON.stringify(result)}
|
|
452
|
+
`);
|
|
453
|
+
process.stdout.write(
|
|
454
|
+
`Loaded ${resolve(path)}: ${count(result.users, "user")}, ${count(result.organizations, "organization")}, ${count(result.memberships, "membership")}.
|
|
455
|
+
Sessions, failure rules and deliveries were cleared. The issuer, audience and signing key did not change.
|
|
456
|
+
`
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
function count(n, noun) {
|
|
460
|
+
return `${n} ${noun}${n === 1 ? "" : "s"}`;
|
|
461
|
+
}
|
|
462
|
+
async function coverage(args) {
|
|
463
|
+
const { values } = parseArgs({
|
|
464
|
+
args,
|
|
465
|
+
options: { url: { type: "string" }, dir: { type: "string" }, min: { type: "string" }, clear: { type: "boolean" }, json: { type: "boolean" } }
|
|
466
|
+
});
|
|
467
|
+
const directory = values.dir ?? DEFAULT_COVERAGE_DIRECTORY;
|
|
468
|
+
if (values.clear) {
|
|
469
|
+
if (values.url) await request(values.url, "/testkit/coverage", { method: "DELETE" });
|
|
470
|
+
else clearCoverageDirectory(directory);
|
|
471
|
+
process.stdout.write(values.url ? `Cleared coverage at ${values.url}.
|
|
472
|
+
` : `Deleted ${resolve(directory)}.
|
|
473
|
+
`);
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
let report;
|
|
477
|
+
let source;
|
|
478
|
+
if (values.url) {
|
|
479
|
+
report = (await request(values.url, "/testkit/coverage")).report;
|
|
480
|
+
source = values.url;
|
|
481
|
+
} else {
|
|
482
|
+
const read = readCoverageDirectory(directory);
|
|
483
|
+
if (read.files === 0) {
|
|
484
|
+
throw new TestkitError("INVALID_REQUEST", `No coverage recorded in ${resolve(directory)}.`, [
|
|
485
|
+
"Turn it on with useKindeTestkit({ coverage: true }), startKindeTestkit({ coverage: true }) or kinde-testkit start --coverage.",
|
|
486
|
+
"Or read a running issuer with --url."
|
|
487
|
+
]);
|
|
488
|
+
}
|
|
489
|
+
report = read.report;
|
|
490
|
+
source = `${read.files} test run${read.files === 1 ? "" : "s"} in ${resolve(directory)}`;
|
|
491
|
+
}
|
|
492
|
+
if (values.json) process.stdout.write(`${JSON.stringify(report, null, 2)}
|
|
493
|
+
`);
|
|
494
|
+
else process.stdout.write(`${formatCoverageReport(report)}
|
|
495
|
+
|
|
496
|
+
From ${source}.
|
|
497
|
+
`);
|
|
498
|
+
const min = values.min === void 0 ? void 0 : Number(values.min);
|
|
499
|
+
if (min !== void 0 && report.covered < min) {
|
|
500
|
+
process.stderr.write(`
|
|
501
|
+
Coverage ${report.covered}/${report.total} is below the minimum of ${min}.
|
|
502
|
+
`);
|
|
503
|
+
process.exitCode = 1;
|
|
504
|
+
}
|
|
3170
505
|
}
|
|
3171
506
|
async function readStdin() {
|
|
3172
507
|
const chunks = [];
|
|
@@ -3323,24 +658,10 @@ async function request(base, path, init) {
|
|
|
3323
658
|
if (!response.ok) {
|
|
3324
659
|
const details = Array.isArray(body.details) ? body.details : [];
|
|
3325
660
|
const message = String(body.error_description ?? `Request failed with ${response.status}`);
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
${message}
|
|
3329
|
-
${details.map((d) => ` - ${d}
|
|
3330
|
-
`).join("")}`);
|
|
3331
|
-
process.exit(1);
|
|
661
|
+
failWith(String(body.error ?? "ERROR"), message, details);
|
|
3332
662
|
}
|
|
3333
663
|
return body;
|
|
3334
664
|
}
|
|
3335
|
-
function readSeed(path) {
|
|
3336
|
-
try {
|
|
3337
|
-
return JSON.parse(readFileSync2(path, "utf8"));
|
|
3338
|
-
} catch (error) {
|
|
3339
|
-
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${resolve2(path)}.`, [
|
|
3340
|
-
error instanceof Error ? error.message : String(error)
|
|
3341
|
-
]);
|
|
3342
|
-
}
|
|
3343
|
-
}
|
|
3344
665
|
function csv(value) {
|
|
3345
666
|
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
3346
667
|
}
|
|
@@ -3348,15 +669,15 @@ function relaunchTrustingLocalCertificate(argv) {
|
|
|
3348
669
|
if (process.env.KINDE_TESTKIT_TRUSTED || argv[0] === "start" || argv[0] === "cert") return false;
|
|
3349
670
|
const urlArg = argv.find((arg, i) => arg.startsWith("--url=") || argv[i - 1] === "--url");
|
|
3350
671
|
const target = urlArg?.replace(/^--url=/, "") ?? process.env.KINDE_TESTKIT_URL ?? "";
|
|
3351
|
-
const certPath =
|
|
3352
|
-
if (!target.startsWith("https://") || !
|
|
672
|
+
const certPath = resolve(".kinde-testkit", "localhost-cert.pem");
|
|
673
|
+
if (!target.startsWith("https://") || !existsSync(certPath)) return false;
|
|
3353
674
|
let trusted = certPath;
|
|
3354
675
|
const existing = process.env.NODE_EXTRA_CA_CERTS;
|
|
3355
|
-
if (existing &&
|
|
3356
|
-
trusted =
|
|
3357
|
-
const current =
|
|
3358
|
-
|
|
3359
|
-
${
|
|
676
|
+
if (existing && resolve(existing) !== certPath) {
|
|
677
|
+
trusted = resolve(".kinde-testkit", "ca-bundle.pem");
|
|
678
|
+
const current = existsSync(existing) ? readFileSync(existing, "utf8") : "";
|
|
679
|
+
writeFileSync(trusted, `${current.trimEnd()}
|
|
680
|
+
${readFileSync(certPath, "utf8")}`);
|
|
3360
681
|
}
|
|
3361
682
|
const result = spawnSync(process.execPath, [process.argv[1], ...argv], {
|
|
3362
683
|
stdio: "inherit",
|
|
@@ -3364,13 +685,21 @@ ${readFileSync2(certPath, "utf8")}`);
|
|
|
3364
685
|
});
|
|
3365
686
|
process.exit(result.status ?? 1);
|
|
3366
687
|
}
|
|
3367
|
-
|
|
3368
|
-
if (
|
|
3369
|
-
process.
|
|
688
|
+
function failWith(code, message, details = []) {
|
|
689
|
+
if (process.argv.includes("--json")) {
|
|
690
|
+
process.stdout.write(`${JSON.stringify({ error: { code, message, details } })}
|
|
3370
691
|
`);
|
|
3371
692
|
} else {
|
|
3372
|
-
process.stderr.write(`${
|
|
3373
|
-
|
|
693
|
+
process.stderr.write(`${code}
|
|
694
|
+
|
|
695
|
+
${message}
|
|
696
|
+
${details.map((d) => ` - ${d}
|
|
697
|
+
`).join("")}`);
|
|
3374
698
|
}
|
|
3375
699
|
process.exit(1);
|
|
700
|
+
}
|
|
701
|
+
if (!relaunchTrustingLocalCertificate(process.argv.slice(2))) main(process.argv.slice(2)).catch((error) => {
|
|
702
|
+
if (error instanceof TestkitError) failWith(error.code, error.summary, error.details);
|
|
703
|
+
failWith("ERROR", error instanceof Error ? error.message : String(error));
|
|
3376
704
|
});
|
|
705
|
+
//# sourceMappingURL=cli.js.map
|