kinde-testkit 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +235 -11
- package/dist/cli.js +2160 -267
- package/dist/cypress-support.d.ts +98 -0
- package/dist/cypress-support.js +119 -0
- package/dist/cypress-support.js.map +1 -0
- package/dist/cypress.cjs +4249 -0
- package/dist/cypress.cjs.map +1 -0
- package/dist/cypress.d.cts +118 -0
- package/dist/cypress.d.ts +118 -0
- package/dist/cypress.js +3324 -0
- package/dist/cypress.js.map +1 -0
- package/dist/index.cjs +3270 -314
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +326 -2
- package/dist/index.d.ts +326 -2
- package/dist/index.js +1954 -150
- package/dist/index.js.map +1 -1
- package/dist/jest.cjs +4318 -0
- package/dist/jest.cjs.map +1 -0
- package/dist/jest.d.cts +567 -0
- package/dist/jest.d.ts +567 -0
- package/dist/jest.js +3392 -0
- package/dist/jest.js.map +1 -0
- package/dist/vitest.d.ts +236 -1
- package/dist/vitest.js +1853 -155
- package/dist/vitest.js.map +1 -1
- package/package.json +36 -3
package/dist/index.cjs
CHANGED
|
@@ -20,12 +20,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var src_exports = {};
|
|
22
22
|
__export(src_exports, {
|
|
23
|
+
ActivityLog: () => ActivityLog,
|
|
23
24
|
BILLING_EVENT_TYPES: () => BILLING_EVENT_TYPES,
|
|
25
|
+
COVERAGE_GROUPS: () => COVERAGE_GROUPS,
|
|
26
|
+
CoverageRecorder: () => CoverageRecorder,
|
|
24
27
|
DEFAULT_AUTH_METHODS: () => DEFAULT_AUTH_METHODS,
|
|
25
28
|
DEFAULT_CLIENT_ID: () => DEFAULT_CLIENT_ID,
|
|
29
|
+
DEFAULT_COVERAGE_DIRECTORY: () => DEFAULT_COVERAGE_DIRECTORY,
|
|
26
30
|
DEFAULT_ISSUER: () => DEFAULT_ISSUER,
|
|
27
31
|
DEFAULT_M2M_CLIENT_ID: () => DEFAULT_M2M_CLIENT_ID,
|
|
28
32
|
DEFAULT_SCOPES: () => DEFAULT_SCOPES,
|
|
33
|
+
DEFAULT_SEED_FILES: () => DEFAULT_SEED_FILES,
|
|
34
|
+
Directory: () => Directory,
|
|
29
35
|
FailureInjector: () => FailureInjector,
|
|
30
36
|
INVALID_TOKEN_KINDS: () => INVALID_TOKEN_KINDS,
|
|
31
37
|
KindeTestkit: () => KindeTestkit,
|
|
@@ -33,20 +39,35 @@ __export(src_exports, {
|
|
|
33
39
|
TestkitError: () => TestkitError,
|
|
34
40
|
WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
|
|
35
41
|
WebhookDispatcher: () => WebhookDispatcher,
|
|
42
|
+
appLoginUrl: () => appLoginUrl,
|
|
43
|
+
buildReport: () => buildReport,
|
|
44
|
+
clearCoverageDirectory: () => clearCoverageDirectory,
|
|
36
45
|
createKindeOrganization: () => createKindeOrganization,
|
|
37
46
|
createKindeToken: () => createKindeToken,
|
|
38
47
|
createKindeUser: () => createKindeUser,
|
|
48
|
+
createLocalCertificate: () => createLocalCertificate,
|
|
39
49
|
createMembership: () => createMembership,
|
|
50
|
+
ensureLocalCertificate: () => ensureLocalCertificate,
|
|
51
|
+
findSeedFile: () => findSeedFile,
|
|
52
|
+
formatCoverageReport: () => formatCoverageReport,
|
|
40
53
|
getDefaultTestkit: () => getDefaultTestkit,
|
|
41
54
|
inspectToken: () => inspectToken,
|
|
42
55
|
isAuthenticated: () => isAuthenticated,
|
|
56
|
+
kindeTest: () => kindeTest,
|
|
57
|
+
loadSeedFile: () => loadSeedFile,
|
|
58
|
+
mergeSnapshots: () => mergeSnapshots,
|
|
43
59
|
parseEnvFile: () => parseEnvFile,
|
|
44
60
|
principalFromClaims: () => principalFromClaims,
|
|
61
|
+
readCoverageDirectory: () => readCoverageDirectory,
|
|
62
|
+
readSignInRequest: () => readSignInRequest,
|
|
45
63
|
resetFactories: () => resetFactories,
|
|
64
|
+
resolveLocation: () => resolveLocation,
|
|
46
65
|
resolveSeed: () => resolveSeed,
|
|
47
66
|
runDoctor: () => runDoctor,
|
|
48
67
|
scenario: () => scenario,
|
|
49
68
|
seedScenario: () => seedScenario,
|
|
69
|
+
signInFailure: () => signInFailure,
|
|
70
|
+
signInForm: () => signInForm,
|
|
50
71
|
startKindeTestkit: () => startKindeTestkit,
|
|
51
72
|
toKindeRole: () => toKindeRole
|
|
52
73
|
});
|
|
@@ -173,16 +194,1148 @@ function isAuthenticated(value) {
|
|
|
173
194
|
|
|
174
195
|
// src/testkit.ts
|
|
175
196
|
var import_node_crypto2 = require("crypto");
|
|
176
|
-
|
|
197
|
+
|
|
198
|
+
// node_modules/jose/dist/webapi/lib/buffer_utils.js
|
|
199
|
+
var encoder = new TextEncoder();
|
|
200
|
+
var decoder = new TextDecoder();
|
|
201
|
+
var strictDecoder = new TextDecoder("utf-8", { fatal: true });
|
|
202
|
+
var UINT32_RANGE = 2 ** 32;
|
|
203
|
+
function concat(...buffers) {
|
|
204
|
+
const size = buffers.reduce((acc, { length: length2 }) => acc + length2, 0), buf = new Uint8Array(size);
|
|
205
|
+
let i = 0;
|
|
206
|
+
for (const buffer of buffers)
|
|
207
|
+
buf.set(buffer, i), i += buffer.length;
|
|
208
|
+
return buf;
|
|
209
|
+
}
|
|
210
|
+
var NON_ASCII = /[^\x00-\x7f]/;
|
|
211
|
+
function encode(string) {
|
|
212
|
+
if (typeof string == "string" && string.length >= 128) {
|
|
213
|
+
if (NON_ASCII.test(string))
|
|
214
|
+
throw new TypeError("non-ASCII string encountered in encode()");
|
|
215
|
+
return encoder.encode(string);
|
|
216
|
+
}
|
|
217
|
+
const bytes = new Uint8Array(string.length);
|
|
218
|
+
for (let i = 0; i < string.length; i++) {
|
|
219
|
+
const code = string.charCodeAt(i);
|
|
220
|
+
if (code > 127)
|
|
221
|
+
throw new TypeError("non-ASCII string encountered in encode()");
|
|
222
|
+
bytes[i] = code;
|
|
223
|
+
}
|
|
224
|
+
return bytes;
|
|
225
|
+
}
|
|
226
|
+
function encodeBase64(input, url = false) {
|
|
227
|
+
if (Uint8Array.prototype.toBase64)
|
|
228
|
+
return input.toBase64({ alphabet: url ? "base64url" : "base64", omitPadding: url });
|
|
229
|
+
const CHUNK_SIZE = 32768, arr = [];
|
|
230
|
+
for (let i = 0; i < input.length; i += CHUNK_SIZE)
|
|
231
|
+
arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
232
|
+
const encoded = btoa(arr.join(""));
|
|
233
|
+
return url ? encoded.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_") : encoded;
|
|
234
|
+
}
|
|
235
|
+
function decodeBase64(encoded, url = false) {
|
|
236
|
+
if (Uint8Array.fromBase64)
|
|
237
|
+
return Uint8Array.fromBase64(encoded, { alphabet: url ? "base64url" : "base64" });
|
|
238
|
+
if (url) {
|
|
239
|
+
if (encoded.includes("+") || encoded.includes("/"))
|
|
240
|
+
throw new TypeError("Invalid base64url");
|
|
241
|
+
encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
242
|
+
}
|
|
243
|
+
const binary = atob(encoded), bytes = new Uint8Array(binary.length);
|
|
244
|
+
for (let i = 0; i < binary.length; i++)
|
|
245
|
+
bytes[i] = binary.charCodeAt(i);
|
|
246
|
+
return bytes;
|
|
247
|
+
}
|
|
248
|
+
async function digest(algorithm, data) {
|
|
249
|
+
const subtleDigest = `SHA-${algorithm.slice(-3)}`;
|
|
250
|
+
return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// node_modules/jose/dist/webapi/util/errors.js
|
|
254
|
+
var JOSEError = class extends Error {
|
|
255
|
+
static code = "ERR_JOSE_GENERIC";
|
|
256
|
+
code = "ERR_JOSE_GENERIC";
|
|
257
|
+
constructor(message2, options) {
|
|
258
|
+
super(message2, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
var JWTClaimValidationFailed = class extends JOSEError {
|
|
262
|
+
static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
263
|
+
code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
264
|
+
claim;
|
|
265
|
+
reason;
|
|
266
|
+
payload;
|
|
267
|
+
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
268
|
+
super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
var JWTExpired = class extends JOSEError {
|
|
272
|
+
static code = "ERR_JWT_EXPIRED";
|
|
273
|
+
code = "ERR_JWT_EXPIRED";
|
|
274
|
+
claim;
|
|
275
|
+
reason;
|
|
276
|
+
payload;
|
|
277
|
+
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
278
|
+
super(message2, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
var JOSEAlgNotAllowed = class extends JOSEError {
|
|
282
|
+
static code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
283
|
+
code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
284
|
+
};
|
|
285
|
+
var JOSENotSupported = class extends JOSEError {
|
|
286
|
+
static code = "ERR_JOSE_NOT_SUPPORTED";
|
|
287
|
+
code = "ERR_JOSE_NOT_SUPPORTED";
|
|
288
|
+
};
|
|
289
|
+
var JWSInvalid = class extends JOSEError {
|
|
290
|
+
static code = "ERR_JWS_INVALID";
|
|
291
|
+
code = "ERR_JWS_INVALID";
|
|
292
|
+
};
|
|
293
|
+
var JWTInvalid = class extends JOSEError {
|
|
294
|
+
static code = "ERR_JWT_INVALID";
|
|
295
|
+
code = "ERR_JWT_INVALID";
|
|
296
|
+
};
|
|
297
|
+
var JWKInvalid = class extends JOSEError {
|
|
298
|
+
static code = "ERR_JWK_INVALID";
|
|
299
|
+
code = "ERR_JWK_INVALID";
|
|
300
|
+
};
|
|
301
|
+
var JWKSInvalid = class extends JOSEError {
|
|
302
|
+
static code = "ERR_JWKS_INVALID";
|
|
303
|
+
code = "ERR_JWKS_INVALID";
|
|
304
|
+
};
|
|
305
|
+
var JWKSNoMatchingKey = class extends JOSEError {
|
|
306
|
+
static code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
307
|
+
code = "ERR_JWKS_NO_MATCHING_KEY";
|
|
308
|
+
constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
|
|
309
|
+
super(message2, options);
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
var JWKSMultipleMatchingKeys = class extends JOSEError {
|
|
313
|
+
[Symbol.asyncIterator] = async function* () {
|
|
314
|
+
};
|
|
315
|
+
static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
316
|
+
code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
|
|
317
|
+
constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
|
|
318
|
+
super(message2, options);
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
var JWKSTimeout = class extends JOSEError {
|
|
322
|
+
static code = "ERR_JWKS_TIMEOUT";
|
|
323
|
+
code = "ERR_JWKS_TIMEOUT";
|
|
324
|
+
constructor(message2 = "request timed out", options) {
|
|
325
|
+
super(message2, options);
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
var JWSSignatureVerificationFailed = class extends JOSEError {
|
|
329
|
+
static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
330
|
+
code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
331
|
+
constructor(message2 = "signature verification failed", options) {
|
|
332
|
+
super(message2, options);
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
// node_modules/jose/dist/webapi/util/base64url.js
|
|
337
|
+
var base64url_exports = {};
|
|
338
|
+
__export(base64url_exports, {
|
|
339
|
+
decode: () => decode,
|
|
340
|
+
encode: () => encode2
|
|
341
|
+
});
|
|
342
|
+
var invalid = "The input to be decoded is not correctly encoded.";
|
|
343
|
+
function decode(input) {
|
|
344
|
+
try {
|
|
345
|
+
return decodeBase64(typeof input == "string" ? input : decoder.decode(input), true);
|
|
346
|
+
} catch (cause) {
|
|
347
|
+
throw new TypeError(invalid, { cause });
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function encode2(input) {
|
|
351
|
+
return encodeBase64(typeof input == "string" ? encoder.encode(input) : input, true);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// node_modules/jose/dist/webapi/lib/validate.js
|
|
355
|
+
function isObject(input) {
|
|
356
|
+
if (typeof input != "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]")
|
|
357
|
+
return false;
|
|
358
|
+
const prototype = Object.getPrototypeOf(input);
|
|
359
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
360
|
+
}
|
|
361
|
+
function isJwkSet(input) {
|
|
362
|
+
return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);
|
|
363
|
+
}
|
|
364
|
+
function isDisjoint(...headers) {
|
|
365
|
+
const parameters = /* @__PURE__ */ new Set();
|
|
366
|
+
for (const header of headers)
|
|
367
|
+
if (header)
|
|
368
|
+
for (const parameter of Object.keys(header)) {
|
|
369
|
+
if (parameters.has(parameter))
|
|
370
|
+
return false;
|
|
371
|
+
parameters.add(parameter);
|
|
372
|
+
}
|
|
373
|
+
return true;
|
|
374
|
+
}
|
|
375
|
+
function assertNotSet(value, name) {
|
|
376
|
+
if (value !== void 0)
|
|
377
|
+
throw new TypeError(`${name} can only be called once`);
|
|
378
|
+
}
|
|
379
|
+
function decodeBase64url(value, label, ErrorClass) {
|
|
380
|
+
try {
|
|
381
|
+
return decode(value);
|
|
382
|
+
} catch (cause) {
|
|
383
|
+
throw new ErrorClass(`Failed to base64url decode the ${label}`, { cause });
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
function encodeAsciiMember(value, label, ErrorClass) {
|
|
387
|
+
try {
|
|
388
|
+
return encode(value);
|
|
389
|
+
} catch (cause) {
|
|
390
|
+
throw new ErrorClass(`The ${label} is not a valid base64url string`, { cause });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
function parseJoseHeader(encodedProtectedHeader, ErrorClass, message2) {
|
|
394
|
+
let parsed;
|
|
395
|
+
try {
|
|
396
|
+
parsed = JSON.parse(strictDecoder.decode(decode(encodedProtectedHeader)));
|
|
397
|
+
} catch (cause) {
|
|
398
|
+
throw new ErrorClass(message2, { cause });
|
|
399
|
+
}
|
|
400
|
+
if (!isObject(parsed))
|
|
401
|
+
throw new ErrorClass(message2);
|
|
402
|
+
return parsed;
|
|
403
|
+
}
|
|
404
|
+
var JWS_RECOGNIZED = { __proto__: null, b64: true };
|
|
405
|
+
function validateAlgorithms(option, algorithms) {
|
|
406
|
+
if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != "string")))
|
|
407
|
+
throw new TypeError(`"${option}" option must be an array of strings`);
|
|
408
|
+
return algorithms === void 0 ? void 0 : new Set(algorithms);
|
|
409
|
+
}
|
|
410
|
+
function validateCritDuplicates(Err, protectedHeader) {
|
|
411
|
+
const { crit } = protectedHeader ?? {};
|
|
412
|
+
if (Array.isArray(crit) && new Set(crit).size !== crit.length)
|
|
413
|
+
throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
|
|
414
|
+
}
|
|
415
|
+
function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
|
|
416
|
+
if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)
|
|
417
|
+
throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
|
|
418
|
+
if (!protectedHeader || protectedHeader.crit === void 0)
|
|
419
|
+
return [];
|
|
420
|
+
if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != "string" || input.length === 0))
|
|
421
|
+
throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
|
|
422
|
+
const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
|
|
423
|
+
for (const parameter of protectedHeader.crit) {
|
|
424
|
+
if (!(parameter in recognized))
|
|
425
|
+
throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
426
|
+
if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)
|
|
427
|
+
throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
428
|
+
if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))
|
|
429
|
+
throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
430
|
+
}
|
|
431
|
+
return protectedHeader.crit;
|
|
432
|
+
}
|
|
433
|
+
function validateB64(protectedHeader, extensions) {
|
|
434
|
+
if (extensions.includes("b64")) {
|
|
435
|
+
const b64 = protectedHeader.b64;
|
|
436
|
+
if (typeof b64 != "boolean")
|
|
437
|
+
throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
|
438
|
+
return b64;
|
|
439
|
+
}
|
|
440
|
+
return true;
|
|
441
|
+
}
|
|
442
|
+
function serializeJoseHeader(Err, header) {
|
|
443
|
+
let serialized, parsed;
|
|
444
|
+
try {
|
|
445
|
+
serialized = JSON.stringify(header), parsed = JSON.parse(serialized);
|
|
446
|
+
} catch (cause) {
|
|
447
|
+
throw new Err("JOSE Header is not valid JSON", { cause });
|
|
448
|
+
}
|
|
449
|
+
if (!isObject(parsed))
|
|
450
|
+
throw new Err("JOSE Header is not a JSON object");
|
|
451
|
+
return [parsed, serialized];
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// node_modules/jose/dist/webapi/lib/key.js
|
|
455
|
+
var tag = (key) => key[Symbol.toStringTag];
|
|
456
|
+
var jwkMatchesOp = (entry, key, usage) => {
|
|
457
|
+
const { alg } = entry;
|
|
458
|
+
if (key.use !== void 0) {
|
|
459
|
+
const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
|
|
460
|
+
if (key.use !== expected)
|
|
461
|
+
throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
462
|
+
}
|
|
463
|
+
if (key.alg !== void 0 && key.alg !== alg)
|
|
464
|
+
throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
|
|
465
|
+
if (Array.isArray(key.key_ops)) {
|
|
466
|
+
const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
|
|
467
|
+
if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))
|
|
468
|
+
throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
async function prepareKey(entry, key, usage) {
|
|
472
|
+
const { alg, secret } = entry, requiresPrivateKey = usage === "decrypt" || usage === "sign";
|
|
473
|
+
if (secret && key instanceof Uint8Array)
|
|
474
|
+
return key;
|
|
475
|
+
let normalized, keyObject;
|
|
476
|
+
if (isObject(key)) {
|
|
477
|
+
if (normalized = normalizeJwk(key), typeof normalized.kty != "string")
|
|
478
|
+
throw invalidKeyType(alg, key, secret);
|
|
479
|
+
if (!(secret ? normalized.kty === "oct" && typeof normalized.k == "string" : normalized.kty !== "oct" && (requiresPrivateKey ? normalized.kty === "AKP" && typeof normalized.priv == "string" || typeof normalized.d == "string" : normalized.d === void 0 && normalized.priv === void 0)))
|
|
480
|
+
throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present' : `JSON Web Key for this operation must be a ${requiresPrivateKey ? "private" : "public"} JWK`);
|
|
481
|
+
if (jwkMatchesOp(entry, normalized, usage), normalized.kty === "oct")
|
|
482
|
+
return decode(normalized.k);
|
|
483
|
+
if (!Object.isFrozen(key)) {
|
|
484
|
+
const { key_ops } = key;
|
|
485
|
+
Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);
|
|
486
|
+
}
|
|
487
|
+
} else {
|
|
488
|
+
if (!isKeyLike(key))
|
|
489
|
+
throw invalidKeyType(alg, key, secret);
|
|
490
|
+
const expectedType = secret ? "secret" : requiresPrivateKey ? "private" : "public";
|
|
491
|
+
if (key.type !== expectedType && (secret || ["secret", "public", "private"].includes(key.type)))
|
|
492
|
+
throw new TypeError(`${tag(key)} instances must be of type "${expectedType}" for the ${alg} algorithm`);
|
|
493
|
+
if (isCryptoKey(key))
|
|
494
|
+
return key;
|
|
495
|
+
if (keyObject = key, keyObject.type === "secret")
|
|
496
|
+
return keyObject.export();
|
|
497
|
+
}
|
|
498
|
+
cache ||= /* @__PURE__ */ new WeakMap();
|
|
499
|
+
const cacheKey = key;
|
|
500
|
+
let cached = cache.get(cacheKey);
|
|
501
|
+
if (cached?.[alg])
|
|
502
|
+
return cached[alg];
|
|
503
|
+
if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == "function") {
|
|
504
|
+
const isPublic = keyObject.type === "public", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;
|
|
505
|
+
return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);
|
|
506
|
+
}
|
|
507
|
+
return normalized ??= keyObject.export({ format: "jwk" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);
|
|
508
|
+
}
|
|
509
|
+
var cache;
|
|
510
|
+
var nist = {
|
|
511
|
+
__proto__: null,
|
|
512
|
+
prime256v1: "P-256",
|
|
513
|
+
secp384r1: "P-384",
|
|
514
|
+
secp521r1: "P-521"
|
|
515
|
+
};
|
|
516
|
+
var isCryptoKey = (key) => {
|
|
517
|
+
if (key?.[Symbol.toStringTag] === "CryptoKey")
|
|
518
|
+
return true;
|
|
519
|
+
try {
|
|
520
|
+
return key instanceof CryptoKey;
|
|
521
|
+
} catch {
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
526
|
+
var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
527
|
+
function message(msg, actual, ...types) {
|
|
528
|
+
if (types.length > 2) {
|
|
529
|
+
const last = types.pop();
|
|
530
|
+
msg += `one of type ${types.join(", ")}, or ${last}.`;
|
|
531
|
+
} else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;
|
|
532
|
+
return actual == null ? msg += ` Received ${actual}` : typeof actual == "function" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == "object" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;
|
|
533
|
+
}
|
|
534
|
+
var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
|
|
535
|
+
function invalidKeyType(alg, actual, secret) {
|
|
536
|
+
const types = ["CryptoKey", "KeyObject", "JSON Web Key"];
|
|
537
|
+
return secret && types.push("Uint8Array"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));
|
|
538
|
+
}
|
|
539
|
+
var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
|
540
|
+
function checkUsage(key, usage) {
|
|
541
|
+
if (usage && !key.usages.includes(usage))
|
|
542
|
+
throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
|
|
543
|
+
}
|
|
544
|
+
function checkModulusLength(alg, key) {
|
|
545
|
+
const { modulusLength } = key.algorithm;
|
|
546
|
+
if (typeof modulusLength != "number" || modulusLength < 2048)
|
|
547
|
+
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
548
|
+
}
|
|
549
|
+
function checkCryptoKey(key, expected, usage) {
|
|
550
|
+
const algorithm = key.algorithm;
|
|
551
|
+
if (algorithm.name !== expected.name)
|
|
552
|
+
throw unusable(expected.name);
|
|
553
|
+
if (expected.hash && algorithm.hash?.name !== expected.hash)
|
|
554
|
+
throw unusable(expected.hash, "algorithm.hash");
|
|
555
|
+
if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)
|
|
556
|
+
throw unusable(expected.namedCurve, "algorithm.namedCurve");
|
|
557
|
+
if (expected.length !== void 0 && algorithm.length !== expected.length)
|
|
558
|
+
throw unusable(expected.length, "algorithm.length");
|
|
559
|
+
checkUsage(key, usage);
|
|
560
|
+
}
|
|
561
|
+
function snapshotJwk(jwk) {
|
|
562
|
+
return { __proto__: null, ...jwk };
|
|
563
|
+
}
|
|
564
|
+
function normalizeJwk(jwk) {
|
|
565
|
+
const normalized = snapshotJwk(jwk);
|
|
566
|
+
if (normalized.ext !== void 0 && typeof normalized.ext != "boolean")
|
|
567
|
+
throw new TypeError('"ext" (Extractable) Parameter must be a boolean');
|
|
568
|
+
if (normalized.key_ops !== void 0) {
|
|
569
|
+
const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;
|
|
570
|
+
if (!keyOps || keyOps.some((operation) => typeof operation != "string") || new Set(keyOps).size !== keyOps.length)
|
|
571
|
+
throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');
|
|
572
|
+
normalized.key_ops = keyOps;
|
|
573
|
+
}
|
|
574
|
+
return normalized;
|
|
575
|
+
}
|
|
576
|
+
function validateExtractableOption(extractable) {
|
|
577
|
+
if (extractable !== void 0 && typeof extractable != "boolean")
|
|
578
|
+
throw new TypeError('"extractable" option must be a boolean');
|
|
579
|
+
return extractable;
|
|
580
|
+
}
|
|
581
|
+
async function jwkToKey(entry, jwk, extractable) {
|
|
582
|
+
if (!entry.kty.includes(jwk.kty))
|
|
583
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
584
|
+
const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };
|
|
585
|
+
return keyData.kty !== "AKP" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey("jwk", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
|
|
586
|
+
}
|
|
587
|
+
async function rawKey(key, expected, usage, extractable = false) {
|
|
588
|
+
return key instanceof Uint8Array && (key = await crypto.subtle.importKey("raw", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// node_modules/jose/dist/webapi/lib/key_descriptor.js
|
|
592
|
+
function table(entries) {
|
|
593
|
+
const out = { __proto__: null };
|
|
594
|
+
for (const alg in entries)
|
|
595
|
+
out[alg] = { ...entries[alg], alg };
|
|
596
|
+
return out;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// node_modules/jose/dist/webapi/lib/jwe_algorithms.js
|
|
600
|
+
var wrap = [
|
|
601
|
+
["encrypt", "wrapKey"],
|
|
602
|
+
["decrypt", "unwrapKey"]
|
|
603
|
+
];
|
|
604
|
+
var derive = [[], ["deriveBits"]];
|
|
605
|
+
var none = [[], []];
|
|
606
|
+
function rsaes(bits) {
|
|
607
|
+
return {
|
|
608
|
+
kty: ["RSA"],
|
|
609
|
+
mode: "key-encryption",
|
|
610
|
+
subtle: { name: "RSA-OAEP", hash: `SHA-${bits}` },
|
|
611
|
+
usages: wrap,
|
|
612
|
+
ops: ["wrapKey", "unwrapKey"]
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
function ecdh(mode) {
|
|
616
|
+
return {
|
|
617
|
+
kty: ["EC", "OKP"],
|
|
618
|
+
mode,
|
|
619
|
+
subtle: { name: "ECDH" },
|
|
620
|
+
resolve: ({ kty, crv, asymmetricKeyType }) => {
|
|
621
|
+
if (crv === "X25519" || asymmetricKeyType === "x25519")
|
|
622
|
+
return { name: "X25519" };
|
|
623
|
+
if (kty === "OKP")
|
|
624
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
625
|
+
return { name: "ECDH", namedCurve: crv };
|
|
626
|
+
},
|
|
627
|
+
usages: derive,
|
|
628
|
+
ops: [void 0, "deriveBits"]
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
function aeskw(bits, gcm = false) {
|
|
632
|
+
return {
|
|
633
|
+
kty: ["oct"],
|
|
634
|
+
mode: "key-wrapping",
|
|
635
|
+
secret: true,
|
|
636
|
+
subtle: { name: gcm ? "AES-GCM" : "AES-KW", length: bits },
|
|
637
|
+
usages: none,
|
|
638
|
+
ops: gcm ? ["encrypt", "decrypt"] : ["wrapKey", "unwrapKey"]
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
function pbes2() {
|
|
642
|
+
return {
|
|
643
|
+
kty: ["oct"],
|
|
644
|
+
mode: "key-wrapping",
|
|
645
|
+
secret: true,
|
|
646
|
+
subtle: { name: "PBKDF2" },
|
|
647
|
+
usages: none,
|
|
648
|
+
ops: ["deriveBits", "deriveBits"]
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
var JWE = table({
|
|
652
|
+
dir: {
|
|
653
|
+
kty: ["oct"],
|
|
654
|
+
mode: "direct-encryption",
|
|
655
|
+
secret: true,
|
|
656
|
+
subtle: { name: "AES-GCM" },
|
|
657
|
+
usages: none,
|
|
658
|
+
ops: ["encrypt", "decrypt"]
|
|
659
|
+
},
|
|
660
|
+
"RSA-OAEP": rsaes(1),
|
|
661
|
+
"RSA-OAEP-256": rsaes(256),
|
|
662
|
+
"RSA-OAEP-384": rsaes(384),
|
|
663
|
+
"RSA-OAEP-512": rsaes(512),
|
|
664
|
+
"ECDH-ES": ecdh("direct-key-agreement"),
|
|
665
|
+
"ECDH-ES+A128KW": ecdh("key-agreement-with-key-wrapping"),
|
|
666
|
+
"ECDH-ES+A192KW": ecdh("key-agreement-with-key-wrapping"),
|
|
667
|
+
"ECDH-ES+A256KW": ecdh("key-agreement-with-key-wrapping"),
|
|
668
|
+
A128KW: aeskw(128),
|
|
669
|
+
A192KW: aeskw(192),
|
|
670
|
+
A256KW: aeskw(256),
|
|
671
|
+
A128GCMKW: aeskw(128, true),
|
|
672
|
+
A192GCMKW: aeskw(192, true),
|
|
673
|
+
A256GCMKW: aeskw(256, true),
|
|
674
|
+
"PBES2-HS256+A128KW": pbes2(),
|
|
675
|
+
"PBES2-HS384+A192KW": pbes2(),
|
|
676
|
+
"PBES2-HS512+A256KW": pbes2()
|
|
677
|
+
});
|
|
678
|
+
var contentOps = ["encrypt", "decrypt"];
|
|
679
|
+
function contentEncryption(bits, cbc = false) {
|
|
680
|
+
return {
|
|
681
|
+
kty: ["oct"],
|
|
682
|
+
secret: true,
|
|
683
|
+
subtle: { name: cbc ? "AES-CBC" : "AES-GCM", length: bits },
|
|
684
|
+
usages: none,
|
|
685
|
+
ops: contentOps,
|
|
686
|
+
cekBits: bits,
|
|
687
|
+
ivBits: cbc ? 128 : 96,
|
|
688
|
+
cbc
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
var ENC = table({
|
|
692
|
+
A128GCM: contentEncryption(128),
|
|
693
|
+
A192GCM: contentEncryption(192),
|
|
694
|
+
A256GCM: contentEncryption(256),
|
|
695
|
+
"A128CBC-HS256": contentEncryption(256, true),
|
|
696
|
+
"A192CBC-HS384": contentEncryption(384, true),
|
|
697
|
+
"A256CBC-HS512": contentEncryption(512, true)
|
|
698
|
+
});
|
|
699
|
+
|
|
700
|
+
// node_modules/jose/dist/webapi/lib/jws_algorithms.js
|
|
701
|
+
var sig = [["verify"], ["sign"]];
|
|
702
|
+
function hmac(bits) {
|
|
703
|
+
const subtle = { name: "HMAC", hash: `SHA-${bits}` };
|
|
704
|
+
return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
|
|
705
|
+
}
|
|
706
|
+
function rsa(bits, saltLength) {
|
|
707
|
+
const subtle = { name: saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash: `SHA-${bits}` };
|
|
708
|
+
return {
|
|
709
|
+
kty: ["RSA"],
|
|
710
|
+
subtle,
|
|
711
|
+
signing: saltLength ? { ...subtle, saltLength } : subtle,
|
|
712
|
+
usages: sig,
|
|
713
|
+
minRsaBits: 2048
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
function ecdsa(crv, bits) {
|
|
717
|
+
return {
|
|
718
|
+
kty: ["EC"],
|
|
719
|
+
crv,
|
|
720
|
+
subtle: { name: "ECDSA", namedCurve: crv },
|
|
721
|
+
signing: { name: "ECDSA", hash: `SHA-${bits}` },
|
|
722
|
+
usages: sig
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
function eddsa() {
|
|
726
|
+
const subtle = { name: "Ed25519" };
|
|
727
|
+
return {
|
|
728
|
+
kty: ["OKP"],
|
|
729
|
+
crv: "Ed25519",
|
|
730
|
+
subtle,
|
|
731
|
+
signing: subtle,
|
|
732
|
+
usages: sig
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
function mldsa(parameterSet) {
|
|
736
|
+
const subtle = { name: `ML-DSA-${parameterSet}` };
|
|
737
|
+
return {
|
|
738
|
+
kty: ["AKP"],
|
|
739
|
+
subtle,
|
|
740
|
+
signing: subtle,
|
|
741
|
+
usages: sig
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
var JWS = table({
|
|
745
|
+
HS256: hmac(256),
|
|
746
|
+
HS384: hmac(384),
|
|
747
|
+
HS512: hmac(512),
|
|
748
|
+
RS256: rsa(256),
|
|
749
|
+
RS384: rsa(384),
|
|
750
|
+
RS512: rsa(512),
|
|
751
|
+
PS256: rsa(256, 32),
|
|
752
|
+
PS384: rsa(384, 48),
|
|
753
|
+
PS512: rsa(512, 64),
|
|
754
|
+
ES256: ecdsa("P-256", 256),
|
|
755
|
+
ES384: ecdsa("P-384", 384),
|
|
756
|
+
ES512: ecdsa("P-521", 512),
|
|
757
|
+
EdDSA: eddsa(),
|
|
758
|
+
Ed25519: eddsa(),
|
|
759
|
+
"ML-DSA-44": mldsa(44),
|
|
760
|
+
"ML-DSA-65": mldsa(65),
|
|
761
|
+
"ML-DSA-87": mldsa(87)
|
|
762
|
+
});
|
|
763
|
+
function jwsAlgorithm(alg) {
|
|
764
|
+
const entry = typeof alg == "string" ? JWS[alg] : void 0;
|
|
765
|
+
if (!entry)
|
|
766
|
+
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
767
|
+
return entry;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
// node_modules/jose/dist/webapi/lib/jws_verify.js
|
|
771
|
+
function prepareVerify(options) {
|
|
772
|
+
return [options && validateAlgorithms("algorithms", options.algorithms), options?.crit];
|
|
773
|
+
}
|
|
774
|
+
function parseProtectedHeader(encodedProtectedHeader) {
|
|
775
|
+
return encodedProtectedHeader === void 0 ? {} : parseJoseHeader(encodedProtectedHeader, JWSInvalid, "JWS Protected Header is invalid");
|
|
776
|
+
}
|
|
777
|
+
function encodeCompactUnencodedPayload(payload) {
|
|
778
|
+
try {
|
|
779
|
+
return encode(payload);
|
|
780
|
+
} catch (cause) {
|
|
781
|
+
throw new JWSInvalid("JWS Compact Serialization payload must use only ASCII characters", {
|
|
782
|
+
cause
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
async function verifySignature(jws, shared, key, encodeUnencodedPayload, parsedProtected) {
|
|
787
|
+
const { protected: encodedProtectedHeader, header, payload: inputPayload } = jws, protectedHeader = parsedProtected ?? parseProtectedHeader(encodedProtectedHeader);
|
|
788
|
+
if (!isDisjoint(protectedHeader, header))
|
|
789
|
+
throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
790
|
+
const joseHeader = { ...protectedHeader, ...header }, b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, shared[1], protectedHeader, joseHeader)), { alg } = joseHeader;
|
|
791
|
+
if (typeof alg != "string" || !alg)
|
|
792
|
+
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
793
|
+
if (shared[0] && !shared[0].has(alg))
|
|
794
|
+
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
|
795
|
+
if (b64) {
|
|
796
|
+
if (typeof inputPayload != "string")
|
|
797
|
+
throw new JWSInvalid("JWS Payload must be a string");
|
|
798
|
+
} else if (typeof inputPayload != "string" && !(inputPayload instanceof Uint8Array))
|
|
799
|
+
throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
|
|
800
|
+
const signingPayload = b64 || typeof inputPayload != "string" ? inputPayload : encodeUnencodedPayload(inputPayload);
|
|
801
|
+
let resolvedKey = false;
|
|
802
|
+
typeof key == "function" && (key = await key(protectedHeader, jws), resolvedKey = true);
|
|
803
|
+
const entry = jwsAlgorithm(alg), signingInput = concat(encodedProtectedHeader !== void 0 ? encode(encodedProtectedHeader) : new Uint8Array(), encode("."), typeof signingPayload == "string" ? shared[2] ??= encodeAsciiMember(signingPayload, "payload", JWSInvalid) : signingPayload), signature = decodeBase64url(jws.signature, "signature", JWSInvalid), verificationKey = await prepareKey(entry, key, "verify"), cryptoKey = await rawKey(verificationKey, entry.subtle, "verify");
|
|
804
|
+
entry.minRsaBits && checkModulusLength(entry.alg, cryptoKey);
|
|
805
|
+
let verified = false;
|
|
806
|
+
try {
|
|
807
|
+
verified = await crypto.subtle.verify(entry.signing, cryptoKey, signature, signingInput);
|
|
808
|
+
} catch (cause) {
|
|
809
|
+
throw new JWSSignatureVerificationFailed(void 0, { cause });
|
|
810
|
+
}
|
|
811
|
+
if (!verified)
|
|
812
|
+
throw new JWSSignatureVerificationFailed();
|
|
813
|
+
const result = { payload: typeof signingPayload == "string" ? decodeBase64url(signingPayload, "payload", JWSInvalid) : signingPayload };
|
|
814
|
+
return encodedProtectedHeader !== void 0 && (result.protectedHeader = protectedHeader), header !== void 0 && (result.unprotectedHeader = header), resolvedKey ? [{ ...result, key: verificationKey }, b64] : [result, b64];
|
|
815
|
+
}
|
|
816
|
+
async function verifyCompact(jws, shared, key) {
|
|
817
|
+
if (jws instanceof Uint8Array && (jws = decoder.decode(jws)), typeof jws != "string")
|
|
818
|
+
throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
|
|
819
|
+
const { 0: protectedHeader, 1: payload, 2: signature, length: length2 } = jws.split(".");
|
|
820
|
+
if (length2 !== 3)
|
|
821
|
+
throw new JWSInvalid("Invalid Compact JWS");
|
|
822
|
+
return verifySignature({ payload, protected: protectedHeader, signature }, shared, key, encodeCompactUnencodedPayload);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// node_modules/jose/dist/webapi/lib/jwt_claims_set.js
|
|
826
|
+
var epoch = (date) => Math.floor(date.getTime() / 1e3);
|
|
827
|
+
var multipliers = {
|
|
828
|
+
s: 1,
|
|
829
|
+
m: 60,
|
|
830
|
+
h: 3600,
|
|
831
|
+
d: 86400,
|
|
832
|
+
w: 604800,
|
|
833
|
+
y: 31557600
|
|
834
|
+
};
|
|
835
|
+
var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
|
|
836
|
+
var checkFailed = "check_failed";
|
|
837
|
+
function invalidDuration() {
|
|
838
|
+
throw new TypeError("Invalid time period format");
|
|
839
|
+
}
|
|
840
|
+
function secs(str2) {
|
|
841
|
+
typeof str2 != "string" && invalidDuration();
|
|
842
|
+
const matched = REGEX.exec(str2);
|
|
843
|
+
(!matched || matched[4] && matched[1]) && invalidDuration();
|
|
844
|
+
const value = parseFloat(matched[2]), durationSeconds = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
|
|
845
|
+
return Number.isFinite(durationSeconds) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -durationSeconds : durationSeconds;
|
|
846
|
+
}
|
|
847
|
+
function validateInput(label, input) {
|
|
848
|
+
if (!Number.isFinite(input))
|
|
849
|
+
throw new TypeError(`Invalid ${label} input`);
|
|
850
|
+
return input;
|
|
851
|
+
}
|
|
852
|
+
function validateStringClaim(claim, value) {
|
|
853
|
+
if (typeof value != "string")
|
|
854
|
+
throw new TypeError(`"${claim}" claim must be a string`);
|
|
855
|
+
}
|
|
856
|
+
function validateAudienceClaim(value) {
|
|
857
|
+
if (typeof value != "string" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != "string")))
|
|
858
|
+
throw new TypeError('"aud" claim must be a string or an array of strings');
|
|
859
|
+
}
|
|
860
|
+
function numericDate(value, label) {
|
|
861
|
+
return typeof value == "number" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);
|
|
862
|
+
}
|
|
863
|
+
var normalizeTyp = (value) => {
|
|
864
|
+
const normalized = value.toLowerCase();
|
|
865
|
+
return value.includes("/") ? normalized : `application/${normalized}`;
|
|
866
|
+
};
|
|
867
|
+
var checkAudiencePresence = (audPayload, audOption) => typeof audPayload == "string" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : false;
|
|
868
|
+
function validateNumericDate(claimsSet, claim, required = false) {
|
|
869
|
+
const value = claimsSet[claim];
|
|
870
|
+
if (!(value === void 0 && !required)) {
|
|
871
|
+
if (typeof value != "number")
|
|
872
|
+
throw new JWTClaimValidationFailed(`"${claim}" claim must be a number`, claimsSet, claim, "invalid");
|
|
873
|
+
return value;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
function unexpectedClaim(claimsSet, claim) {
|
|
877
|
+
throw new JWTClaimValidationFailed(`unexpected "${claim}" claim value`, claimsSet, claim, checkFailed);
|
|
878
|
+
}
|
|
879
|
+
function validateClaimsSet(protectedHeader, claimsSetBytes, options = {}) {
|
|
880
|
+
let claimsSet;
|
|
881
|
+
try {
|
|
882
|
+
claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));
|
|
883
|
+
} catch (cause) {
|
|
884
|
+
throw new JWTInvalid("JWT Claims Set must be a top-level JSON object", { cause });
|
|
885
|
+
}
|
|
886
|
+
if (!isObject(claimsSet))
|
|
887
|
+
throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
|
|
888
|
+
const { typ } = options;
|
|
889
|
+
if (typ !== void 0 && (typeof protectedHeader.typ != "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))
|
|
890
|
+
throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', claimsSet, "typ", checkFailed);
|
|
891
|
+
const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];
|
|
892
|
+
maxTokenAge !== void 0 && presenceCheck.push("iat"), audience !== void 0 && presenceCheck.push("aud"), subject !== void 0 && presenceCheck.push("sub"), issuer !== void 0 && presenceCheck.push("iss");
|
|
893
|
+
for (const claim of new Set(presenceCheck.reverse()))
|
|
894
|
+
if (!Object.hasOwn(claimsSet, claim))
|
|
895
|
+
throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claimsSet, claim, "missing");
|
|
896
|
+
issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(claimsSet.iss) && unexpectedClaim(claimsSet, "iss"), subject !== void 0 && claimsSet.sub !== subject && unexpectedClaim(claimsSet, "sub"), audience !== void 0 && !checkAudiencePresence(claimsSet.aud, typeof audience == "string" ? [audience] : audience) && unexpectedClaim(claimsSet, "aud");
|
|
897
|
+
const { clockTolerance } = options;
|
|
898
|
+
let tolerance = 0;
|
|
899
|
+
if (typeof clockTolerance == "string")
|
|
900
|
+
tolerance = secs(clockTolerance);
|
|
901
|
+
else if (clockTolerance !== void 0) {
|
|
902
|
+
if (typeof clockTolerance != "number")
|
|
903
|
+
throw new TypeError("Invalid clockTolerance option type");
|
|
904
|
+
tolerance = clockTolerance;
|
|
905
|
+
}
|
|
906
|
+
if (validateInput("clockTolerance option", tolerance), tolerance < 0)
|
|
907
|
+
throw new TypeError("Invalid clockTolerance option input");
|
|
908
|
+
const { currentDate } = options, now = validateInput("currentDate option", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(claimsSet, "iat", maxTokenAge !== void 0), nbf = validateNumericDate(claimsSet, "nbf");
|
|
909
|
+
if (nbf !== void 0 && nbf > now + tolerance)
|
|
910
|
+
throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', claimsSet, "nbf", checkFailed);
|
|
911
|
+
const exp = validateNumericDate(claimsSet, "exp");
|
|
912
|
+
if (exp !== void 0 && exp <= now - tolerance)
|
|
913
|
+
throw new JWTExpired('"exp" claim timestamp check failed', claimsSet, "exp", checkFailed);
|
|
914
|
+
if (maxTokenAge !== void 0) {
|
|
915
|
+
const age = now - iat, max = validateInput("maxTokenAge option", typeof maxTokenAge == "number" ? maxTokenAge : secs(maxTokenAge));
|
|
916
|
+
if (max < 0)
|
|
917
|
+
throw new TypeError("Invalid maxTokenAge option input");
|
|
918
|
+
if (age - tolerance > max)
|
|
919
|
+
throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', claimsSet, "iat", checkFailed);
|
|
920
|
+
if (age < -tolerance)
|
|
921
|
+
throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', claimsSet, "iat", checkFailed);
|
|
922
|
+
}
|
|
923
|
+
return claimsSet;
|
|
924
|
+
}
|
|
925
|
+
var producerClaimsSets;
|
|
926
|
+
function producerClaimsSet(producer) {
|
|
927
|
+
return producerClaimsSets.get(producer);
|
|
928
|
+
}
|
|
929
|
+
function jwtClaimsSetBytes(producer) {
|
|
930
|
+
const claimsSet = producerClaimsSet(producer);
|
|
931
|
+
for (const claim of ["iat", "nbf", "exp"]) {
|
|
932
|
+
const value = claimsSet[claim];
|
|
933
|
+
if (typeof value == "number" && !Number.isFinite(value))
|
|
934
|
+
throw new TypeError(`"${claim}" claim must be a finite number`);
|
|
935
|
+
}
|
|
936
|
+
return encoder.encode(JSON.stringify(claimsSet));
|
|
937
|
+
}
|
|
938
|
+
var JWTClaimsBuilder = class {
|
|
939
|
+
constructor(claimsSet = {}) {
|
|
940
|
+
if (!isObject(claimsSet))
|
|
941
|
+
throw new TypeError("JWT Claims Set MUST be an object");
|
|
942
|
+
(producerClaimsSets ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(claimsSet));
|
|
943
|
+
}
|
|
944
|
+
setIssuer(value) {
|
|
945
|
+
return validateStringClaim("iss", value), producerClaimsSet(this).iss = value, this;
|
|
946
|
+
}
|
|
947
|
+
setSubject(value) {
|
|
948
|
+
return validateStringClaim("sub", value), producerClaimsSet(this).sub = value, this;
|
|
949
|
+
}
|
|
950
|
+
setAudience(value) {
|
|
951
|
+
return validateAudienceClaim(value), producerClaimsSet(this).aud = value, this;
|
|
952
|
+
}
|
|
953
|
+
setJti(value) {
|
|
954
|
+
return validateStringClaim("jti", value), producerClaimsSet(this).jti = value, this;
|
|
955
|
+
}
|
|
956
|
+
setNotBefore(value) {
|
|
957
|
+
return producerClaimsSet(this).nbf = numericDate(value, "setNotBefore"), this;
|
|
958
|
+
}
|
|
959
|
+
setExpirationTime(value) {
|
|
960
|
+
return producerClaimsSet(this).exp = numericDate(value, "setExpirationTime"), this;
|
|
961
|
+
}
|
|
962
|
+
setIssuedAt(value) {
|
|
963
|
+
const claimsSet = producerClaimsSet(this);
|
|
964
|
+
return value === void 0 ? claimsSet.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == "string" ? claimsSet.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)) : claimsSet.iat = numericDate(value, "setIssuedAt"), this;
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
|
|
968
|
+
// node_modules/jose/dist/webapi/jwt/verify.js
|
|
969
|
+
async function jwtVerify(jwt, key, options) {
|
|
970
|
+
const [verified, b64] = await verifyCompact(jwt, prepareVerify(options), key);
|
|
971
|
+
if (!b64)
|
|
972
|
+
throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
973
|
+
const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
|
|
974
|
+
return { ...verified, payload };
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// node_modules/jose/dist/webapi/lib/jws_sign.js
|
|
978
|
+
async function createSignature(input, key, rejectUnencoded) {
|
|
979
|
+
let [payload, protectedHeader, unprotectedHeader, crit] = input, encodedProtectedHeader = "";
|
|
980
|
+
if (protectedHeader !== void 0) {
|
|
981
|
+
const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);
|
|
982
|
+
protectedHeader = normalized[0], encodedProtectedHeader = encode2(normalized[1]);
|
|
983
|
+
}
|
|
984
|
+
if (unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWSInvalid, unprotectedHeader)[0]), !protectedHeader && !unprotectedHeader)
|
|
985
|
+
throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
|
|
986
|
+
if (!isDisjoint(protectedHeader, unprotectedHeader))
|
|
987
|
+
throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
988
|
+
const joseHeader = { ...protectedHeader, ...unprotectedHeader };
|
|
989
|
+
validateCritDuplicates(JWSInvalid, protectedHeader);
|
|
990
|
+
const b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));
|
|
991
|
+
b64 || rejectUnencoded?.();
|
|
992
|
+
const { alg } = joseHeader;
|
|
993
|
+
if (typeof alg != "string" || !alg)
|
|
994
|
+
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
995
|
+
const entry = jwsAlgorithm(alg);
|
|
996
|
+
let encodedPayload = "", signingPayload = payload, signingInput;
|
|
997
|
+
if (b64) {
|
|
998
|
+
const encodedPayloadCache = input[4];
|
|
999
|
+
encodedPayloadCache ? (encodedPayload = encodedPayloadCache[0] ??= encode2(payload), signingPayload = encodedPayloadCache[1] ??= encode(encodedPayload)) : (encodedPayload = encode2(payload), signingInput = encoder.encode(`${encodedProtectedHeader}.${encodedPayload}`));
|
|
1000
|
+
}
|
|
1001
|
+
signingInput ??= concat(encode(encodedProtectedHeader), encode("."), signingPayload);
|
|
1002
|
+
const signingKey = await rawKey(await prepareKey(entry, key, "sign"), entry.subtle, "sign");
|
|
1003
|
+
entry.minRsaBits && checkModulusLength(entry.alg, signingKey);
|
|
1004
|
+
const jws = {
|
|
1005
|
+
signature: encode2(new Uint8Array(await crypto.subtle.sign(entry.signing, signingKey, signingInput))),
|
|
1006
|
+
payload: encodedPayload
|
|
1007
|
+
};
|
|
1008
|
+
return protectedHeader && (jws.protected = encodedProtectedHeader), unprotectedHeader && (jws.header = unprotectedHeader), [jws, b64];
|
|
1009
|
+
}
|
|
1010
|
+
async function createCompactSignature(payload, protectedHeader, crit, key, rejectUnencoded) {
|
|
1011
|
+
const [jws] = await createSignature([payload, protectedHeader, void 0, crit], key, rejectUnencoded);
|
|
1012
|
+
return `${jws.protected}.${jws.payload}.${jws.signature}`;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// node_modules/jose/dist/webapi/jwt/sign.js
|
|
1016
|
+
var SignJWT_base = JWTClaimsBuilder;
|
|
1017
|
+
var SignJWT = class extends SignJWT_base {
|
|
1018
|
+
#protectedHeader;
|
|
1019
|
+
setProtectedHeader(protectedHeader) {
|
|
1020
|
+
return assertNotSet(this.#protectedHeader, "setProtectedHeader"), this.#protectedHeader = protectedHeader, this;
|
|
1021
|
+
}
|
|
1022
|
+
async sign(key, options) {
|
|
1023
|
+
return createCompactSignature(jwtClaimsSetBytes(this), this.#protectedHeader, options?.crit, key, () => {
|
|
1024
|
+
throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
};
|
|
1028
|
+
|
|
1029
|
+
// node_modules/jose/dist/webapi/lib/key_algorithm.js
|
|
1030
|
+
var algArgument = '"alg" (Algorithm)';
|
|
1031
|
+
function unsupportedAlg(source = 'JWK "alg" (Algorithm) Parameter') {
|
|
1032
|
+
throw new JOSENotSupported(`Invalid or unsupported ${source} value`);
|
|
1033
|
+
}
|
|
1034
|
+
function keyAlgorithm(alg, source) {
|
|
1035
|
+
return (typeof alg == "string" ? JWS[alg] ?? JWE[alg] : void 0) ?? unsupportedAlg(source);
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
// node_modules/jose/dist/webapi/key/export.js
|
|
1039
|
+
async function exportJWK(key) {
|
|
1040
|
+
if (isKeyObject(key))
|
|
1041
|
+
if (key.type === "secret")
|
|
1042
|
+
key = key.export();
|
|
1043
|
+
else
|
|
1044
|
+
return key.export({ format: "jwk" });
|
|
1045
|
+
if (key instanceof Uint8Array)
|
|
1046
|
+
return {
|
|
1047
|
+
kty: "oct",
|
|
1048
|
+
k: encode2(key)
|
|
1049
|
+
};
|
|
1050
|
+
if (!isCryptoKey(key))
|
|
1051
|
+
throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
|
|
1052
|
+
if (!key.extractable)
|
|
1053
|
+
throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
|
|
1054
|
+
const jwk = await crypto.subtle.exportKey("jwk", key);
|
|
1055
|
+
delete jwk.ext, delete jwk.key_ops, delete jwk.use, jwk.kty !== "AKP" && delete jwk.alg;
|
|
1056
|
+
for (const parameter of Object.keys(jwk))
|
|
1057
|
+
jwk[parameter] === void 0 && delete jwk[parameter];
|
|
1058
|
+
return jwk;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// node_modules/jose/dist/webapi/jwk/thumbprint.js
|
|
1062
|
+
var check = (value, description) => {
|
|
1063
|
+
if (typeof value != "string" || !value)
|
|
1064
|
+
throw new JWKInvalid(`${description} missing or invalid`);
|
|
1065
|
+
};
|
|
1066
|
+
async function calculateJwkThumbprint(key, digestAlgorithm) {
|
|
1067
|
+
let jwk;
|
|
1068
|
+
if (isObject(key)) {
|
|
1069
|
+
if (jwk = snapshotJwk(key), typeof jwk.kty != "string")
|
|
1070
|
+
throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
1071
|
+
} else if (isKeyLike(key))
|
|
1072
|
+
jwk = snapshotJwk(await exportJWK(key));
|
|
1073
|
+
else
|
|
1074
|
+
throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
1075
|
+
if (digestAlgorithm ??= "sha256", digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512")
|
|
1076
|
+
throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
|
|
1077
|
+
let requiredMembers;
|
|
1078
|
+
switch (jwk.kty) {
|
|
1079
|
+
case "AKP":
|
|
1080
|
+
check(jwk.alg, '"alg" (Algorithm) Parameter'), check(jwk.pub, '"pub" (Public key) Parameter'), requiredMembers = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
|
|
1081
|
+
break;
|
|
1082
|
+
case "EC":
|
|
1083
|
+
check(jwk.crv, '"crv" (Curve) Parameter'), check(jwk.x, '"x" (X Coordinate) Parameter'), check(jwk.y, '"y" (Y Coordinate) Parameter'), requiredMembers = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
|
|
1084
|
+
break;
|
|
1085
|
+
case "OKP":
|
|
1086
|
+
check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'), check(jwk.x, '"x" (Public Key) Parameter'), requiredMembers = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
|
|
1087
|
+
break;
|
|
1088
|
+
case "RSA":
|
|
1089
|
+
check(jwk.e, '"e" (Exponent) Parameter'), check(jwk.n, '"n" (Modulus) Parameter'), requiredMembers = { e: jwk.e, kty: jwk.kty, n: jwk.n };
|
|
1090
|
+
break;
|
|
1091
|
+
case "oct":
|
|
1092
|
+
if (typeof jwk.k != "string")
|
|
1093
|
+
throw new JWKInvalid('"k" (Key Value) Parameter missing or invalid');
|
|
1094
|
+
requiredMembers = { k: jwk.k, kty: jwk.kty };
|
|
1095
|
+
break;
|
|
1096
|
+
default:
|
|
1097
|
+
throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
|
|
1098
|
+
}
|
|
1099
|
+
const thumbprintInput = encode(JSON.stringify(requiredMembers));
|
|
1100
|
+
return encode2(await digest(digestAlgorithm, thumbprintInput));
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
// node_modules/jose/dist/webapi/jwks/local.js
|
|
1104
|
+
function isUsableJWK(jwk, entry, alg, kid) {
|
|
1105
|
+
const { kty, key_ops: keyOps, ext, kid: jwkKid, alg: jwkAlg, use, crv } = jwk;
|
|
1106
|
+
return (ext === void 0 || typeof ext == "boolean") && (keyOps === void 0 || Array.isArray(keyOps) && keyOps.every((operation, index) => typeof operation == "string" && keyOps.indexOf(operation) === index) && keyOps.includes("verify")) && entry.kty.includes(kty) && (kid === void 0 || typeof kid == "string" && kid === jwkKid) && (jwkAlg === void 0 ? kty !== "AKP" : alg === jwkAlg) && (use === void 0 || use === "sig") && (!entry.crv || crv === entry.crv);
|
|
1107
|
+
}
|
|
1108
|
+
async function importWithAlgCache(cache2, jwk, entry) {
|
|
1109
|
+
const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk), { alg } = entry;
|
|
1110
|
+
if (cached[alg] === void 0) {
|
|
1111
|
+
const pending = jwkToKey(entry, jwk, true).then((key) => {
|
|
1112
|
+
if (key.type !== "public")
|
|
1113
|
+
throw new JWKSInvalid("JSON Web Key Set members must be public keys");
|
|
1114
|
+
return cached[alg] = key, key;
|
|
1115
|
+
}).catch((error) => {
|
|
1116
|
+
throw cached[alg] === pending && delete cached[alg], error;
|
|
1117
|
+
});
|
|
1118
|
+
cached[alg] = pending;
|
|
1119
|
+
}
|
|
1120
|
+
return cached[alg];
|
|
1121
|
+
}
|
|
1122
|
+
function createLocalJWKSet(jwks) {
|
|
1123
|
+
let snapshot;
|
|
1124
|
+
try {
|
|
1125
|
+
snapshot = structuredClone(jwks);
|
|
1126
|
+
} catch (cause) {
|
|
1127
|
+
throw new JWKSInvalid("JSON Web Key Set malformed", { cause });
|
|
1128
|
+
}
|
|
1129
|
+
if (!isJwkSet(snapshot))
|
|
1130
|
+
throw new JWKSInvalid("JSON Web Key Set malformed");
|
|
1131
|
+
const metadata = snapshot.keys.map((jwk) => {
|
|
1132
|
+
const normalized = snapshotJwk(jwk);
|
|
1133
|
+
return Array.isArray(normalized.key_ops) && (normalized.key_ops = [...normalized.key_ops]), normalized;
|
|
1134
|
+
}), cached = /* @__PURE__ */ new WeakMap();
|
|
1135
|
+
return Object.defineProperty(async (protectedHeader, token) => {
|
|
1136
|
+
const { alg, kid } = { ...protectedHeader, ...token?.header }, entry = typeof alg == "string" ? JWS[alg] : void 0;
|
|
1137
|
+
if (!entry || entry.secret)
|
|
1138
|
+
throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
|
|
1139
|
+
const candidates = snapshot.keys.filter((_, index) => isUsableJWK(metadata[index], entry, alg, kid)), { 0: jwk, length: length2 } = candidates;
|
|
1140
|
+
if (!length2)
|
|
1141
|
+
throw new JWKSNoMatchingKey();
|
|
1142
|
+
if (length2 !== 1) {
|
|
1143
|
+
const error = new JWKSMultipleMatchingKeys();
|
|
1144
|
+
throw error[Symbol.asyncIterator] = async function* () {
|
|
1145
|
+
for (const jwk2 of candidates)
|
|
1146
|
+
try {
|
|
1147
|
+
yield await importWithAlgCache(cached, jwk2, entry);
|
|
1148
|
+
} catch {
|
|
1149
|
+
}
|
|
1150
|
+
}, error;
|
|
1151
|
+
}
|
|
1152
|
+
return importWithAlgCache(cached, jwk, entry);
|
|
1153
|
+
}, "jwks", {
|
|
1154
|
+
value: () => structuredClone(snapshot)
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
// node_modules/jose/dist/webapi/jwks/remote.js
|
|
1159
|
+
function isCloudflareWorkers() {
|
|
1160
|
+
return typeof WebSocketPair < "u" || typeof navigator < "u" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime < "u" && EdgeRuntime === "vercel";
|
|
1161
|
+
}
|
|
1162
|
+
var USER_AGENT;
|
|
1163
|
+
(typeof navigator > "u" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) && (USER_AGENT = "jose/v6.2.17");
|
|
1164
|
+
var customFetch = /* @__PURE__ */ Symbol();
|
|
1165
|
+
async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
|
|
1166
|
+
const response = await fetchImpl(url, {
|
|
1167
|
+
method: "GET",
|
|
1168
|
+
signal,
|
|
1169
|
+
redirect: "manual",
|
|
1170
|
+
headers
|
|
1171
|
+
}).catch((err) => {
|
|
1172
|
+
throw err.name === "TimeoutError" ? new JWKSTimeout(void 0, { cause: err }) : err;
|
|
1173
|
+
});
|
|
1174
|
+
if (response.status !== 200)
|
|
1175
|
+
throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
|
|
1176
|
+
try {
|
|
1177
|
+
return await response.json();
|
|
1178
|
+
} catch (cause) {
|
|
1179
|
+
throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON", { cause });
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
var jwksCache = /* @__PURE__ */ Symbol();
|
|
1183
|
+
function isFreshFor(timestamp, duration) {
|
|
1184
|
+
return Number.isFinite(timestamp) && Date.now() < timestamp + duration;
|
|
1185
|
+
}
|
|
1186
|
+
function validateDuration(value, fallback, option) {
|
|
1187
|
+
if (Number.isNaN(value))
|
|
1188
|
+
throw new TypeError(`"${option}" option must not be NaN`);
|
|
1189
|
+
if (typeof value == "number" && value < 0)
|
|
1190
|
+
throw new TypeError(`"${option}" option must not be negative`);
|
|
1191
|
+
return typeof value == "number" ? value : fallback;
|
|
1192
|
+
}
|
|
1193
|
+
function createRemoteJWKSet(url, options) {
|
|
1194
|
+
if (!(url instanceof URL))
|
|
1195
|
+
throw new TypeError("url must be an instance of URL");
|
|
1196
|
+
const href = new URL(url.href).href, opts = options ?? {}, timeoutOption = opts.timeoutDuration;
|
|
1197
|
+
if (typeof timeoutOption == "number" && (!Number.isInteger(timeoutOption) || timeoutOption < 0))
|
|
1198
|
+
throw new TypeError('"timeoutDuration" option must be a non-negative integer');
|
|
1199
|
+
const timeoutDuration = typeof timeoutOption == "number" ? timeoutOption : 5e3, cooldownDuration = validateDuration(opts.cooldownDuration, 3e4, "cooldownDuration"), cacheMaxAge = validateDuration(opts.cacheMaxAge, 6e5, "cacheMaxAge"), headers = new Headers(opts.headers);
|
|
1200
|
+
USER_AGENT && !headers.has("User-Agent") && headers.set("User-Agent", USER_AGENT), headers.has("accept") || headers.set("accept", "application/json, application/jwk-set+json");
|
|
1201
|
+
const fetchImpl = opts[customFetch], cache2 = opts[jwksCache];
|
|
1202
|
+
let jwksTimestamp, pendingFetch, reloadSequence = 0, appliedSequence = 0, local;
|
|
1203
|
+
if (cache2 && typeof cache2 == "object") {
|
|
1204
|
+
const { uat, jwks } = cache2;
|
|
1205
|
+
isFreshFor(uat, cacheMaxAge) && isJwkSet(jwks) && (jwksTimestamp = uat, local = createLocalJWKSet(jwks));
|
|
1206
|
+
}
|
|
1207
|
+
const reload = async () => {
|
|
1208
|
+
if (pendingFetch && isCloudflareWorkers() && (pendingFetch = void 0), !pendingFetch) {
|
|
1209
|
+
const sequence = ++reloadSequence, current = pendingFetch = fetchJwks(href, headers, AbortSignal.timeout(timeoutDuration), fetchImpl).then((json) => {
|
|
1210
|
+
const next = createLocalJWKSet(json);
|
|
1211
|
+
if (sequence <= appliedSequence)
|
|
1212
|
+
return;
|
|
1213
|
+
local = next;
|
|
1214
|
+
const updatedAt = Date.now();
|
|
1215
|
+
cache2 && (cache2.uat = updatedAt, cache2.jwks = json), jwksTimestamp = updatedAt, appliedSequence = sequence;
|
|
1216
|
+
}).finally(() => {
|
|
1217
|
+
pendingFetch === current && (pendingFetch = void 0);
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
await pendingFetch;
|
|
1221
|
+
};
|
|
1222
|
+
return Object.defineProperties(async (protectedHeader, token) => {
|
|
1223
|
+
(!local || !isFreshFor(jwksTimestamp, cacheMaxAge)) && await reload();
|
|
1224
|
+
try {
|
|
1225
|
+
return await local(protectedHeader, token);
|
|
1226
|
+
} catch (err) {
|
|
1227
|
+
if (err instanceof JWKSNoMatchingKey && !isFreshFor(jwksTimestamp, cooldownDuration))
|
|
1228
|
+
return await reload(), local(protectedHeader, token);
|
|
1229
|
+
throw err;
|
|
1230
|
+
}
|
|
1231
|
+
}, {
|
|
1232
|
+
coolingDown: {
|
|
1233
|
+
get: () => isFreshFor(jwksTimestamp, cooldownDuration),
|
|
1234
|
+
enumerable: true
|
|
1235
|
+
},
|
|
1236
|
+
fresh: {
|
|
1237
|
+
get: () => isFreshFor(jwksTimestamp, cacheMaxAge),
|
|
1238
|
+
enumerable: true
|
|
1239
|
+
},
|
|
1240
|
+
reload: {
|
|
1241
|
+
value: reload,
|
|
1242
|
+
enumerable: true
|
|
1243
|
+
},
|
|
1244
|
+
reloading: {
|
|
1245
|
+
get: () => !!pendingFetch,
|
|
1246
|
+
enumerable: true
|
|
1247
|
+
},
|
|
1248
|
+
jwks: {
|
|
1249
|
+
value: () => local?.jwks(),
|
|
1250
|
+
enumerable: true
|
|
1251
|
+
}
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
// node_modules/jose/dist/webapi/util/decode_protected_header.js
|
|
1256
|
+
function decodeProtectedHeader(token) {
|
|
1257
|
+
let encodedProtectedHeader;
|
|
1258
|
+
if (typeof token == "string") {
|
|
1259
|
+
const parts = token.split(".");
|
|
1260
|
+
(parts.length === 3 || parts.length === 5) && ([encodedProtectedHeader] = parts);
|
|
1261
|
+
} else if (typeof token == "object" && token)
|
|
1262
|
+
if ("protected" in token)
|
|
1263
|
+
encodedProtectedHeader = token.protected;
|
|
1264
|
+
else
|
|
1265
|
+
throw new TypeError("Token does not contain a Protected Header");
|
|
1266
|
+
const invalid3 = "Invalid Token or Protected Header formatting";
|
|
1267
|
+
if (typeof encodedProtectedHeader != "string" || !encodedProtectedHeader)
|
|
1268
|
+
throw new TypeError(invalid3);
|
|
1269
|
+
return parseJoseHeader(encodedProtectedHeader, TypeError, invalid3);
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
// node_modules/jose/dist/webapi/util/decode_jwt.js
|
|
1273
|
+
function decodeJwt(jwt) {
|
|
1274
|
+
if (typeof jwt != "string")
|
|
1275
|
+
throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
|
|
1276
|
+
const { 1: encodedPayload, length: length2 } = jwt.split(".");
|
|
1277
|
+
if (length2 === 5)
|
|
1278
|
+
throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
|
|
1279
|
+
if (length2 !== 3)
|
|
1280
|
+
throw new JWTInvalid("Invalid JWT");
|
|
1281
|
+
if (!encodedPayload)
|
|
1282
|
+
throw new JWTInvalid("JWTs must contain a payload");
|
|
1283
|
+
let claimsSetBytes;
|
|
1284
|
+
try {
|
|
1285
|
+
claimsSetBytes = decode(encodedPayload);
|
|
1286
|
+
} catch (cause) {
|
|
1287
|
+
throw new JWTInvalid("Failed to base64url decode the payload", { cause });
|
|
1288
|
+
}
|
|
1289
|
+
let claimsSet;
|
|
1290
|
+
try {
|
|
1291
|
+
claimsSet = JSON.parse(strictDecoder.decode(claimsSetBytes));
|
|
1292
|
+
} catch (cause) {
|
|
1293
|
+
throw new JWTInvalid("Failed to parse the decoded payload as JSON", { cause });
|
|
1294
|
+
}
|
|
1295
|
+
if (!isObject(claimsSet))
|
|
1296
|
+
throw new JWTInvalid("Invalid JWT Claims Set");
|
|
1297
|
+
return claimsSet;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// node_modules/jose/dist/webapi/key/generate_key_pair.js
|
|
1301
|
+
function getModulusLengthOption(options) {
|
|
1302
|
+
const modulusLength = options?.modulusLength ?? 2048;
|
|
1303
|
+
if (typeof modulusLength != "number" || !Number.isInteger(modulusLength) || modulusLength < 2048)
|
|
1304
|
+
throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
|
|
1305
|
+
return modulusLength;
|
|
1306
|
+
}
|
|
1307
|
+
async function generateKeyPair(alg, options) {
|
|
1308
|
+
const extractable = validateExtractableOption(options?.extractable), entry = keyAlgorithm(alg, algArgument);
|
|
1309
|
+
entry.secret && unsupportedAlg(algArgument);
|
|
1310
|
+
let algorithm;
|
|
1311
|
+
if (entry.resolve) {
|
|
1312
|
+
const crv = options?.crv ?? "P-256";
|
|
1313
|
+
if (!["P-256", "P-384", "P-521", "X25519"].includes(crv))
|
|
1314
|
+
throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
|
|
1315
|
+
algorithm = entry.resolve({ crv });
|
|
1316
|
+
} else {
|
|
1317
|
+
if (entry.crv !== void 0 && options?.crv !== void 0 && options.crv !== entry.crv)
|
|
1318
|
+
throw new JOSENotSupported(`Invalid or unsupported crv option provided, the only supported value for ${alg} is ${entry.crv}`);
|
|
1319
|
+
algorithm = entry.kty[0] === "RSA" ? {
|
|
1320
|
+
...entry.subtle,
|
|
1321
|
+
publicExponent: Uint8Array.of(1, 0, 1),
|
|
1322
|
+
modulusLength: getModulusLengthOption(options)
|
|
1323
|
+
} : entry.subtle;
|
|
1324
|
+
}
|
|
1325
|
+
return crypto.subtle.generateKey(algorithm, extractable ?? false, [
|
|
1326
|
+
...entry.usages[1],
|
|
1327
|
+
...entry.usages[0]
|
|
1328
|
+
]);
|
|
1329
|
+
}
|
|
177
1330
|
|
|
178
1331
|
// src/errors.ts
|
|
179
1332
|
var TestkitError = class extends Error {
|
|
180
1333
|
code;
|
|
181
1334
|
details;
|
|
182
|
-
constructor(code,
|
|
183
|
-
super(details.length > 0 ? `${
|
|
1335
|
+
constructor(code, message2, details = []) {
|
|
1336
|
+
super(details.length > 0 ? `${message2}
|
|
184
1337
|
|
|
185
|
-
${details.map((d) => ` - ${d}`).join("\n")}` :
|
|
1338
|
+
${details.map((d) => ` - ${d}`).join("\n")}` : message2);
|
|
186
1339
|
this.name = "TestkitError";
|
|
187
1340
|
this.code = code;
|
|
188
1341
|
this.details = details;
|
|
@@ -198,17 +1351,17 @@ ${this.message}`;
|
|
|
198
1351
|
var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
|
|
199
1352
|
function toSeconds(value) {
|
|
200
1353
|
if (typeof value === "number") {
|
|
201
|
-
if (!Number.isFinite(value) || value < 0) throw
|
|
1354
|
+
if (!Number.isFinite(value) || value < 0) throw invalid2(String(value));
|
|
202
1355
|
return Math.floor(value);
|
|
203
1356
|
}
|
|
204
1357
|
const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
|
|
205
1358
|
if (!match) {
|
|
206
1359
|
if (/^\d+$/.test(value.trim())) return Number(value.trim());
|
|
207
|
-
throw
|
|
1360
|
+
throw invalid2(value);
|
|
208
1361
|
}
|
|
209
1362
|
return Number(match[1]) * UNITS[match[2]];
|
|
210
1363
|
}
|
|
211
|
-
function
|
|
1364
|
+
function invalid2(value) {
|
|
212
1365
|
return new TestkitError(
|
|
213
1366
|
"INVALID_DURATION",
|
|
214
1367
|
`"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
|
|
@@ -236,6 +1389,20 @@ var INVALID_TOKEN_KINDS = [
|
|
|
236
1389
|
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
237
1390
|
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
238
1391
|
var KindeTestkit = class _KindeTestkit {
|
|
1392
|
+
observers = [];
|
|
1393
|
+
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
1394
|
+
observe(observer) {
|
|
1395
|
+
this.observers.push(observer);
|
|
1396
|
+
return () => {
|
|
1397
|
+
this.observers = this.observers.filter((o) => o !== observer);
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
async signAccess(payload, invalid3, now) {
|
|
1401
|
+
const final = applyInvalidClaims(payload, invalid3, now);
|
|
1402
|
+
const token = await this.sign(final, invalid3);
|
|
1403
|
+
for (const observer of this.observers) observer.accessToken?.(final, invalid3, token);
|
|
1404
|
+
return token;
|
|
1405
|
+
}
|
|
239
1406
|
issuer;
|
|
240
1407
|
audience;
|
|
241
1408
|
clientId;
|
|
@@ -267,7 +1434,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
267
1434
|
return toSeconds(this.accessTokenExpiresIn);
|
|
268
1435
|
}
|
|
269
1436
|
async verify(token) {
|
|
270
|
-
const { payload } = await
|
|
1437
|
+
const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
|
|
271
1438
|
issuer: this.issuer,
|
|
272
1439
|
algorithms: ["RS256"]
|
|
273
1440
|
});
|
|
@@ -295,7 +1462,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
295
1462
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
296
1463
|
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
297
1464
|
Object.assign(payload, options.claims ?? {});
|
|
298
|
-
return this.
|
|
1465
|
+
return this.signAccess(payload, options.invalid, now);
|
|
299
1466
|
}
|
|
300
1467
|
async m2mToken(options = {}) {
|
|
301
1468
|
const now = this.clock();
|
|
@@ -316,10 +1483,13 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
316
1483
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
317
1484
|
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
318
1485
|
Object.assign(payload, options.claims ?? {});
|
|
319
|
-
return this.
|
|
1486
|
+
return this.signAccess(payload, options.invalid, now);
|
|
320
1487
|
}
|
|
321
1488
|
async tokenFor(scenario2, overrides = {}) {
|
|
322
|
-
if (scenario2.kind === "unauthenticated")
|
|
1489
|
+
if (scenario2.kind === "unauthenticated") {
|
|
1490
|
+
for (const observer of this.observers) observer.anonymous?.();
|
|
1491
|
+
return null;
|
|
1492
|
+
}
|
|
323
1493
|
return this.token({
|
|
324
1494
|
subject: scenario2.user.id,
|
|
325
1495
|
organizationCode: scenario2.organization?.code ?? null,
|
|
@@ -361,7 +1531,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
361
1531
|
for (const key of Object.keys(payload)) {
|
|
362
1532
|
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
363
1533
|
}
|
|
364
|
-
|
|
1534
|
+
const token = await this.sign(payload);
|
|
1535
|
+
for (const observer of this.observers) observer.idToken?.(payload, token);
|
|
1536
|
+
return token;
|
|
365
1537
|
}
|
|
366
1538
|
async headersFor(scenario2, overrides = {}) {
|
|
367
1539
|
const token = await this.tokenFor(scenario2, overrides);
|
|
@@ -371,17 +1543,17 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
371
1543
|
if (scenario2.kind === "unauthenticated") return null;
|
|
372
1544
|
return scenarioPrincipal(scenario2, this.issuer);
|
|
373
1545
|
}
|
|
374
|
-
async signPayload(payload,
|
|
375
|
-
return this.sign(payload,
|
|
1546
|
+
async signPayload(payload, invalid3) {
|
|
1547
|
+
return this.sign(payload, invalid3);
|
|
376
1548
|
}
|
|
377
|
-
async sign(payload,
|
|
378
|
-
if (
|
|
379
|
-
const header =
|
|
380
|
-
return `${header}.${
|
|
1549
|
+
async sign(payload, invalid3) {
|
|
1550
|
+
if (invalid3 === "unsigned") {
|
|
1551
|
+
const header = base64url_exports.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
1552
|
+
return `${header}.${base64url_exports.encode(JSON.stringify(payload))}.`;
|
|
381
1553
|
}
|
|
382
|
-
const key =
|
|
383
|
-
const jwt = await new
|
|
384
|
-
return
|
|
1554
|
+
const key = invalid3 === "unknown-key" ? await this.stranger() : this.signingKey;
|
|
1555
|
+
const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
|
|
1556
|
+
return invalid3 === "bad-signature" ? tamperSignature(jwt) : jwt;
|
|
385
1557
|
}
|
|
386
1558
|
stranger() {
|
|
387
1559
|
this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
|
|
@@ -415,9 +1587,9 @@ function scenarioPrincipal(scenario2, issuer) {
|
|
|
415
1587
|
claims: { ...scenario2.claims }
|
|
416
1588
|
};
|
|
417
1589
|
}
|
|
418
|
-
function applyInvalidClaims(payload,
|
|
1590
|
+
function applyInvalidClaims(payload, invalid3, now) {
|
|
419
1591
|
const next = { ...payload };
|
|
420
|
-
switch (
|
|
1592
|
+
switch (invalid3) {
|
|
421
1593
|
case "expired":
|
|
422
1594
|
next.iat = now - 7200;
|
|
423
1595
|
next.exp = now - 3600;
|
|
@@ -447,16 +1619,16 @@ function applyInvalidClaims(payload, invalid2, now) {
|
|
|
447
1619
|
return next;
|
|
448
1620
|
}
|
|
449
1621
|
async function createSigningKey(prefix) {
|
|
450
|
-
const { privateKey, publicKey } = await
|
|
451
|
-
const jwk = await
|
|
452
|
-
const kid = `${prefix}-${(await
|
|
1622
|
+
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
|
1623
|
+
const jwk = await exportJWK(publicKey);
|
|
1624
|
+
const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
|
|
453
1625
|
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
454
1626
|
}
|
|
455
1627
|
function tamperSignature(jwt) {
|
|
456
1628
|
const [header, payload, signature] = jwt.split(".");
|
|
457
|
-
const bytes =
|
|
1629
|
+
const bytes = base64url_exports.decode(signature);
|
|
458
1630
|
bytes[0] = (bytes[0] ?? 0) ^ 255;
|
|
459
|
-
return `${header}.${payload}.${
|
|
1631
|
+
return `${header}.${payload}.${base64url_exports.encode(bytes)}`;
|
|
460
1632
|
}
|
|
461
1633
|
function toArray(value) {
|
|
462
1634
|
if (value === void 0) return [];
|
|
@@ -487,23 +1659,249 @@ async function createKindeToken(options = {}) {
|
|
|
487
1659
|
|
|
488
1660
|
// src/server.ts
|
|
489
1661
|
var import_node_http = require("http");
|
|
1662
|
+
var import_node_https = require("https");
|
|
490
1663
|
|
|
491
|
-
// src/
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
1664
|
+
// src/certificate.ts
|
|
1665
|
+
var import_node_crypto3 = require("crypto");
|
|
1666
|
+
var import_node_fs = require("fs");
|
|
1667
|
+
var import_node_path = require("path");
|
|
1668
|
+
var CERT_FILE = "localhost-cert.pem";
|
|
1669
|
+
var KEY_FILE = "localhost-key.pem";
|
|
1670
|
+
var VALID_DAYS = 825;
|
|
1671
|
+
function ensureLocalCertificate(directory = ".kinde-testkit") {
|
|
1672
|
+
const dir = (0, import_node_path.resolve)(directory);
|
|
1673
|
+
const certPath = (0, import_node_path.join)(dir, CERT_FILE);
|
|
1674
|
+
const keyPath = (0, import_node_path.join)(dir, KEY_FILE);
|
|
1675
|
+
if ((0, import_node_fs.existsSync)(certPath) && (0, import_node_fs.existsSync)(keyPath)) {
|
|
1676
|
+
const cert2 = (0, import_node_fs.readFileSync)(certPath, "utf8");
|
|
1677
|
+
const key2 = (0, import_node_fs.readFileSync)(keyPath, "utf8");
|
|
1678
|
+
try {
|
|
1679
|
+
if (new Date(new import_node_crypto3.X509Certificate(cert2).validTo).getTime() > Date.now() + 864e5) {
|
|
1680
|
+
return { cert: cert2, key: key2, certPath, keyPath, created: false };
|
|
1681
|
+
}
|
|
1682
|
+
} catch {
|
|
1683
|
+
}
|
|
496
1684
|
}
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
1685
|
+
const { cert, key } = createLocalCertificate();
|
|
1686
|
+
(0, import_node_fs.mkdirSync)(dir, { recursive: true });
|
|
1687
|
+
(0, import_node_fs.writeFileSync)(certPath, cert);
|
|
1688
|
+
(0, import_node_fs.writeFileSync)(keyPath, key, { mode: 384 });
|
|
1689
|
+
(0, import_node_fs.writeFileSync)((0, import_node_path.join)(dir, ".gitignore"), "*\n");
|
|
1690
|
+
return { cert, key, certPath, keyPath, created: true };
|
|
1691
|
+
}
|
|
1692
|
+
function createLocalCertificate() {
|
|
1693
|
+
const { publicKey, privateKey } = (0, import_node_crypto3.generateKeyPairSync)("rsa", { modulusLength: 2048 });
|
|
1694
|
+
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
1695
|
+
const keyId = (0, import_node_crypto3.createHash)("sha1").update(subjectPublicKeyBits(spki)).digest();
|
|
1696
|
+
const name = seq(set(seq(oid("2.5.4.3"), tlv(12, Buffer.from("kinde-testkit localhost")))));
|
|
1697
|
+
const now = Date.now();
|
|
1698
|
+
const algorithm = seq(oid("1.2.840.113549.1.1.11"), tlv(5, Buffer.alloc(0)));
|
|
1699
|
+
const serial = (0, import_node_crypto3.randomBytes)(16);
|
|
1700
|
+
serial[0] &= 127;
|
|
1701
|
+
const extensions = seq(
|
|
1702
|
+
seq(oid("2.5.29.19"), tlv(1, Buffer.from([255])), octets(seq(tlv(1, Buffer.from([255]))))),
|
|
1703
|
+
seq(oid("2.5.29.14"), octets(octets(keyId))),
|
|
1704
|
+
seq(oid("2.5.29.35"), octets(seq(tlv(128, keyId)))),
|
|
1705
|
+
seq(
|
|
1706
|
+
oid("2.5.29.17"),
|
|
1707
|
+
octets(
|
|
1708
|
+
seq(
|
|
1709
|
+
tlv(130, Buffer.from("localhost")),
|
|
1710
|
+
tlv(135, Buffer.from([127, 0, 0, 1])),
|
|
1711
|
+
tlv(135, Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))
|
|
1712
|
+
)
|
|
1713
|
+
)
|
|
1714
|
+
)
|
|
1715
|
+
);
|
|
1716
|
+
const tbs = seq(
|
|
1717
|
+
tlv(160, integer(Buffer.from([2]))),
|
|
1718
|
+
integer(serial),
|
|
1719
|
+
algorithm,
|
|
1720
|
+
name,
|
|
1721
|
+
seq(utcTime(new Date(now - 6e4)), utcTime(new Date(now + VALID_DAYS * 864e5))),
|
|
1722
|
+
name,
|
|
1723
|
+
spki,
|
|
1724
|
+
tlv(163, extensions)
|
|
1725
|
+
);
|
|
1726
|
+
const signature = (0, import_node_crypto3.sign)("sha256", tbs, privateKey);
|
|
1727
|
+
const der = seq(tbs, algorithm, tlv(3, Buffer.concat([Buffer.from([0]), signature])));
|
|
1728
|
+
return {
|
|
1729
|
+
cert: pem("CERTIFICATE", der),
|
|
1730
|
+
key: privateKey.export({ type: "pkcs8", format: "pem" }).toString()
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
function subjectPublicKeyBits(spki) {
|
|
1734
|
+
const outer = readTlv(spki, 0);
|
|
1735
|
+
const algorithm = readTlv(spki, outer.start);
|
|
1736
|
+
const bits = readTlv(spki, algorithm.end);
|
|
1737
|
+
return spki.subarray(bits.start + 1, bits.end);
|
|
1738
|
+
}
|
|
1739
|
+
function readTlv(buf, offset) {
|
|
1740
|
+
let len = buf[offset + 1];
|
|
1741
|
+
let header = 2;
|
|
1742
|
+
if (len & 128) {
|
|
1743
|
+
const n = len & 127;
|
|
1744
|
+
len = 0;
|
|
1745
|
+
for (let i = 0; i < n; i++) len = len << 8 | buf[offset + 2 + i];
|
|
1746
|
+
header += n;
|
|
1747
|
+
}
|
|
1748
|
+
return { start: offset + header, end: offset + header + len };
|
|
1749
|
+
}
|
|
1750
|
+
function tlv(tag2, content) {
|
|
1751
|
+
return Buffer.concat([Buffer.from([tag2]), length(content.length), content]);
|
|
1752
|
+
}
|
|
1753
|
+
function length(n) {
|
|
1754
|
+
if (n < 128) return Buffer.from([n]);
|
|
1755
|
+
const bytes = [];
|
|
1756
|
+
while (n > 0) {
|
|
1757
|
+
bytes.unshift(n & 255);
|
|
1758
|
+
n >>= 8;
|
|
1759
|
+
}
|
|
1760
|
+
return Buffer.from([128 | bytes.length, ...bytes]);
|
|
1761
|
+
}
|
|
1762
|
+
function seq(...items) {
|
|
1763
|
+
return tlv(48, Buffer.concat(items));
|
|
1764
|
+
}
|
|
1765
|
+
function set(...items) {
|
|
1766
|
+
return tlv(49, Buffer.concat(items));
|
|
1767
|
+
}
|
|
1768
|
+
function octets(content) {
|
|
1769
|
+
return tlv(4, content);
|
|
1770
|
+
}
|
|
1771
|
+
function integer(bytes) {
|
|
1772
|
+
return tlv(2, bytes[0] & 128 ? Buffer.concat([Buffer.from([0]), bytes]) : bytes);
|
|
1773
|
+
}
|
|
1774
|
+
function oid(dotted) {
|
|
1775
|
+
const parts = dotted.split(".").map(Number);
|
|
1776
|
+
const bytes = [parts[0] * 40 + parts[1]];
|
|
1777
|
+
for (const part of parts.slice(2)) {
|
|
1778
|
+
const chunk = [part & 127];
|
|
1779
|
+
let value = part >> 7;
|
|
1780
|
+
while (value > 0) {
|
|
1781
|
+
chunk.unshift(value & 127 | 128);
|
|
1782
|
+
value >>= 7;
|
|
1783
|
+
}
|
|
1784
|
+
bytes.push(...chunk);
|
|
1785
|
+
}
|
|
1786
|
+
return tlv(6, Buffer.from(bytes));
|
|
1787
|
+
}
|
|
1788
|
+
function utcTime(date) {
|
|
1789
|
+
const iso = date.toISOString();
|
|
1790
|
+
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`;
|
|
1791
|
+
return tlv(23, Buffer.from(value));
|
|
1792
|
+
}
|
|
1793
|
+
function pem(label, der) {
|
|
1794
|
+
const body = der.toString("base64").match(/.{1,64}/g).join("\n");
|
|
1795
|
+
return `-----BEGIN ${label}-----
|
|
1796
|
+
${body}
|
|
1797
|
+
-----END ${label}-----
|
|
1798
|
+
`;
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
// src/login-page.ts
|
|
1802
|
+
var STYLE = `
|
|
1803
|
+
: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}
|
|
1804
|
+
@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}}
|
|
1805
|
+
*{box-sizing:border-box}
|
|
1806
|
+
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}
|
|
1807
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
1808
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
1809
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
1810
|
+
p{margin:0;color:var(--muted)}
|
|
1811
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
1812
|
+
form{margin:0}
|
|
1813
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
1814
|
+
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}
|
|
1815
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
1816
|
+
.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}
|
|
1817
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
1818
|
+
.list{display:grid;gap:8px}
|
|
1819
|
+
.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}
|
|
1820
|
+
.option:hover{border-color:var(--muted)}
|
|
1821
|
+
.option strong{display:block;font-weight:500}
|
|
1822
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
1823
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
1824
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
1825
|
+
`;
|
|
1826
|
+
function escapeHtml(value) {
|
|
1827
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1828
|
+
}
|
|
1829
|
+
function layout(title, body) {
|
|
1830
|
+
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>`;
|
|
1831
|
+
}
|
|
1832
|
+
function displayName(user) {
|
|
1833
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
1834
|
+
}
|
|
1835
|
+
function renderSignIn(options) {
|
|
1836
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
1837
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
1838
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
1839
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
1840
|
+
const tag2 = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
1841
|
+
return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag2}</span></button>`;
|
|
1842
|
+
}).join("");
|
|
1843
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
1844
|
+
return layout(
|
|
1845
|
+
"Sign in",
|
|
1846
|
+
`<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>`
|
|
1847
|
+
);
|
|
1848
|
+
}
|
|
1849
|
+
function renderOrganizationPicker(options) {
|
|
1850
|
+
const choices = options.organizations.map(
|
|
1851
|
+
(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>`
|
|
1852
|
+
).join("");
|
|
1853
|
+
return layout(
|
|
1854
|
+
"Choose an organization",
|
|
1855
|
+
`<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>`
|
|
1856
|
+
);
|
|
1857
|
+
}
|
|
1858
|
+
function renderMessage(title, message2) {
|
|
1859
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message2)}</p>`);
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
// src/seed.ts
|
|
1863
|
+
function roleRecord(key, extra = {}) {
|
|
1864
|
+
return {
|
|
1865
|
+
id: stableId("role", key),
|
|
1866
|
+
key,
|
|
1867
|
+
name: extra.name ?? titleCase(key),
|
|
1868
|
+
description: extra.description ?? null,
|
|
1869
|
+
isDefault: extra.isDefault ?? false,
|
|
1870
|
+
permissions: [...extra.permissions ?? []]
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
function permissionRecord(key, extra = {}) {
|
|
1874
|
+
return {
|
|
1875
|
+
id: stableId("perm", key),
|
|
1876
|
+
key,
|
|
1877
|
+
name: extra.name ?? titleCase(key.replace(/[:.]/g, " ")),
|
|
1878
|
+
description: extra.description ?? null
|
|
1879
|
+
};
|
|
1880
|
+
}
|
|
1881
|
+
function effectivePermissions(seed, membership) {
|
|
1882
|
+
if (!membership) return [];
|
|
1883
|
+
const fromRoles = membership.roles.flatMap((key) => seed.roles.find((role) => role.key === key)?.permissions ?? []);
|
|
1884
|
+
return [.../* @__PURE__ */ new Set([...membership.permissions, ...fromRoles])];
|
|
1885
|
+
}
|
|
1886
|
+
function resolveSeed(input) {
|
|
1887
|
+
const problems = [];
|
|
1888
|
+
if (!isRecord(input)) {
|
|
1889
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
1890
|
+
}
|
|
1891
|
+
const rawUsers = listOf(input.users, "users", problems);
|
|
1892
|
+
const rawOrganizations = listOf(input.organizations, "organizations", problems);
|
|
1893
|
+
const rawMemberships = listOf(input.memberships, "memberships", problems);
|
|
1894
|
+
const rawApplications = listOf(input.applications, "applications", problems);
|
|
1895
|
+
const rawWebhooks = listOf(input.webhooks, "webhooks", problems);
|
|
1896
|
+
const rawRoles = listOf(input.roles, "roles", problems);
|
|
1897
|
+
const rawFlags = listOf(input.featureFlags, "featureFlags", problems);
|
|
1898
|
+
const rawPlans = listOf(input.plans, "plans", problems);
|
|
1899
|
+
const rawPermissions = listOf(input.permissions, "permissions", problems);
|
|
1900
|
+
const webhooks = [];
|
|
1901
|
+
rawWebhooks.forEach((raw, index) => {
|
|
1902
|
+
if (!isRecord(raw) || typeof raw.url !== "string" || !/^https?:\/\//.test(raw.url)) {
|
|
1903
|
+
problems.push(`webhooks[${index}] needs an http or https "url".`);
|
|
1904
|
+
return;
|
|
507
1905
|
}
|
|
508
1906
|
if (raw.events !== void 0 && (!Array.isArray(raw.events) || raw.events.some((e) => typeof e !== "string"))) {
|
|
509
1907
|
problems.push(`webhooks[${index}].events must be a list of event type names.`);
|
|
@@ -602,7 +2000,107 @@ function resolveSeed(input) {
|
|
|
602
2000
|
if (problems.length > 0) {
|
|
603
2001
|
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
604
2002
|
}
|
|
605
|
-
|
|
2003
|
+
const permissions = [];
|
|
2004
|
+
rawPermissions.forEach((raw, index) => {
|
|
2005
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
2006
|
+
problems.push(`permissions[${index}] needs a string "key".`);
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
if (permissions.some((p) => p.key === raw.key)) {
|
|
2010
|
+
problems.push(`permissions[${index}] repeats the key "${raw.key}".`);
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
permissions.push(
|
|
2014
|
+
permissionRecord(raw.key, {
|
|
2015
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
2016
|
+
description: typeof raw.description === "string" ? raw.description : void 0
|
|
2017
|
+
})
|
|
2018
|
+
);
|
|
2019
|
+
});
|
|
2020
|
+
const roles = [];
|
|
2021
|
+
rawRoles.forEach((raw, index) => {
|
|
2022
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || raw.key.length === 0) {
|
|
2023
|
+
problems.push(`roles[${index}] needs a string "key".`);
|
|
2024
|
+
return;
|
|
2025
|
+
}
|
|
2026
|
+
if (roles.some((r) => r.key === raw.key)) {
|
|
2027
|
+
problems.push(`roles[${index}] repeats the key "${raw.key}".`);
|
|
2028
|
+
return;
|
|
2029
|
+
}
|
|
2030
|
+
if (raw.permissions !== void 0 && (!Array.isArray(raw.permissions) || raw.permissions.some((p) => typeof p !== "string"))) {
|
|
2031
|
+
problems.push(`roles[${index}].permissions must be a list of permission keys.`);
|
|
2032
|
+
return;
|
|
2033
|
+
}
|
|
2034
|
+
roles.push(
|
|
2035
|
+
roleRecord(raw.key, {
|
|
2036
|
+
name: typeof raw.name === "string" ? raw.name : void 0,
|
|
2037
|
+
description: typeof raw.description === "string" ? raw.description : void 0,
|
|
2038
|
+
isDefault: raw.isDefault === true,
|
|
2039
|
+
permissions: raw.permissions ?? []
|
|
2040
|
+
})
|
|
2041
|
+
);
|
|
2042
|
+
});
|
|
2043
|
+
if (problems.length > 0) {
|
|
2044
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
2045
|
+
}
|
|
2046
|
+
const featureFlags = [];
|
|
2047
|
+
rawFlags.forEach((raw, index) => {
|
|
2048
|
+
if (!isRecord(raw) || typeof raw.key !== "string" || !["boolean", "string", "number"].includes(typeof raw.value)) {
|
|
2049
|
+
problems.push(`featureFlags[${index}] needs a string "key" and a boolean, string or number "value".`);
|
|
2050
|
+
return;
|
|
2051
|
+
}
|
|
2052
|
+
const type = raw.type === "string" || raw.type === "integer" || raw.type === "boolean" ? raw.type : typeof raw.value === "number" ? "integer" : typeof raw.value === "string" ? "string" : "boolean";
|
|
2053
|
+
featureFlags.push({
|
|
2054
|
+
id: stableId("flag", raw.key),
|
|
2055
|
+
key: raw.key,
|
|
2056
|
+
name: typeof raw.name === "string" ? raw.name : raw.key,
|
|
2057
|
+
type,
|
|
2058
|
+
value: raw.value,
|
|
2059
|
+
organizations: isRecord(raw.organizations) ? raw.organizations : {}
|
|
2060
|
+
});
|
|
2061
|
+
});
|
|
2062
|
+
const plans = [];
|
|
2063
|
+
rawPlans.forEach((raw, index) => {
|
|
2064
|
+
if (!isRecord(raw) || typeof raw.key !== "string") {
|
|
2065
|
+
problems.push(`plans[${index}] needs a string "key".`);
|
|
2066
|
+
return;
|
|
2067
|
+
}
|
|
2068
|
+
const entitlements = Array.isArray(raw.entitlements) ? raw.entitlements : [];
|
|
2069
|
+
plans.push({
|
|
2070
|
+
key: raw.key,
|
|
2071
|
+
name: typeof raw.name === "string" ? raw.name : titleCase(raw.key),
|
|
2072
|
+
subscribers: Array.isArray(raw.subscribers) ? raw.subscribers.filter((s) => typeof s === "string") : [],
|
|
2073
|
+
subscribedOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2074
|
+
entitlements: entitlements.filter((e) => typeof e.featureKey === "string").map((e) => ({
|
|
2075
|
+
id: stableId("entitlement", `${raw.key}:${e.featureKey}`),
|
|
2076
|
+
featureKey: e.featureKey,
|
|
2077
|
+
featureName: typeof e.featureName === "string" ? e.featureName : titleCase(e.featureKey),
|
|
2078
|
+
priceName: typeof e.priceName === "string" ? e.priceName : titleCase(e.featureKey),
|
|
2079
|
+
fixedCharge: typeof e.fixedCharge === "number" ? e.fixedCharge : null,
|
|
2080
|
+
unitAmount: typeof e.unitAmount === "number" ? e.unitAmount : null,
|
|
2081
|
+
limitMax: typeof e.limitMax === "number" ? e.limitMax : null,
|
|
2082
|
+
limitMin: typeof e.limitMin === "number" ? e.limitMin : null
|
|
2083
|
+
}))
|
|
2084
|
+
});
|
|
2085
|
+
});
|
|
2086
|
+
const userProperties = {};
|
|
2087
|
+
rawUsers.forEach((raw) => {
|
|
2088
|
+
if (isRecord(raw) && typeof raw.id === "string" && isRecord(raw.properties)) {
|
|
2089
|
+
userProperties[raw.id] = raw.properties;
|
|
2090
|
+
}
|
|
2091
|
+
});
|
|
2092
|
+
if (problems.length > 0) {
|
|
2093
|
+
throw new TestkitError("SEED_INVALID", "The seed has problems. Fix them and start again.", problems);
|
|
2094
|
+
}
|
|
2095
|
+
const usedRoles = new Set(memberships.flatMap((m) => m.roles));
|
|
2096
|
+
for (const key of usedRoles) if (!roles.some((r) => r.key === key)) roles.push(roleRecord(key));
|
|
2097
|
+
const usedPermissions = /* @__PURE__ */ new Set([
|
|
2098
|
+
...memberships.flatMap((m) => m.permissions),
|
|
2099
|
+
...roles.flatMap((r) => r.permissions),
|
|
2100
|
+
...applications.flatMap((a) => a.permissions ?? [])
|
|
2101
|
+
]);
|
|
2102
|
+
for (const key of usedPermissions) if (!permissions.some((p) => p.key === key)) permissions.push(permissionRecord(key));
|
|
2103
|
+
return { users, organizations, memberships, applications, webhooks, roles, permissions, featureFlags, plans, userProperties };
|
|
606
2104
|
}
|
|
607
2105
|
function findUser(users, ref) {
|
|
608
2106
|
const needle = ref.toLowerCase();
|
|
@@ -647,7 +2145,7 @@ function seedScenario(seed, ref) {
|
|
|
647
2145
|
user,
|
|
648
2146
|
organization,
|
|
649
2147
|
roles: [...membership?.roles ?? []],
|
|
650
|
-
permissions:
|
|
2148
|
+
permissions: effectivePermissions(seed, membership),
|
|
651
2149
|
claims: {}
|
|
652
2150
|
};
|
|
653
2151
|
}
|
|
@@ -662,72 +2160,18 @@ function listOf(value, field, problems) {
|
|
|
662
2160
|
function isRecord(value) {
|
|
663
2161
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
664
2162
|
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
*{box-sizing:border-box}
|
|
674
|
-
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}
|
|
675
|
-
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
676
|
-
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
677
|
-
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
678
|
-
p{margin:0;color:var(--muted)}
|
|
679
|
-
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
680
|
-
form{margin:0}
|
|
681
|
-
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
682
|
-
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}
|
|
683
|
-
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
684
|
-
.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}
|
|
685
|
-
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
686
|
-
.list{display:grid;gap:8px}
|
|
687
|
-
.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}
|
|
688
|
-
.option:hover{border-color:var(--muted)}
|
|
689
|
-
.option strong{display:block;font-weight:500}
|
|
690
|
-
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
691
|
-
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
692
|
-
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
693
|
-
`;
|
|
694
|
-
function escapeHtml(value) {
|
|
695
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
696
|
-
}
|
|
697
|
-
function layout(title, body) {
|
|
698
|
-
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>`;
|
|
699
|
-
}
|
|
700
|
-
function displayName(user) {
|
|
701
|
-
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
702
|
-
}
|
|
703
|
-
function renderSignIn(options) {
|
|
704
|
-
const users = options.users.map(({ user, organizations }) => {
|
|
705
|
-
const value = escapeHtml(user.email ?? user.id);
|
|
706
|
-
const hasName = Boolean(user.givenName || user.familyName);
|
|
707
|
-
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
708
|
-
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
709
|
-
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>`;
|
|
710
|
-
}).join("");
|
|
711
|
-
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
712
|
-
return layout(
|
|
713
|
-
"Sign in",
|
|
714
|
-
`<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>`
|
|
715
|
-
);
|
|
716
|
-
}
|
|
717
|
-
function renderOrganizationPicker(options) {
|
|
718
|
-
const choices = options.organizations.map(
|
|
719
|
-
(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>`
|
|
720
|
-
).join("");
|
|
721
|
-
return layout(
|
|
722
|
-
"Choose an organization",
|
|
723
|
-
`<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>`
|
|
724
|
-
);
|
|
725
|
-
}
|
|
726
|
-
function renderMessage(title, message) {
|
|
727
|
-
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
2163
|
+
function featureFlagsFor(seed, organizationCode) {
|
|
2164
|
+
if (seed.featureFlags.length === 0) return void 0;
|
|
2165
|
+
const claim = {};
|
|
2166
|
+
for (const flag of seed.featureFlags) {
|
|
2167
|
+
const value = organizationCode && organizationCode in flag.organizations ? flag.organizations[organizationCode] : flag.value;
|
|
2168
|
+
claim[flag.key] = { t: flag.type === "boolean" ? "b" : flag.type === "integer" ? "i" : "s", v: value };
|
|
2169
|
+
}
|
|
2170
|
+
return claim;
|
|
728
2171
|
}
|
|
729
2172
|
|
|
730
2173
|
// src/oauth.ts
|
|
2174
|
+
var import_node_crypto4 = require("crypto");
|
|
731
2175
|
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
732
2176
|
var OAuthError = class extends Error {
|
|
733
2177
|
constructor(status, error, description) {
|
|
@@ -739,14 +2183,18 @@ var OAuthError = class extends Error {
|
|
|
739
2183
|
error;
|
|
740
2184
|
};
|
|
741
2185
|
var AuthorizationServer = class {
|
|
742
|
-
constructor(testkit, seed, emit = () => void 0) {
|
|
2186
|
+
constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
|
|
743
2187
|
this.testkit = testkit;
|
|
744
2188
|
this.seed = seed;
|
|
745
2189
|
this.emit = emit;
|
|
2190
|
+
this.directory = directory;
|
|
2191
|
+
this.observe = observe;
|
|
746
2192
|
}
|
|
747
2193
|
testkit;
|
|
748
2194
|
seed;
|
|
749
2195
|
emit;
|
|
2196
|
+
directory;
|
|
2197
|
+
observe;
|
|
750
2198
|
codes = /* @__PURE__ */ new Map();
|
|
751
2199
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
752
2200
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -783,6 +2231,7 @@ var AuthorizationServer = class {
|
|
|
783
2231
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
784
2232
|
}
|
|
785
2233
|
if (params.get("prompt") === "none") {
|
|
2234
|
+
this.observe("session.silent");
|
|
786
2235
|
return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
787
2236
|
}
|
|
788
2237
|
sendHtml(
|
|
@@ -796,15 +2245,15 @@ var AuthorizationServer = class {
|
|
|
796
2245
|
})
|
|
797
2246
|
);
|
|
798
2247
|
}
|
|
799
|
-
login(res,
|
|
2248
|
+
login(res, form2) {
|
|
800
2249
|
let request;
|
|
801
2250
|
try {
|
|
802
|
-
request = decodeRequest(
|
|
2251
|
+
request = decodeRequest(form2.request ?? "");
|
|
803
2252
|
} catch {
|
|
804
2253
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
805
2254
|
}
|
|
806
2255
|
const encoded = encodeRequest(request);
|
|
807
|
-
const ref = (
|
|
2256
|
+
const ref = (form2.user || form2.email || "").trim();
|
|
808
2257
|
if (!ref) {
|
|
809
2258
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
|
|
810
2259
|
}
|
|
@@ -812,11 +2261,25 @@ var AuthorizationServer = class {
|
|
|
812
2261
|
if (!user) {
|
|
813
2262
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
814
2263
|
}
|
|
2264
|
+
if (this.directory?.isSuspended(user.id)) {
|
|
2265
|
+
this.observe("identity.suspended");
|
|
2266
|
+
return sendHtml(
|
|
2267
|
+
res,
|
|
2268
|
+
403,
|
|
2269
|
+
renderSignIn({
|
|
2270
|
+
request: encoded,
|
|
2271
|
+
users: this.loginPageUsers(),
|
|
2272
|
+
requiredOrganization: request.orgCode ?? void 0,
|
|
2273
|
+
error: `${user.email ?? user.id} is suspended and cannot sign in.`
|
|
2274
|
+
})
|
|
2275
|
+
);
|
|
2276
|
+
}
|
|
815
2277
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
816
|
-
const wanted = request.orgCode ??
|
|
2278
|
+
const wanted = request.orgCode ?? form2.org ?? null;
|
|
817
2279
|
let organizationCode = null;
|
|
818
2280
|
if (wanted) {
|
|
819
2281
|
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
2282
|
+
this.observe("organization.non-member");
|
|
820
2283
|
return sendHtml(
|
|
821
2284
|
res,
|
|
822
2285
|
403,
|
|
@@ -848,7 +2311,7 @@ var AuthorizationServer = class {
|
|
|
848
2311
|
user,
|
|
849
2312
|
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
850
2313
|
roles: [...membership?.roles ?? []],
|
|
851
|
-
permissions:
|
|
2314
|
+
permissions: effectivePermissions(this.seed, membership),
|
|
852
2315
|
claims: {}
|
|
853
2316
|
};
|
|
854
2317
|
const code = randomToken();
|
|
@@ -864,24 +2327,27 @@ var AuthorizationServer = class {
|
|
|
864
2327
|
codeChallengeMethod: request.codeChallengeMethod,
|
|
865
2328
|
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
866
2329
|
});
|
|
2330
|
+
this.directory?.recordSignIn(user, organizationCode);
|
|
867
2331
|
this.emit("user.authenticated", user);
|
|
868
2332
|
const target = new URL(request.redirectUri);
|
|
869
2333
|
target.searchParams.set("code", code);
|
|
870
2334
|
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
871
2335
|
redirect(res, target.toString());
|
|
872
2336
|
}
|
|
873
|
-
async token(req, res,
|
|
2337
|
+
async token(req, res, form2) {
|
|
874
2338
|
try {
|
|
875
|
-
const clientId = clientIdFrom(req,
|
|
876
|
-
const grantType =
|
|
2339
|
+
const clientId = clientIdFrom(req, form2);
|
|
2340
|
+
const grantType = form2.grant_type;
|
|
877
2341
|
if (grantType === "client_credentials") {
|
|
878
|
-
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req,
|
|
2342
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
|
|
879
2343
|
}
|
|
880
2344
|
let grant;
|
|
881
2345
|
if (grantType === "authorization_code") {
|
|
882
|
-
grant = this.redeemCode(
|
|
2346
|
+
grant = this.redeemCode(form2, clientId);
|
|
2347
|
+
this.observe("session.sign-in");
|
|
883
2348
|
} else if (grantType === "refresh_token") {
|
|
884
|
-
grant = this.redeemRefreshToken(
|
|
2349
|
+
grant = this.redeemRefreshToken(form2, clientId);
|
|
2350
|
+
this.observe("session.refresh");
|
|
885
2351
|
} else {
|
|
886
2352
|
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
887
2353
|
}
|
|
@@ -893,14 +2359,14 @@ var AuthorizationServer = class {
|
|
|
893
2359
|
throw error;
|
|
894
2360
|
}
|
|
895
2361
|
}
|
|
896
|
-
async clientCredentials(clientId, clientSecret,
|
|
2362
|
+
async clientCredentials(clientId, clientSecret, form2) {
|
|
897
2363
|
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
898
2364
|
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
899
2365
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
900
2366
|
}
|
|
901
|
-
const requested = (
|
|
902
|
-
const granted = app?.scopes ? requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
903
|
-
const audience = (
|
|
2367
|
+
const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
|
|
2368
|
+
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
2369
|
+
const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
|
|
904
2370
|
return {
|
|
905
2371
|
access_token: await this.testkit.m2mToken({
|
|
906
2372
|
clientId,
|
|
@@ -920,8 +2386,8 @@ var AuthorizationServer = class {
|
|
|
920
2386
|
this.refreshTokens.clear();
|
|
921
2387
|
this.signedUpUsers.clear();
|
|
922
2388
|
}
|
|
923
|
-
redeemCode(
|
|
924
|
-
const code =
|
|
2389
|
+
redeemCode(form2, clientId) {
|
|
2390
|
+
const code = form2.code ?? "";
|
|
925
2391
|
const pending = this.codes.get(code);
|
|
926
2392
|
this.codes.delete(code);
|
|
927
2393
|
if (!pending || pending.expiresAt < Date.now()) {
|
|
@@ -930,20 +2396,20 @@ var AuthorizationServer = class {
|
|
|
930
2396
|
if (pending.clientId !== clientId) {
|
|
931
2397
|
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
932
2398
|
}
|
|
933
|
-
if (
|
|
2399
|
+
if (form2.redirect_uri !== pending.redirectUri) {
|
|
934
2400
|
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
935
2401
|
}
|
|
936
2402
|
if (pending.codeChallenge) {
|
|
937
|
-
const verifier =
|
|
938
|
-
const expected = pending.codeChallengeMethod === "plain" ? verifier : (0,
|
|
2403
|
+
const verifier = form2.code_verifier ?? "";
|
|
2404
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
|
|
939
2405
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
940
2406
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
941
2407
|
}
|
|
942
2408
|
}
|
|
943
2409
|
return pending;
|
|
944
2410
|
}
|
|
945
|
-
redeemRefreshToken(
|
|
946
|
-
const token =
|
|
2411
|
+
redeemRefreshToken(form2, clientId) {
|
|
2412
|
+
const token = form2.refresh_token ?? "";
|
|
947
2413
|
const grant = this.refreshTokens.get(token);
|
|
948
2414
|
this.refreshTokens.delete(token);
|
|
949
2415
|
if (!grant) {
|
|
@@ -965,7 +2431,8 @@ var AuthorizationServer = class {
|
|
|
965
2431
|
scopes: grant.scope,
|
|
966
2432
|
clientId: grant.clientId,
|
|
967
2433
|
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
968
|
-
authTime: grant.authTime
|
|
2434
|
+
authTime: grant.authTime,
|
|
2435
|
+
featureFlags: featureFlagsFor(this.seed, scenario2.organization?.code ?? null)
|
|
969
2436
|
}),
|
|
970
2437
|
expires_in: this.testkit.accessTokenLifetime,
|
|
971
2438
|
scope: grant.scope.join(" "),
|
|
@@ -1003,142 +2470,843 @@ var AuthorizationServer = class {
|
|
|
1003
2470
|
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
1004
2471
|
sendJson(res, 200, {
|
|
1005
2472
|
id: user.id,
|
|
1006
|
-
sub: user.id,
|
|
1007
|
-
provided_id: null,
|
|
1008
|
-
name: name || null,
|
|
1009
|
-
given_name: user.givenName,
|
|
1010
|
-
family_name: user.familyName,
|
|
1011
|
-
updated_at: Math.floor(Date.now() / 1e3),
|
|
2473
|
+
sub: user.id,
|
|
2474
|
+
provided_id: null,
|
|
2475
|
+
name: name || null,
|
|
2476
|
+
given_name: user.givenName,
|
|
2477
|
+
family_name: user.familyName,
|
|
2478
|
+
updated_at: Math.floor(Date.now() / 1e3),
|
|
2479
|
+
email: user.email,
|
|
2480
|
+
email_verified: user.emailVerified,
|
|
2481
|
+
picture: user.picture,
|
|
2482
|
+
preferred_username: null,
|
|
2483
|
+
phone: null
|
|
2484
|
+
});
|
|
2485
|
+
}
|
|
2486
|
+
revoke(res, form2) {
|
|
2487
|
+
if (form2.token) this.refreshTokens.delete(form2.token);
|
|
2488
|
+
this.observe("session.revoke");
|
|
2489
|
+
sendJson(res, 200, {});
|
|
2490
|
+
}
|
|
2491
|
+
logout(res, params) {
|
|
2492
|
+
this.observe("session.sign-out");
|
|
2493
|
+
const target = params.get("redirect");
|
|
2494
|
+
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
2495
|
+
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
2496
|
+
}
|
|
2497
|
+
resolveUser(ref) {
|
|
2498
|
+
const seeded = findUser(this.seed.users, ref);
|
|
2499
|
+
if (seeded) return seeded;
|
|
2500
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
2501
|
+
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
2502
|
+
if (!this.signedUpUsers.has(user.id)) {
|
|
2503
|
+
this.signedUpUsers.set(user.id, user);
|
|
2504
|
+
this.observe("identity.unseeded");
|
|
2505
|
+
if (this.directory) this.seed.users.push(user);
|
|
2506
|
+
this.emit("user.created", user);
|
|
2507
|
+
}
|
|
2508
|
+
return this.signedUpUsers.get(user.id);
|
|
2509
|
+
}
|
|
2510
|
+
organization(code) {
|
|
2511
|
+
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
2512
|
+
}
|
|
2513
|
+
loginPageUsers() {
|
|
2514
|
+
return this.seed.users.map((user) => ({
|
|
2515
|
+
user,
|
|
2516
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
2517
|
+
}));
|
|
2518
|
+
}
|
|
2519
|
+
};
|
|
2520
|
+
function parseAuthorizeRequest(params) {
|
|
2521
|
+
const clientId = params.get("client_id");
|
|
2522
|
+
const redirectUri = params.get("redirect_uri");
|
|
2523
|
+
if (!clientId) throw new Error("client_id is missing.");
|
|
2524
|
+
if (!redirectUri || !isHttpUrl(redirectUri)) {
|
|
2525
|
+
throw new Error("redirect_uri must be an absolute http or https URL.");
|
|
2526
|
+
}
|
|
2527
|
+
if (params.get("response_type") !== "code") {
|
|
2528
|
+
throw new Error('response_type must be "code".');
|
|
2529
|
+
}
|
|
2530
|
+
const method = params.get("code_challenge_method");
|
|
2531
|
+
const challenge = params.get("code_challenge");
|
|
2532
|
+
if (challenge && method && method !== "S256" && method !== "plain") {
|
|
2533
|
+
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
2534
|
+
}
|
|
2535
|
+
return {
|
|
2536
|
+
clientId,
|
|
2537
|
+
redirectUri,
|
|
2538
|
+
state: params.get("state"),
|
|
2539
|
+
scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
|
|
2540
|
+
nonce: params.get("nonce"),
|
|
2541
|
+
audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
|
|
2542
|
+
orgCode: params.get("org_code"),
|
|
2543
|
+
loginHint: params.get("login_hint"),
|
|
2544
|
+
codeChallenge: challenge,
|
|
2545
|
+
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
2546
|
+
};
|
|
2547
|
+
}
|
|
2548
|
+
function encodeRequest(request) {
|
|
2549
|
+
return Buffer.from(JSON.stringify(request)).toString("base64url");
|
|
2550
|
+
}
|
|
2551
|
+
function decodeRequest(value) {
|
|
2552
|
+
const request = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
2553
|
+
if (!request.clientId || !request.redirectUri || !isHttpUrl(request.redirectUri)) {
|
|
2554
|
+
throw new Error("invalid request");
|
|
2555
|
+
}
|
|
2556
|
+
return request;
|
|
2557
|
+
}
|
|
2558
|
+
function clientIdFrom(req, form2) {
|
|
2559
|
+
const header = req.headers.authorization ?? "";
|
|
2560
|
+
if (header.startsWith("Basic ")) {
|
|
2561
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
2562
|
+
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
2563
|
+
if (id) return id;
|
|
2564
|
+
}
|
|
2565
|
+
if (form2.client_id) return form2.client_id;
|
|
2566
|
+
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
2567
|
+
}
|
|
2568
|
+
function clientSecretFrom(req, form2) {
|
|
2569
|
+
const header = req.headers.authorization ?? "";
|
|
2570
|
+
if (header.startsWith("Basic ")) {
|
|
2571
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
2572
|
+
const index = decoded.indexOf(":");
|
|
2573
|
+
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
2574
|
+
}
|
|
2575
|
+
return form2.client_secret ?? null;
|
|
2576
|
+
}
|
|
2577
|
+
function redirectWithError(res, request, error, description) {
|
|
2578
|
+
const target = new URL(request.redirectUri);
|
|
2579
|
+
target.searchParams.set("error", error);
|
|
2580
|
+
target.searchParams.set("error_description", description);
|
|
2581
|
+
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
2582
|
+
redirect(res, target.toString());
|
|
2583
|
+
}
|
|
2584
|
+
function isHttpUrl(value) {
|
|
2585
|
+
try {
|
|
2586
|
+
const { protocol } = new URL(value);
|
|
2587
|
+
return protocol === "http:" || protocol === "https:";
|
|
2588
|
+
} catch {
|
|
2589
|
+
return false;
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
function randomToken() {
|
|
2593
|
+
return (0, import_node_crypto4.randomBytes)(32).toString("base64url");
|
|
2594
|
+
}
|
|
2595
|
+
function safeEqual(a, b) {
|
|
2596
|
+
const left = Buffer.from(a);
|
|
2597
|
+
const right = Buffer.from(b);
|
|
2598
|
+
return left.length === right.length && (0, import_node_crypto4.timingSafeEqual)(left, right);
|
|
2599
|
+
}
|
|
2600
|
+
function redirect(res, location) {
|
|
2601
|
+
res.writeHead(303, { location, "cache-control": "no-store" });
|
|
2602
|
+
res.end();
|
|
2603
|
+
}
|
|
2604
|
+
function sendHtml(res, status, html) {
|
|
2605
|
+
res.writeHead(status, {
|
|
2606
|
+
"content-type": "text/html; charset=utf-8",
|
|
2607
|
+
"cache-control": "no-store",
|
|
2608
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
2609
|
+
});
|
|
2610
|
+
res.end(html);
|
|
2611
|
+
}
|
|
2612
|
+
function sendJson(res, status, body) {
|
|
2613
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
2614
|
+
res.end(JSON.stringify(body));
|
|
2615
|
+
}
|
|
2616
|
+
|
|
2617
|
+
// src/account.ts
|
|
2618
|
+
var DEFAULT_PAGE_SIZE = 10;
|
|
2619
|
+
var AccountApi = class {
|
|
2620
|
+
constructor(testkit, directory) {
|
|
2621
|
+
this.testkit = testkit;
|
|
2622
|
+
this.directory = directory;
|
|
2623
|
+
}
|
|
2624
|
+
testkit;
|
|
2625
|
+
directory;
|
|
2626
|
+
async handle(req, res, url) {
|
|
2627
|
+
if (!url.pathname.startsWith("/account_api/v1/")) return false;
|
|
2628
|
+
if ((req.method ?? "GET") !== "GET") {
|
|
2629
|
+
sendJson2(res, 405, errors("METHOD_NOT_ALLOWED", "The Account API endpoints kinde-testkit implements are GET only."));
|
|
2630
|
+
return true;
|
|
2631
|
+
}
|
|
2632
|
+
const header = req.headers.authorization ?? "";
|
|
2633
|
+
let token;
|
|
2634
|
+
try {
|
|
2635
|
+
if (!header.startsWith("Bearer ")) throw new Error("missing");
|
|
2636
|
+
token = await this.testkit.verify(header.slice(7));
|
|
2637
|
+
} catch {
|
|
2638
|
+
sendJson2(res, 403, errors("TOKEN_INVALID", "Send the user's access token from this issuer as a Bearer token."));
|
|
2639
|
+
return true;
|
|
2640
|
+
}
|
|
2641
|
+
if (typeof token.sub !== "string" || Array.isArray(token.gty) && token.gty.includes("client_credentials")) {
|
|
2642
|
+
sendJson2(res, 403, errors("USER_TOKEN_REQUIRED", "The Account API needs a user access token, not a machine-to-machine token."));
|
|
2643
|
+
return true;
|
|
2644
|
+
}
|
|
2645
|
+
const userId = token.sub;
|
|
2646
|
+
const orgCode = typeof token.org_code === "string" ? token.org_code : null;
|
|
2647
|
+
const path = url.pathname.slice("/account_api/v1/".length);
|
|
2648
|
+
const d = this.directory;
|
|
2649
|
+
const membership = orgCode ? d.membership(userId, orgCode) : void 0;
|
|
2650
|
+
if (path === "permissions") {
|
|
2651
|
+
const items = effectivePermissions(d.seed, membership).map((key) => {
|
|
2652
|
+
const p = d.ensurePermission(key);
|
|
2653
|
+
return { id: p.id, name: p.name, key: p.key };
|
|
2654
|
+
});
|
|
2655
|
+
sendPage(res, url, "permissions", items, { org_code: orgCode });
|
|
2656
|
+
return true;
|
|
2657
|
+
}
|
|
2658
|
+
if (path.startsWith("permission/")) {
|
|
2659
|
+
const key = decodeURIComponent(path.slice("permission/".length));
|
|
2660
|
+
sendJson2(res, 200, {
|
|
2661
|
+
data: { org_code: orgCode, permission_key: key, is_granted: effectivePermissions(d.seed, membership).includes(key) }
|
|
2662
|
+
});
|
|
2663
|
+
return true;
|
|
2664
|
+
}
|
|
2665
|
+
if (path === "roles") {
|
|
2666
|
+
const items = (membership?.roles ?? []).map((key) => {
|
|
2667
|
+
const r = d.ensureRole(key);
|
|
2668
|
+
return { id: r.id, name: r.name, key: r.key };
|
|
2669
|
+
});
|
|
2670
|
+
sendPage(res, url, "roles", items, { org_code: orgCode });
|
|
2671
|
+
return true;
|
|
2672
|
+
}
|
|
2673
|
+
if (path === "feature_flags") {
|
|
2674
|
+
const items = d.seed.featureFlags.map((flag) => ({
|
|
2675
|
+
id: flag.id,
|
|
2676
|
+
name: flag.name,
|
|
2677
|
+
key: flag.key,
|
|
2678
|
+
type: flag.type,
|
|
2679
|
+
value: orgCode && orgCode in flag.organizations ? flag.organizations[orgCode] : flag.value
|
|
2680
|
+
}));
|
|
2681
|
+
sendPage(res, url, "feature_flags", items, {});
|
|
2682
|
+
return true;
|
|
2683
|
+
}
|
|
2684
|
+
if (path === "properties") {
|
|
2685
|
+
const values = d.seed.userProperties[userId] ?? {};
|
|
2686
|
+
const items = Object.entries(values).map(([key, value]) => ({ id: `prop_${key}`, name: key, key, value }));
|
|
2687
|
+
sendPage(res, url, "properties", items, {});
|
|
2688
|
+
return true;
|
|
2689
|
+
}
|
|
2690
|
+
if (path === "entitlements" || path.startsWith("entitlement")) {
|
|
2691
|
+
const plan = d.seed.plans.find((p) => p.subscribers.includes(userId)) ?? (orgCode ? d.seed.plans.find((p) => p.subscribers.includes(orgCode)) : void 0);
|
|
2692
|
+
const entitlements = (plan?.entitlements ?? []).map((e) => ({
|
|
2693
|
+
id: e.id,
|
|
2694
|
+
fixed_charge: e.fixedCharge,
|
|
2695
|
+
price_name: e.priceName,
|
|
2696
|
+
unit_amount: e.unitAmount,
|
|
2697
|
+
feature_key: e.featureKey,
|
|
2698
|
+
feature_name: e.featureName,
|
|
2699
|
+
entitlement_limit_max: e.limitMax,
|
|
2700
|
+
entitlement_limit_min: e.limitMin
|
|
2701
|
+
}));
|
|
2702
|
+
if (path === "entitlements") {
|
|
2703
|
+
const plans = plan ? [{ key: plan.key, name: plan.name, subscribed_on: plan.subscribedOn }] : [];
|
|
2704
|
+
sendPage(res, url, "entitlements", entitlements, { org_code: orgCode, plans });
|
|
2705
|
+
return true;
|
|
2706
|
+
}
|
|
2707
|
+
const key = decodeURIComponent(path.replace(/^entitlement\/?/, "")) || url.searchParams.get("key") || "";
|
|
2708
|
+
const entitlement = entitlements.find((e) => e.feature_key === key);
|
|
2709
|
+
if (!entitlement) {
|
|
2710
|
+
sendJson2(res, 404, errors("ENTITLEMENT_NOT_FOUND", `No entitlement for the feature ${key}.`));
|
|
2711
|
+
} else {
|
|
2712
|
+
sendJson2(res, 200, { data: { org_code: orgCode, entitlement }, metadata: {} });
|
|
2713
|
+
}
|
|
2714
|
+
return true;
|
|
2715
|
+
}
|
|
2716
|
+
if (path === "portal_link") {
|
|
2717
|
+
sendJson2(res, 200, { url: `${this.testkit.issuer}/testkit/portal?subnav=${encodeURIComponent(url.searchParams.get("subnav") ?? "profile")}` });
|
|
2718
|
+
return true;
|
|
2719
|
+
}
|
|
2720
|
+
sendJson2(res, 404, errors("ROUTE_NOT_FOUND", `kinde-testkit does not implement GET ${url.pathname}.`));
|
|
2721
|
+
return true;
|
|
2722
|
+
}
|
|
2723
|
+
};
|
|
2724
|
+
function sendPage(res, url, field, items, extra) {
|
|
2725
|
+
const size = Math.max(Number(url.searchParams.get("page_size") ?? DEFAULT_PAGE_SIZE) || DEFAULT_PAGE_SIZE, 1);
|
|
2726
|
+
const after = url.searchParams.get("starting_after");
|
|
2727
|
+
const start = after ? items.findIndex((item) => item.id === after) + 1 : 0;
|
|
2728
|
+
const page = items.slice(start, start + size);
|
|
2729
|
+
const hasMore = start + size < items.length;
|
|
2730
|
+
sendJson2(res, 200, {
|
|
2731
|
+
data: { ...extra, [field]: page },
|
|
2732
|
+
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
2733
|
+
});
|
|
2734
|
+
}
|
|
2735
|
+
function errors(code, message2) {
|
|
2736
|
+
return { errors: [{ code, message: message2 }] };
|
|
2737
|
+
}
|
|
2738
|
+
function sendJson2(res, status, body) {
|
|
2739
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
2740
|
+
res.end(JSON.stringify(body));
|
|
2741
|
+
}
|
|
2742
|
+
|
|
2743
|
+
// src/directory.ts
|
|
2744
|
+
var import_node_crypto5 = require("crypto");
|
|
2745
|
+
var Directory = class {
|
|
2746
|
+
constructor(seed) {
|
|
2747
|
+
this.seed = seed;
|
|
2748
|
+
this.snapshot = JSON.stringify(seed);
|
|
2749
|
+
}
|
|
2750
|
+
seed;
|
|
2751
|
+
userMeta = /* @__PURE__ */ new Map();
|
|
2752
|
+
orgMeta = /* @__PURE__ */ new Map();
|
|
2753
|
+
snapshot;
|
|
2754
|
+
restore() {
|
|
2755
|
+
const original = JSON.parse(this.snapshot);
|
|
2756
|
+
for (const key of ["users", "organizations", "memberships", "roles", "permissions"]) {
|
|
2757
|
+
this.seed[key].splice(0, this.seed[key].length, ...original[key]);
|
|
2758
|
+
}
|
|
2759
|
+
this.userMeta.clear();
|
|
2760
|
+
this.orgMeta.clear();
|
|
2761
|
+
}
|
|
2762
|
+
/** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
|
|
2763
|
+
load(next) {
|
|
2764
|
+
for (const key of Object.keys(next)) {
|
|
2765
|
+
const current = this.seed[key];
|
|
2766
|
+
if (Array.isArray(current)) {
|
|
2767
|
+
current.splice(0, current.length, ...next[key]);
|
|
2768
|
+
} else {
|
|
2769
|
+
const record = current;
|
|
2770
|
+
for (const name of Object.keys(record)) delete record[name];
|
|
2771
|
+
Object.assign(record, next[key]);
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
this.snapshot = JSON.stringify(this.seed);
|
|
2775
|
+
this.userMeta.clear();
|
|
2776
|
+
this.orgMeta.clear();
|
|
2777
|
+
}
|
|
2778
|
+
user(id) {
|
|
2779
|
+
return this.seed.users.find((user) => user.id === id);
|
|
2780
|
+
}
|
|
2781
|
+
meta(user) {
|
|
2782
|
+
let meta = this.userMeta.get(user.id);
|
|
2783
|
+
if (!meta) {
|
|
2784
|
+
meta = {
|
|
2785
|
+
providedId: null,
|
|
2786
|
+
isSuspended: false,
|
|
2787
|
+
isPasswordResetRequested: false,
|
|
2788
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2789
|
+
totalSignIns: 0,
|
|
2790
|
+
lastSignedIn: null
|
|
2791
|
+
};
|
|
2792
|
+
this.userMeta.set(user.id, meta);
|
|
2793
|
+
}
|
|
2794
|
+
return meta;
|
|
2795
|
+
}
|
|
2796
|
+
isSuspended(userId) {
|
|
2797
|
+
return this.userMeta.get(userId)?.isSuspended ?? false;
|
|
2798
|
+
}
|
|
2799
|
+
recordSignIn(user, organizationCode) {
|
|
2800
|
+
const meta = this.meta(user);
|
|
2801
|
+
meta.totalSignIns += 1;
|
|
2802
|
+
meta.lastSignedIn = (/* @__PURE__ */ new Date()).toISOString();
|
|
2803
|
+
void organizationCode;
|
|
2804
|
+
}
|
|
2805
|
+
createUser(input) {
|
|
2806
|
+
const user = createKindeUser({
|
|
2807
|
+
id: `kp_${(0, import_node_crypto5.randomBytes)(16).toString("hex")}`,
|
|
2808
|
+
email: input.email ?? null,
|
|
2809
|
+
givenName: input.givenName ?? null,
|
|
2810
|
+
familyName: input.familyName ?? null,
|
|
2811
|
+
picture: input.picture ?? null
|
|
2812
|
+
});
|
|
2813
|
+
this.seed.users.push(user);
|
|
2814
|
+
this.meta(user).providedId = input.providedId ?? null;
|
|
2815
|
+
return user;
|
|
2816
|
+
}
|
|
2817
|
+
deleteUser(id) {
|
|
2818
|
+
const index = this.seed.users.findIndex((user) => user.id === id);
|
|
2819
|
+
if (index < 0) return false;
|
|
2820
|
+
this.seed.users.splice(index, 1);
|
|
2821
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
2822
|
+
if (this.seed.memberships[i].userId === id) this.seed.memberships.splice(i, 1);
|
|
2823
|
+
}
|
|
2824
|
+
this.userMeta.delete(id);
|
|
2825
|
+
return true;
|
|
2826
|
+
}
|
|
2827
|
+
organization(code) {
|
|
2828
|
+
return this.seed.organizations.find((org) => org.code === code);
|
|
2829
|
+
}
|
|
2830
|
+
orgInfo(org) {
|
|
2831
|
+
let meta = this.orgMeta.get(org.code);
|
|
2832
|
+
if (!meta) {
|
|
2833
|
+
meta = {
|
|
2834
|
+
externalId: typeof org.metadata.external_id === "string" ? org.metadata.external_id : null,
|
|
2835
|
+
handle: slug(org.name),
|
|
2836
|
+
createdOn: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2837
|
+
isAllowRegistrations: false
|
|
2838
|
+
};
|
|
2839
|
+
this.orgMeta.set(org.code, meta);
|
|
2840
|
+
}
|
|
2841
|
+
return meta;
|
|
2842
|
+
}
|
|
2843
|
+
createOrganization(input) {
|
|
2844
|
+
const org = createKindeOrganization({ code: `org_${(0, import_node_crypto5.randomBytes)(6).toString("hex").slice(0, 11)}`, name: input.name });
|
|
2845
|
+
this.seed.organizations.push(org);
|
|
2846
|
+
const meta = this.orgInfo(org);
|
|
2847
|
+
meta.externalId = input.externalId ?? null;
|
|
2848
|
+
if (input.handle) meta.handle = input.handle;
|
|
2849
|
+
return org;
|
|
2850
|
+
}
|
|
2851
|
+
deleteOrganization(code) {
|
|
2852
|
+
const index = this.seed.organizations.findIndex((org) => org.code === code);
|
|
2853
|
+
if (index < 0) return false;
|
|
2854
|
+
this.seed.organizations.splice(index, 1);
|
|
2855
|
+
for (let i = this.seed.memberships.length - 1; i >= 0; i--) {
|
|
2856
|
+
if (this.seed.memberships[i].organizationCode === code) this.seed.memberships.splice(i, 1);
|
|
2857
|
+
}
|
|
2858
|
+
this.orgMeta.delete(code);
|
|
2859
|
+
return true;
|
|
2860
|
+
}
|
|
2861
|
+
membership(userId, organizationCode) {
|
|
2862
|
+
return this.seed.memberships.find((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
2863
|
+
}
|
|
2864
|
+
addMembership(userId, organizationCode, roles = [], permissions = []) {
|
|
2865
|
+
const existing = this.membership(userId, organizationCode);
|
|
2866
|
+
if (existing) return existing;
|
|
2867
|
+
const membership = createMembership({ userId, organizationCode, roles, permissions });
|
|
2868
|
+
this.seed.memberships.push(membership);
|
|
2869
|
+
for (const key of roles) this.ensureRole(key);
|
|
2870
|
+
for (const key of permissions) this.ensurePermission(key);
|
|
2871
|
+
return membership;
|
|
2872
|
+
}
|
|
2873
|
+
removeMembership(userId, organizationCode) {
|
|
2874
|
+
const index = this.seed.memberships.findIndex((m) => m.userId === userId && m.organizationCode === organizationCode);
|
|
2875
|
+
if (index < 0) return false;
|
|
2876
|
+
this.seed.memberships.splice(index, 1);
|
|
2877
|
+
return true;
|
|
2878
|
+
}
|
|
2879
|
+
role(idOrKey) {
|
|
2880
|
+
return this.seed.roles.find((role) => role.id === idOrKey || role.key === idOrKey);
|
|
2881
|
+
}
|
|
2882
|
+
permission(idOrKey) {
|
|
2883
|
+
return this.seed.permissions.find((p) => p.id === idOrKey || p.key === idOrKey);
|
|
2884
|
+
}
|
|
2885
|
+
ensureRole(key, extra = {}) {
|
|
2886
|
+
const existing = this.role(key);
|
|
2887
|
+
if (existing) return existing;
|
|
2888
|
+
const role = roleRecord(key, extra);
|
|
2889
|
+
this.seed.roles.push(role);
|
|
2890
|
+
return role;
|
|
2891
|
+
}
|
|
2892
|
+
ensurePermission(key, extra = {}) {
|
|
2893
|
+
const existing = this.permission(key);
|
|
2894
|
+
if (existing) return existing;
|
|
2895
|
+
const permission = permissionRecord(key, extra);
|
|
2896
|
+
this.seed.permissions.push(permission);
|
|
2897
|
+
return permission;
|
|
2898
|
+
}
|
|
2899
|
+
deleteRole(id) {
|
|
2900
|
+
const role = this.role(id);
|
|
2901
|
+
if (!role) return void 0;
|
|
2902
|
+
this.seed.roles.splice(this.seed.roles.indexOf(role), 1);
|
|
2903
|
+
for (const m of this.seed.memberships) m.roles = m.roles.filter((key) => key !== role.key);
|
|
2904
|
+
return role;
|
|
2905
|
+
}
|
|
2906
|
+
deletePermission(id) {
|
|
2907
|
+
const permission = this.permission(id);
|
|
2908
|
+
if (!permission) return void 0;
|
|
2909
|
+
this.seed.permissions.splice(this.seed.permissions.indexOf(permission), 1);
|
|
2910
|
+
for (const m of this.seed.memberships) m.permissions = m.permissions.filter((key) => key !== permission.key);
|
|
2911
|
+
for (const r of this.seed.roles) r.permissions = r.permissions.filter((key) => key !== permission.key);
|
|
2912
|
+
return permission;
|
|
2913
|
+
}
|
|
2914
|
+
};
|
|
2915
|
+
|
|
2916
|
+
// src/management.ts
|
|
2917
|
+
var OK = { code: "OK", message: "Success" };
|
|
2918
|
+
var DEFAULT_PAGE_SIZE2 = 10;
|
|
2919
|
+
var MAX_PAGE_SIZE = 500;
|
|
2920
|
+
var ManagementApi = class {
|
|
2921
|
+
constructor(testkit, directory, webhooks) {
|
|
2922
|
+
this.testkit = testkit;
|
|
2923
|
+
this.directory = directory;
|
|
2924
|
+
this.webhooks = webhooks;
|
|
2925
|
+
this.register();
|
|
2926
|
+
}
|
|
2927
|
+
testkit;
|
|
2928
|
+
directory;
|
|
2929
|
+
webhooks;
|
|
2930
|
+
routes = [];
|
|
2931
|
+
async handle(req, res, url, readBody) {
|
|
2932
|
+
if (!url.pathname.startsWith("/api/v1/")) return false;
|
|
2933
|
+
const method = req.method ?? "GET";
|
|
2934
|
+
const route = this.routes.find((r) => r.method === method && r.pattern.test(url.pathname));
|
|
2935
|
+
if (!route) {
|
|
2936
|
+
sendJson3(res, 404, errors2("ROUTE_NOT_FOUND", `kinde-testkit does not implement ${method} ${url.pathname}.`));
|
|
2937
|
+
return true;
|
|
2938
|
+
}
|
|
2939
|
+
const token = await this.authenticate(req.headers.authorization);
|
|
2940
|
+
if ("error" in token) {
|
|
2941
|
+
sendJson3(res, 403, errors2(token.code, token.error));
|
|
2942
|
+
return true;
|
|
2943
|
+
}
|
|
2944
|
+
const granted = typeof token.payload.scope === "string" ? token.payload.scope.split(" ").filter(Boolean) : [];
|
|
2945
|
+
if (granted.length > 0 && !granted.includes(route.scope)) {
|
|
2946
|
+
sendJson3(res, 403, errors2("SCOPE_MISSING", `The token needs the ${route.scope} scope.`));
|
|
2947
|
+
return true;
|
|
2948
|
+
}
|
|
2949
|
+
const match = route.pattern.exec(url.pathname);
|
|
2950
|
+
const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(match[i + 1])]));
|
|
2951
|
+
const body = method === "GET" || method === "DELETE" ? {} : await readBody();
|
|
2952
|
+
const [status, payload] = await route.handler({ params, query: url.searchParams, body });
|
|
2953
|
+
sendJson3(res, status, payload);
|
|
2954
|
+
return true;
|
|
2955
|
+
}
|
|
2956
|
+
async authenticate(header) {
|
|
2957
|
+
if (!header?.startsWith("Bearer ")) {
|
|
2958
|
+
return { code: "TOKEN_MISSING", error: "Send a machine-to-machine access token as a Bearer token." };
|
|
2959
|
+
}
|
|
2960
|
+
let payload;
|
|
2961
|
+
try {
|
|
2962
|
+
payload = await this.testkit.verify(header.slice(7));
|
|
2963
|
+
} catch {
|
|
2964
|
+
return { code: "TOKEN_INVALID", error: "The access token is not valid for this issuer." };
|
|
2965
|
+
}
|
|
2966
|
+
const audience = `${this.testkit.issuer}/api`;
|
|
2967
|
+
const aud = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
2968
|
+
if (!aud.includes(audience)) {
|
|
2969
|
+
return { code: "TOKEN_INVALID", error: `The access token's audience must include ${audience}.` };
|
|
2970
|
+
}
|
|
2971
|
+
if (!Array.isArray(payload.gty) || !payload.gty.includes("client_credentials")) {
|
|
2972
|
+
return { code: "TOKEN_INVALID", error: "The Management API needs a machine-to-machine token from the client_credentials grant." };
|
|
2973
|
+
}
|
|
2974
|
+
return { payload };
|
|
2975
|
+
}
|
|
2976
|
+
route(method, path, scope, handler) {
|
|
2977
|
+
const keys = [];
|
|
2978
|
+
const pattern = new RegExp(
|
|
2979
|
+
`^${path.replace(/\{(\w+)\}/g, (_, key) => {
|
|
2980
|
+
keys.push(key);
|
|
2981
|
+
return "([^/]+)";
|
|
2982
|
+
})}$`
|
|
2983
|
+
);
|
|
2984
|
+
this.routes.push({ method, pattern, keys, scope, handler });
|
|
2985
|
+
}
|
|
2986
|
+
register() {
|
|
2987
|
+
const d = this.directory;
|
|
2988
|
+
this.route("GET", "/api/v1/users", "read:users", ({ query }) => {
|
|
2989
|
+
let users = [...d.seed.users];
|
|
2990
|
+
const userId = query.get("user_id");
|
|
2991
|
+
const email = query.get("email")?.toLowerCase();
|
|
2992
|
+
if (userId) users = users.filter((u) => u.id === userId);
|
|
2993
|
+
if (email) users = users.filter((u) => u.email?.toLowerCase() === email);
|
|
2994
|
+
const page = paginate(users, query);
|
|
2995
|
+
return [200, { ...OK, users: page.items.map((u) => this.userListItem(u)), next_token: page.nextToken }];
|
|
2996
|
+
});
|
|
2997
|
+
this.route("GET", "/api/v1/user", "read:users", ({ query }) => {
|
|
2998
|
+
const user = d.user(query.get("id") ?? "");
|
|
2999
|
+
return user ? [200, this.userDetail(user)] : notFound("USER_INVALID", "No user has that id.");
|
|
3000
|
+
});
|
|
3001
|
+
this.route("POST", "/api/v1/user", "create:users", ({ body }) => {
|
|
3002
|
+
const profile = body.profile ?? {};
|
|
3003
|
+
const identities = Array.isArray(body.identities) ? body.identities : [];
|
|
3004
|
+
const emailIdentity = identities.find((i) => i.type === "email");
|
|
3005
|
+
const email = (emailIdentity?.details ?? {}).email;
|
|
3006
|
+
if (typeof email === "string" && d.seed.users.some((u) => u.email?.toLowerCase() === email.toLowerCase())) {
|
|
3007
|
+
return [409, errors2("USER_ALREADY_EXISTS", `A user with the email ${email} already exists.`)];
|
|
3008
|
+
}
|
|
3009
|
+
const orgCode = typeof body.organization_code === "string" ? body.organization_code : null;
|
|
3010
|
+
if (orgCode && !d.organization(orgCode)) return notFound("ORGANIZATION_INVALID", `No organization has the code ${orgCode}.`);
|
|
3011
|
+
const user = d.createUser({
|
|
3012
|
+
email: typeof email === "string" ? email : null,
|
|
3013
|
+
givenName: str(profile.given_name),
|
|
3014
|
+
familyName: str(profile.family_name),
|
|
3015
|
+
picture: str(profile.picture),
|
|
3016
|
+
providedId: str(body.provided_id)
|
|
3017
|
+
});
|
|
3018
|
+
if (orgCode) d.addMembership(user.id, orgCode);
|
|
3019
|
+
this.webhooks.emit("user.created", { user: this.webhooks.userEventData(user) });
|
|
3020
|
+
return [
|
|
3021
|
+
200,
|
|
3022
|
+
{ id: user.id, created: true, identities: identities.map((i) => ({ type: i.type, result: { created: true } })) }
|
|
3023
|
+
];
|
|
3024
|
+
});
|
|
3025
|
+
this.route("PATCH", "/api/v1/user", "update:users", ({ query, body }) => {
|
|
3026
|
+
const user = d.user(query.get("id") ?? "");
|
|
3027
|
+
if (!user) return notFound("USER_INVALID", "No user has that id.");
|
|
3028
|
+
if (typeof body.given_name === "string") user.givenName = body.given_name;
|
|
3029
|
+
if (typeof body.family_name === "string") user.familyName = body.family_name;
|
|
3030
|
+
if (typeof body.picture === "string") user.picture = body.picture;
|
|
3031
|
+
const meta = d.meta(user);
|
|
3032
|
+
if (typeof body.is_suspended === "boolean") meta.isSuspended = body.is_suspended;
|
|
3033
|
+
if (typeof body.is_password_reset_requested === "boolean") meta.isPasswordResetRequested = body.is_password_reset_requested;
|
|
3034
|
+
if (typeof body.provided_id === "string") meta.providedId = body.provided_id;
|
|
3035
|
+
this.webhooks.emit("user.updated", { user: this.webhooks.userEventData(user) });
|
|
3036
|
+
return [
|
|
3037
|
+
200,
|
|
3038
|
+
{
|
|
3039
|
+
id: user.id,
|
|
3040
|
+
given_name: user.givenName,
|
|
3041
|
+
family_name: user.familyName,
|
|
3042
|
+
email: user.email,
|
|
3043
|
+
is_suspended: meta.isSuspended,
|
|
3044
|
+
is_password_reset_requested: meta.isPasswordResetRequested,
|
|
3045
|
+
picture: user.picture
|
|
3046
|
+
}
|
|
3047
|
+
];
|
|
3048
|
+
});
|
|
3049
|
+
this.route("DELETE", "/api/v1/user", "delete:users", ({ query }) => {
|
|
3050
|
+
const id = query.get("id") ?? "";
|
|
3051
|
+
if (!d.deleteUser(id)) return notFound("USER_INVALID", "No user has that id.");
|
|
3052
|
+
this.webhooks.emit("user.deleted", { user: { id } });
|
|
3053
|
+
return [200, OK];
|
|
3054
|
+
});
|
|
3055
|
+
this.route("GET", "/api/v1/organizations", "read:organizations", ({ query }) => {
|
|
3056
|
+
const page = paginate(d.seed.organizations, query);
|
|
3057
|
+
return [200, { ...OK, organizations: page.items.map((o) => this.organizationItem(o)), next_token: page.nextToken }];
|
|
3058
|
+
});
|
|
3059
|
+
this.route("GET", "/api/v1/organization", "read:organizations", ({ query }) => {
|
|
3060
|
+
const org = d.organization(query.get("code") ?? "");
|
|
3061
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
3062
|
+
const meta = d.orgInfo(org);
|
|
3063
|
+
return [200, { ...this.organizationItem(org), created_on: meta.createdOn, is_allow_registrations: meta.isAllowRegistrations }];
|
|
3064
|
+
});
|
|
3065
|
+
this.route("POST", "/api/v1/organization", "create:organizations", ({ body }) => {
|
|
3066
|
+
if (typeof body.name !== "string" || body.name.trim() === "") {
|
|
3067
|
+
return [400, errors2("NAME_REQUIRED", "An organization needs a name.")];
|
|
3068
|
+
}
|
|
3069
|
+
const org = d.createOrganization({ name: body.name, externalId: str(body.external_id), handle: str(body.handle) });
|
|
3070
|
+
if (typeof body.is_allow_registrations === "boolean") d.orgInfo(org).isAllowRegistrations = body.is_allow_registrations;
|
|
3071
|
+
this.webhooks.emit("organization.created", { organization: this.organizationEvent(org) });
|
|
3072
|
+
return [200, { ...OK, organization: { code: org.code } }];
|
|
3073
|
+
});
|
|
3074
|
+
this.route("PATCH", "/api/v1/organization/{org_code}", "update:organizations", ({ params, body }) => {
|
|
3075
|
+
const org = d.organization(params.org_code);
|
|
3076
|
+
if (!org) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
3077
|
+
const meta = d.orgInfo(org);
|
|
3078
|
+
if (typeof body.name === "string") org.name = body.name;
|
|
3079
|
+
if (typeof body.external_id === "string") meta.externalId = body.external_id;
|
|
3080
|
+
if (typeof body.handle === "string") meta.handle = body.handle;
|
|
3081
|
+
if (typeof body.is_allow_registrations === "boolean") meta.isAllowRegistrations = body.is_allow_registrations;
|
|
3082
|
+
this.webhooks.emit("organization.updated", {
|
|
3083
|
+
organization: { ...this.organizationEvent(org), is_allow_registrations: meta.isAllowRegistrations }
|
|
3084
|
+
});
|
|
3085
|
+
return [200, OK];
|
|
3086
|
+
});
|
|
3087
|
+
this.route("DELETE", "/api/v1/organization/{org_code}", "delete:organizations", ({ params }) => {
|
|
3088
|
+
if (!d.deleteOrganization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
3089
|
+
this.webhooks.emit("organization.deleted", { organization: { code: params.org_code } });
|
|
3090
|
+
return [200, OK];
|
|
3091
|
+
});
|
|
3092
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users", "read:organization_users", ({ params, query }) => {
|
|
3093
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
3094
|
+
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);
|
|
3095
|
+
const page = paginate(members, query);
|
|
3096
|
+
return [
|
|
3097
|
+
200,
|
|
3098
|
+
{
|
|
3099
|
+
...OK,
|
|
3100
|
+
organization_users: page.items.map(({ membership, user }) => ({
|
|
3101
|
+
id: user.id,
|
|
3102
|
+
email: user.email,
|
|
3103
|
+
full_name: [user.givenName, user.familyName].filter(Boolean).join(" "),
|
|
3104
|
+
last_name: user.familyName,
|
|
3105
|
+
first_name: user.givenName,
|
|
3106
|
+
picture: user.picture,
|
|
3107
|
+
joined_on: d.meta(user).createdOn,
|
|
3108
|
+
last_accessed_on: d.meta(user).lastSignedIn,
|
|
3109
|
+
is_suspended: d.meta(user).isSuspended,
|
|
3110
|
+
roles: [...membership.roles]
|
|
3111
|
+
})),
|
|
3112
|
+
next_token: page.nextToken
|
|
3113
|
+
}
|
|
3114
|
+
];
|
|
3115
|
+
});
|
|
3116
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users", "create:organization_users", ({ params, body }) => {
|
|
3117
|
+
if (!d.organization(params.org_code)) return notFound("ORGANIZATION_INVALID", "No organization has that code.");
|
|
3118
|
+
const users = Array.isArray(body.users) ? body.users : [];
|
|
3119
|
+
const added = [];
|
|
3120
|
+
const blocked = [];
|
|
3121
|
+
for (const entry of users) {
|
|
3122
|
+
const id = typeof entry.id === "string" ? entry.id : "";
|
|
3123
|
+
if (!d.user(id)) {
|
|
3124
|
+
blocked.push(id);
|
|
3125
|
+
continue;
|
|
3126
|
+
}
|
|
3127
|
+
d.addMembership(id, params.org_code, strings(entry.roles), strings(entry.permissions));
|
|
3128
|
+
added.push(id);
|
|
3129
|
+
}
|
|
3130
|
+
return [200, { ...OK, users_added: added, users_blocked: blocked }];
|
|
3131
|
+
});
|
|
3132
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}", "delete:organization_users", ({ params }) => {
|
|
3133
|
+
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}.`);
|
|
3134
|
+
});
|
|
3135
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "read:organization_user_roles", ({ params }) => {
|
|
3136
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
3137
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
3138
|
+
const roles = membership.roles.map((key) => d.ensureRole(key));
|
|
3139
|
+
return [200, { ...OK, roles: roles.map((r) => ({ id: r.id, key: r.key, name: r.name })) }];
|
|
3140
|
+
});
|
|
3141
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/roles", "create:organization_user_roles", ({ params, body }) => {
|
|
3142
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
3143
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
3144
|
+
const role = d.role(str(body.role_id) ?? "");
|
|
3145
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
3146
|
+
if (!membership.roles.includes(role.key)) membership.roles.push(role.key);
|
|
3147
|
+
return [200, OK];
|
|
3148
|
+
});
|
|
3149
|
+
this.route("DELETE", "/api/v1/organizations/{org_code}/users/{user_id}/roles/{role_id}", "delete:organization_user_roles", ({ params }) => {
|
|
3150
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
3151
|
+
const role = d.role(params.role_id);
|
|
3152
|
+
if (!membership || !role) return notFound("ROLE_INVALID", "No such role on that member.");
|
|
3153
|
+
membership.roles = membership.roles.filter((key) => key !== role.key);
|
|
3154
|
+
return [200, OK];
|
|
3155
|
+
});
|
|
3156
|
+
this.route("GET", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "read:organization_user_permissions", ({ params }) => {
|
|
3157
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
3158
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
3159
|
+
const permissions = effectivePermissions(d.seed, membership).map((key) => {
|
|
3160
|
+
const permission = d.ensurePermission(key);
|
|
3161
|
+
const roles = membership.roles.map((roleKey) => d.role(roleKey)).filter((role) => role?.permissions.includes(key)).map((role) => ({ id: role.id, key: role.key }));
|
|
3162
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description, roles };
|
|
3163
|
+
});
|
|
3164
|
+
return [200, { ...OK, permissions }];
|
|
3165
|
+
});
|
|
3166
|
+
this.route("POST", "/api/v1/organizations/{org_code}/users/{user_id}/permissions", "create:organization_user_permissions", ({ params, body }) => {
|
|
3167
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
3168
|
+
if (!membership) return notFound("MEMBERSHIP_INVALID", `${params.user_id} is not a member of ${params.org_code}.`);
|
|
3169
|
+
const permission = d.permission(str(body.permission_id) ?? "");
|
|
3170
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
3171
|
+
if (!membership.permissions.includes(permission.key)) membership.permissions.push(permission.key);
|
|
3172
|
+
return [200, OK];
|
|
3173
|
+
});
|
|
3174
|
+
this.route(
|
|
3175
|
+
"DELETE",
|
|
3176
|
+
"/api/v1/organizations/{org_code}/users/{user_id}/permissions/{permission_id}",
|
|
3177
|
+
"delete:organization_user_permissions",
|
|
3178
|
+
({ params }) => {
|
|
3179
|
+
const membership = d.membership(params.user_id, params.org_code);
|
|
3180
|
+
const permission = d.permission(params.permission_id);
|
|
3181
|
+
if (!membership || !permission) return notFound("PERMISSION_INVALID", "No such permission on that member.");
|
|
3182
|
+
membership.permissions = membership.permissions.filter((key) => key !== permission.key);
|
|
3183
|
+
return [200, OK];
|
|
3184
|
+
}
|
|
3185
|
+
);
|
|
3186
|
+
this.route("GET", "/api/v1/roles", "read:roles", ({ query }) => {
|
|
3187
|
+
const page = paginate(d.seed.roles, query);
|
|
3188
|
+
return [200, { ...OK, roles: page.items.map((r) => this.roleItem(r)), next_token: page.nextToken }];
|
|
3189
|
+
});
|
|
3190
|
+
this.route("POST", "/api/v1/roles", "create:roles", ({ body }) => {
|
|
3191
|
+
const key = str(body.key);
|
|
3192
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A role needs a key.")];
|
|
3193
|
+
if (d.role(key)) return [409, errors2("ROLE_ALREADY_EXISTS", `A role with the key ${key} already exists.`)];
|
|
3194
|
+
const role = d.ensureRole(key, {
|
|
3195
|
+
name: str(body.name) ?? void 0,
|
|
3196
|
+
description: str(body.description) ?? void 0,
|
|
3197
|
+
isDefault: body.is_default_role === true
|
|
3198
|
+
});
|
|
3199
|
+
this.webhooks.emit("role.created", {
|
|
3200
|
+
role: { description: role.description ?? "", id: role.id, is_default_role: role.isDefault, key: role.key, name: role.name }
|
|
3201
|
+
});
|
|
3202
|
+
return [201, { ...OK, role: { id: role.id } }];
|
|
3203
|
+
});
|
|
3204
|
+
this.route("GET", "/api/v1/roles/{role_id}", "read:roles", ({ params }) => {
|
|
3205
|
+
const role = d.role(params.role_id);
|
|
3206
|
+
return role ? [200, { ...OK, role: this.roleItem(role) }] : notFound("ROLE_INVALID", "No role has that id.");
|
|
3207
|
+
});
|
|
3208
|
+
this.route("DELETE", "/api/v1/roles/{role_id}", "delete:roles", ({ params }) => {
|
|
3209
|
+
const role = d.deleteRole(params.role_id);
|
|
3210
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
3211
|
+
this.webhooks.emit("role.deleted", { role: { id: role.id } });
|
|
3212
|
+
return [200, OK];
|
|
3213
|
+
});
|
|
3214
|
+
this.route("GET", "/api/v1/roles/{role_id}/permissions", "read:role_permissions", ({ params }) => {
|
|
3215
|
+
const role = d.role(params.role_id);
|
|
3216
|
+
if (!role) return notFound("ROLE_INVALID", "No role has that id.");
|
|
3217
|
+
return [200, { ...OK, permissions: role.permissions.map((key) => this.permissionItem(d.ensurePermission(key))) }];
|
|
3218
|
+
});
|
|
3219
|
+
this.route("GET", "/api/v1/permissions", "read:permissions", ({ query }) => {
|
|
3220
|
+
const page = paginate(d.seed.permissions, query);
|
|
3221
|
+
return [200, { ...OK, permissions: page.items.map((p) => this.permissionItem(p)), next_token: page.nextToken }];
|
|
3222
|
+
});
|
|
3223
|
+
this.route("POST", "/api/v1/permissions", "create:permissions", ({ body }) => {
|
|
3224
|
+
const key = str(body.key);
|
|
3225
|
+
if (!key) return [400, errors2("KEY_REQUIRED", "A permission needs a key.")];
|
|
3226
|
+
if (d.permission(key)) return [409, errors2("PERMISSION_ALREADY_EXISTS", `A permission with the key ${key} already exists.`)];
|
|
3227
|
+
const permission = d.ensurePermission(key, { name: str(body.name) ?? void 0, description: str(body.description) ?? void 0 });
|
|
3228
|
+
this.webhooks.emit("permission.created", {
|
|
3229
|
+
permission: { description: permission.description ?? "", id: permission.id, key: permission.key, name: permission.name }
|
|
3230
|
+
});
|
|
3231
|
+
return [201, OK];
|
|
3232
|
+
});
|
|
3233
|
+
this.route("DELETE", "/api/v1/permissions/{permission_id}", "delete:permissions", ({ params }) => {
|
|
3234
|
+
const permission = d.deletePermission(params.permission_id);
|
|
3235
|
+
if (!permission) return notFound("PERMISSION_INVALID", "No permission has that id.");
|
|
3236
|
+
this.webhooks.emit("permission.deleted", { permission: { id: permission.id } });
|
|
3237
|
+
return [200, OK];
|
|
3238
|
+
});
|
|
3239
|
+
}
|
|
3240
|
+
userListItem(user) {
|
|
3241
|
+
const meta = this.directory.meta(user);
|
|
3242
|
+
return {
|
|
3243
|
+
id: user.id,
|
|
3244
|
+
provided_id: meta.providedId,
|
|
1012
3245
|
email: user.email,
|
|
1013
|
-
|
|
3246
|
+
phone: null,
|
|
3247
|
+
username: null,
|
|
3248
|
+
last_name: user.familyName,
|
|
3249
|
+
first_name: user.givenName,
|
|
3250
|
+
is_suspended: meta.isSuspended,
|
|
1014
3251
|
picture: user.picture,
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
}
|
|
1023
|
-
logout(res, params) {
|
|
1024
|
-
const target = params.get("redirect");
|
|
1025
|
-
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
1026
|
-
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
1027
|
-
}
|
|
1028
|
-
resolveUser(ref) {
|
|
1029
|
-
const seeded = findUser(this.seed.users, ref);
|
|
1030
|
-
if (seeded) return seeded;
|
|
1031
|
-
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
1032
|
-
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
1033
|
-
if (!this.signedUpUsers.has(user.id)) {
|
|
1034
|
-
this.signedUpUsers.set(user.id, user);
|
|
1035
|
-
this.emit("user.created", user);
|
|
1036
|
-
}
|
|
1037
|
-
return this.signedUpUsers.get(user.id);
|
|
1038
|
-
}
|
|
1039
|
-
organization(code) {
|
|
1040
|
-
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
1041
|
-
}
|
|
1042
|
-
loginPageUsers() {
|
|
1043
|
-
return this.seed.users.map((user) => ({
|
|
1044
|
-
user,
|
|
1045
|
-
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
1046
|
-
}));
|
|
1047
|
-
}
|
|
1048
|
-
};
|
|
1049
|
-
function parseAuthorizeRequest(params) {
|
|
1050
|
-
const clientId = params.get("client_id");
|
|
1051
|
-
const redirectUri = params.get("redirect_uri");
|
|
1052
|
-
if (!clientId) throw new Error("client_id is missing.");
|
|
1053
|
-
if (!redirectUri || !isHttpUrl(redirectUri)) {
|
|
1054
|
-
throw new Error("redirect_uri must be an absolute http or https URL.");
|
|
3252
|
+
total_sign_ins: meta.totalSignIns,
|
|
3253
|
+
failed_sign_ins: 0,
|
|
3254
|
+
last_signed_in: meta.lastSignedIn,
|
|
3255
|
+
created_on: meta.createdOn,
|
|
3256
|
+
organizations: this.organizationsOf(user),
|
|
3257
|
+
identities: user.email ? [{ type: "email", identity: user.email }] : []
|
|
3258
|
+
};
|
|
1055
3259
|
}
|
|
1056
|
-
|
|
1057
|
-
|
|
3260
|
+
userDetail(user) {
|
|
3261
|
+
const { email, ...rest } = this.userListItem(user);
|
|
3262
|
+
return { ...rest, preferred_email: email };
|
|
1058
3263
|
}
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
if (challenge && method && method !== "S256" && method !== "plain") {
|
|
1062
|
-
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
3264
|
+
organizationsOf(user) {
|
|
3265
|
+
return this.directory.seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode);
|
|
1063
3266
|
}
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
1075
|
-
};
|
|
1076
|
-
}
|
|
1077
|
-
function encodeRequest(request) {
|
|
1078
|
-
return Buffer.from(JSON.stringify(request)).toString("base64url");
|
|
1079
|
-
}
|
|
1080
|
-
function decodeRequest(value) {
|
|
1081
|
-
const request = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
1082
|
-
if (!request.clientId || !request.redirectUri || !isHttpUrl(request.redirectUri)) {
|
|
1083
|
-
throw new Error("invalid request");
|
|
3267
|
+
organizationItem(org) {
|
|
3268
|
+
const meta = this.directory.orgInfo(org);
|
|
3269
|
+
return {
|
|
3270
|
+
code: org.code,
|
|
3271
|
+
name: org.name,
|
|
3272
|
+
handle: meta.handle,
|
|
3273
|
+
is_default: false,
|
|
3274
|
+
external_id: meta.externalId,
|
|
3275
|
+
is_auto_membership_enabled: false
|
|
3276
|
+
};
|
|
1084
3277
|
}
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
const header = req.headers.authorization ?? "";
|
|
1089
|
-
if (header.startsWith("Basic ")) {
|
|
1090
|
-
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1091
|
-
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
1092
|
-
if (id) return id;
|
|
3278
|
+
organizationEvent(org) {
|
|
3279
|
+
const meta = this.directory.orgInfo(org);
|
|
3280
|
+
return { code: org.code, external_id: meta.externalId, handle: meta.handle, name: org.name };
|
|
1093
3281
|
}
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
}
|
|
1097
|
-
function clientSecretFrom(req, form) {
|
|
1098
|
-
const header = req.headers.authorization ?? "";
|
|
1099
|
-
if (header.startsWith("Basic ")) {
|
|
1100
|
-
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1101
|
-
const index = decoded.indexOf(":");
|
|
1102
|
-
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
3282
|
+
roleItem(role) {
|
|
3283
|
+
return { id: role.id, key: role.key, name: role.name, description: role.description, is_default_role: role.isDefault };
|
|
1103
3284
|
}
|
|
1104
|
-
|
|
1105
|
-
}
|
|
1106
|
-
function redirectWithError(res, request, error, description) {
|
|
1107
|
-
const target = new URL(request.redirectUri);
|
|
1108
|
-
target.searchParams.set("error", error);
|
|
1109
|
-
target.searchParams.set("error_description", description);
|
|
1110
|
-
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
1111
|
-
redirect(res, target.toString());
|
|
1112
|
-
}
|
|
1113
|
-
function isHttpUrl(value) {
|
|
1114
|
-
try {
|
|
1115
|
-
const { protocol } = new URL(value);
|
|
1116
|
-
return protocol === "http:" || protocol === "https:";
|
|
1117
|
-
} catch {
|
|
1118
|
-
return false;
|
|
3285
|
+
permissionItem(permission) {
|
|
3286
|
+
return { id: permission.id, key: permission.key, name: permission.name, description: permission.description };
|
|
1119
3287
|
}
|
|
3288
|
+
};
|
|
3289
|
+
function paginate(items, query) {
|
|
3290
|
+
const size = Math.min(Math.max(Number(query.get("page_size") ?? DEFAULT_PAGE_SIZE2) || DEFAULT_PAGE_SIZE2, 1), MAX_PAGE_SIZE);
|
|
3291
|
+
const token = query.get("next_token");
|
|
3292
|
+
const offset = token ? Number(Buffer.from(token, "base64url").toString("utf8")) || 0 : 0;
|
|
3293
|
+
const page = items.slice(offset, offset + size);
|
|
3294
|
+
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
3295
|
+
return { items: page, nextToken: next };
|
|
1120
3296
|
}
|
|
1121
|
-
function
|
|
1122
|
-
return
|
|
3297
|
+
function errors2(code, message2) {
|
|
3298
|
+
return { errors: [{ code, message: message2 }] };
|
|
1123
3299
|
}
|
|
1124
|
-
function
|
|
1125
|
-
|
|
1126
|
-
const right = Buffer.from(b);
|
|
1127
|
-
return left.length === right.length && (0, import_node_crypto3.timingSafeEqual)(left, right);
|
|
3300
|
+
function notFound(code, message2) {
|
|
3301
|
+
return [404, errors2(code, message2)];
|
|
1128
3302
|
}
|
|
1129
|
-
function
|
|
1130
|
-
|
|
1131
|
-
res.end();
|
|
3303
|
+
function str(value) {
|
|
3304
|
+
return typeof value === "string" ? value : null;
|
|
1132
3305
|
}
|
|
1133
|
-
function
|
|
1134
|
-
|
|
1135
|
-
"content-type": "text/html; charset=utf-8",
|
|
1136
|
-
"cache-control": "no-store",
|
|
1137
|
-
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
1138
|
-
});
|
|
1139
|
-
res.end(html);
|
|
3306
|
+
function strings(value) {
|
|
3307
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
1140
3308
|
}
|
|
1141
|
-
function
|
|
3309
|
+
function sendJson3(res, status, body) {
|
|
1142
3310
|
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1143
3311
|
res.end(JSON.stringify(body));
|
|
1144
3312
|
}
|
|
@@ -1224,7 +3392,7 @@ function validate(rule) {
|
|
|
1224
3392
|
}
|
|
1225
3393
|
|
|
1226
3394
|
// src/webhooks.ts
|
|
1227
|
-
var
|
|
3395
|
+
var import_node_crypto6 = require("crypto");
|
|
1228
3396
|
var WEBHOOK_EVENT_TYPES = [
|
|
1229
3397
|
"user.created",
|
|
1230
3398
|
"user.updated",
|
|
@@ -1273,6 +3441,8 @@ var WebhookDispatcher = class {
|
|
|
1273
3441
|
nextEndpoint = 1;
|
|
1274
3442
|
retryDelaysMs;
|
|
1275
3443
|
timeoutMs;
|
|
3444
|
+
/** Set by the server to record coverage. */
|
|
3445
|
+
observe = () => void 0;
|
|
1276
3446
|
addEndpoint(input) {
|
|
1277
3447
|
if (!isHttpUrl2(input.url)) {
|
|
1278
3448
|
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
@@ -1284,6 +3454,14 @@ var WebhookDispatcher = class {
|
|
|
1284
3454
|
this.endpoints.push(endpoint);
|
|
1285
3455
|
return { ...endpoint };
|
|
1286
3456
|
}
|
|
3457
|
+
/** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
|
|
3458
|
+
replaceSeededEndpoints(endpoints) {
|
|
3459
|
+
const seeded = new Set(this.seededEndpoints.map((e) => e.id));
|
|
3460
|
+
this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
|
|
3461
|
+
const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
|
|
3462
|
+
const ids = new Set(added.map((e) => e.id));
|
|
3463
|
+
this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
|
|
3464
|
+
}
|
|
1287
3465
|
removeEndpoint(id) {
|
|
1288
3466
|
const before = this.endpoints.length;
|
|
1289
3467
|
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
@@ -1307,7 +3485,7 @@ var WebhookDispatcher = class {
|
|
|
1307
3485
|
const timestamp = (options.invalid === "stale" ? new Date(now.getTime() - 36e5) : now).toISOString();
|
|
1308
3486
|
const event = {
|
|
1309
3487
|
data: options.data ?? this.buildData(options),
|
|
1310
|
-
event_id: `event_${(0,
|
|
3488
|
+
event_id: `event_${(0, import_node_crypto6.randomBytes)(16).toString("hex")}`,
|
|
1311
3489
|
event_timestamp: timestamp,
|
|
1312
3490
|
source: options.source ?? "admin",
|
|
1313
3491
|
timestamp,
|
|
@@ -1334,16 +3512,23 @@ var WebhookDispatcher = class {
|
|
|
1334
3512
|
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
1335
3513
|
);
|
|
1336
3514
|
}
|
|
3515
|
+
if (copies > 1) this.observe("webhook.duplicate");
|
|
3516
|
+
if (options.invalid === "stale") this.observe("webhook.stale");
|
|
3517
|
+
else if (options.invalid) this.observe("webhook.forged");
|
|
1337
3518
|
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
1338
3519
|
const signed = await this.testkit.signPayload(
|
|
1339
3520
|
event,
|
|
1340
3521
|
options.invalid === "stale" ? void 0 : options.invalid
|
|
1341
3522
|
);
|
|
1342
3523
|
const jobs = targets.flatMap((target) => {
|
|
1343
|
-
const webhookId = `wh_${(0,
|
|
3524
|
+
const webhookId = `wh_${(0, import_node_crypto6.randomBytes)(12).toString("hex")}`;
|
|
1344
3525
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
1345
3526
|
});
|
|
1346
|
-
|
|
3527
|
+
const deliveries = await Promise.all(jobs);
|
|
3528
|
+
if (!options.invalid) {
|
|
3529
|
+
for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
|
|
3530
|
+
}
|
|
3531
|
+
return deliveries;
|
|
1347
3532
|
}
|
|
1348
3533
|
async deliver(url, webhookId, body, event, copy) {
|
|
1349
3534
|
const delivery = {
|
|
@@ -1421,6 +3606,13 @@ var WebhookDispatcher = class {
|
|
|
1421
3606
|
);
|
|
1422
3607
|
}
|
|
1423
3608
|
}
|
|
3609
|
+
emit(type, data, source = "api") {
|
|
3610
|
+
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
3611
|
+
void this.send({ type, data, source }).catch(() => void 0);
|
|
3612
|
+
}
|
|
3613
|
+
userEventData(user) {
|
|
3614
|
+
return this.userPayload(user);
|
|
3615
|
+
}
|
|
1424
3616
|
emitForUser(type, user) {
|
|
1425
3617
|
if (!this.endpoints.some((e) => e.events === null || e.events.includes(type))) return;
|
|
1426
3618
|
const data = type === "user.created" ? { user: this.userPayload(user) } : { user: { id: user.id } };
|
|
@@ -1485,7 +3677,511 @@ function isHttpUrl2(value) {
|
|
|
1485
3677
|
}
|
|
1486
3678
|
}
|
|
1487
3679
|
function sleep(ms) {
|
|
1488
|
-
return new Promise((
|
|
3680
|
+
return new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
3681
|
+
}
|
|
3682
|
+
|
|
3683
|
+
// src/activity.ts
|
|
3684
|
+
var LIMIT = 200;
|
|
3685
|
+
var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
|
|
3686
|
+
var ActivityLog = class {
|
|
3687
|
+
requestLog = [];
|
|
3688
|
+
tokenLog = [];
|
|
3689
|
+
request(entry) {
|
|
3690
|
+
const query = new URLSearchParams(entry.query);
|
|
3691
|
+
for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
|
|
3692
|
+
const search = query.toString();
|
|
3693
|
+
push(this.requestLog, {
|
|
3694
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3695
|
+
method: entry.method,
|
|
3696
|
+
path: search ? `${entry.path}?${search}` : entry.path,
|
|
3697
|
+
status: entry.status,
|
|
3698
|
+
durationMs: entry.durationMs,
|
|
3699
|
+
injected: entry.injected
|
|
3700
|
+
});
|
|
3701
|
+
}
|
|
3702
|
+
token(kind, claims, invalid3, token) {
|
|
3703
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
3704
|
+
push(this.tokenLog, {
|
|
3705
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3706
|
+
kind,
|
|
3707
|
+
subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
|
|
3708
|
+
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
3709
|
+
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
3710
|
+
roles,
|
|
3711
|
+
invalid: invalid3 ?? null,
|
|
3712
|
+
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
3713
|
+
claims,
|
|
3714
|
+
token
|
|
3715
|
+
});
|
|
3716
|
+
}
|
|
3717
|
+
requests() {
|
|
3718
|
+
return [...this.requestLog];
|
|
3719
|
+
}
|
|
3720
|
+
tokens() {
|
|
3721
|
+
return [...this.tokenLog];
|
|
3722
|
+
}
|
|
3723
|
+
reset() {
|
|
3724
|
+
this.requestLog = [];
|
|
3725
|
+
this.tokenLog = [];
|
|
3726
|
+
}
|
|
3727
|
+
};
|
|
3728
|
+
function push(list, entry) {
|
|
3729
|
+
list.push(entry);
|
|
3730
|
+
if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
|
|
3731
|
+
}
|
|
3732
|
+
|
|
3733
|
+
// src/coverage.ts
|
|
3734
|
+
var import_node_fs2 = require("fs");
|
|
3735
|
+
var import_node_path2 = require("path");
|
|
3736
|
+
var COVERAGE_GROUPS = [
|
|
3737
|
+
{
|
|
3738
|
+
name: "Identity",
|
|
3739
|
+
items: [
|
|
3740
|
+
{ id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
|
|
3741
|
+
{ id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
|
|
3742
|
+
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
3743
|
+
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
3744
|
+
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
3745
|
+
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
|
|
3746
|
+
]
|
|
3747
|
+
},
|
|
3748
|
+
{
|
|
3749
|
+
name: "Organizations",
|
|
3750
|
+
items: [
|
|
3751
|
+
{ id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
|
|
3752
|
+
{ id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
|
|
3753
|
+
{ id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
|
|
3754
|
+
{ id: "organization.non-member", label: "Non-member refused", hint: "Ask for a token or sign-in for an organization the user does not belong to." },
|
|
3755
|
+
{ id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
|
|
3756
|
+
]
|
|
3757
|
+
},
|
|
3758
|
+
{
|
|
3759
|
+
name: "Permissions",
|
|
3760
|
+
items: [
|
|
3761
|
+
{ id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
|
|
3762
|
+
{ id: "permission.different-sets", label: "Different permissions in one organization", hint: "Mint tokens for two users in one organization with different permissions, such as an admin and a viewer." },
|
|
3763
|
+
{ id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
|
|
3764
|
+
{ id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
|
|
3765
|
+
{ id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
|
|
3766
|
+
]
|
|
3767
|
+
},
|
|
3768
|
+
{
|
|
3769
|
+
name: "Token validation",
|
|
3770
|
+
items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
|
|
3771
|
+
(kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
|
|
3772
|
+
)
|
|
3773
|
+
},
|
|
3774
|
+
{
|
|
3775
|
+
name: "Sessions",
|
|
3776
|
+
items: [
|
|
3777
|
+
{ id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
|
|
3778
|
+
{ id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
|
|
3779
|
+
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
3780
|
+
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
3781
|
+
{ id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
|
|
3782
|
+
]
|
|
3783
|
+
},
|
|
3784
|
+
{
|
|
3785
|
+
name: "Machine-to-machine",
|
|
3786
|
+
items: [
|
|
3787
|
+
{ id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
|
|
3788
|
+
{ id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
|
|
3789
|
+
{ id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
|
|
3790
|
+
{ id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
|
|
3791
|
+
]
|
|
3792
|
+
},
|
|
3793
|
+
{
|
|
3794
|
+
name: "Kinde APIs",
|
|
3795
|
+
items: [
|
|
3796
|
+
{ id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
|
|
3797
|
+
{ id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
|
|
3798
|
+
{ id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
|
|
3799
|
+
{ id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
|
|
3800
|
+
]
|
|
3801
|
+
},
|
|
3802
|
+
{
|
|
3803
|
+
name: "Webhooks",
|
|
3804
|
+
items: [
|
|
3805
|
+
{ id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
|
|
3806
|
+
{ id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
|
|
3807
|
+
{ id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
|
|
3808
|
+
{ id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
|
|
3809
|
+
{ id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
|
|
3810
|
+
]
|
|
3811
|
+
},
|
|
3812
|
+
{
|
|
3813
|
+
name: "Outages",
|
|
3814
|
+
items: [
|
|
3815
|
+
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
3816
|
+
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
3817
|
+
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
3818
|
+
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
|
|
3819
|
+
]
|
|
3820
|
+
}
|
|
3821
|
+
];
|
|
3822
|
+
var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
|
|
3823
|
+
function tokenLabel(kind) {
|
|
3824
|
+
return {
|
|
3825
|
+
expired: "Expired token",
|
|
3826
|
+
"future-iat": "Token issued in the future",
|
|
3827
|
+
"wrong-issuer": "Wrong issuer",
|
|
3828
|
+
"wrong-audience": "Wrong audience",
|
|
3829
|
+
"bad-signature": "Tampered signature",
|
|
3830
|
+
"unknown-key": "Unknown signing key",
|
|
3831
|
+
unsigned: "Unsigned token",
|
|
3832
|
+
"missing-subject": "No subject"
|
|
3833
|
+
}[kind];
|
|
3834
|
+
}
|
|
3835
|
+
var CoverageRecorder = class {
|
|
3836
|
+
hits = /* @__PURE__ */ new Map();
|
|
3837
|
+
userOrganizations = /* @__PURE__ */ new Map();
|
|
3838
|
+
organizationUsers = /* @__PURE__ */ new Map();
|
|
3839
|
+
organizationPermissionSets = /* @__PURE__ */ new Map();
|
|
3840
|
+
hit(id) {
|
|
3841
|
+
if (!ALL_IDS.has(id)) return;
|
|
3842
|
+
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
3843
|
+
}
|
|
3844
|
+
/** Called for every access token the testkit signs. */
|
|
3845
|
+
observeAccessToken(payload, invalid3) {
|
|
3846
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
3847
|
+
this.hit("m2m.token");
|
|
3848
|
+
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
3849
|
+
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
3850
|
+
if (invalid3) this.hit("m2m.invalid");
|
|
3851
|
+
return;
|
|
3852
|
+
}
|
|
3853
|
+
if (invalid3 === "missing-organization") return this.hit("organization.missing");
|
|
3854
|
+
if (invalid3 === "missing-permissions") return this.hit("permission.none");
|
|
3855
|
+
if (invalid3) return this.hit(`token.${invalid3}`);
|
|
3856
|
+
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
3857
|
+
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
3858
|
+
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
3859
|
+
if (subject) this.hit("identity.user");
|
|
3860
|
+
if (!organization) this.hit("identity.no-organization");
|
|
3861
|
+
if (permissions.length > 0) this.hit("permission.granted");
|
|
3862
|
+
else this.hit("permission.none");
|
|
3863
|
+
if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
|
|
3864
|
+
if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
|
|
3865
|
+
if (!organization) return;
|
|
3866
|
+
this.hit("organization.token");
|
|
3867
|
+
if (subject) {
|
|
3868
|
+
const organizations = add(this.userOrganizations, subject, organization);
|
|
3869
|
+
if (organizations.size > 1) this.hit("organization.two-for-one-user");
|
|
3870
|
+
add(this.organizationUsers, organization, subject);
|
|
3871
|
+
const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
|
|
3872
|
+
const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
|
|
3873
|
+
if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
|
|
3874
|
+
}
|
|
3875
|
+
const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
|
|
3876
|
+
if (sets.size > 1) this.hit("permission.different-sets");
|
|
3877
|
+
}
|
|
3878
|
+
report() {
|
|
3879
|
+
return buildReport(Object.fromEntries(this.hits));
|
|
3880
|
+
}
|
|
3881
|
+
snapshot() {
|
|
3882
|
+
return { version: 1, hits: Object.fromEntries(this.hits) };
|
|
3883
|
+
}
|
|
3884
|
+
reset() {
|
|
3885
|
+
this.hits.clear();
|
|
3886
|
+
this.userOrganizations.clear();
|
|
3887
|
+
this.organizationUsers.clear();
|
|
3888
|
+
this.organizationPermissionSets.clear();
|
|
3889
|
+
}
|
|
3890
|
+
/** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
|
|
3891
|
+
write(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
3892
|
+
const folder = (0, import_node_path2.resolve)(directory);
|
|
3893
|
+
(0, import_node_fs2.mkdirSync)(folder, { recursive: true });
|
|
3894
|
+
const file = (0, import_node_path2.join)(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
|
|
3895
|
+
(0, import_node_fs2.writeFileSync)(file, `${JSON.stringify(this.snapshot())}
|
|
3896
|
+
`);
|
|
3897
|
+
return file;
|
|
3898
|
+
}
|
|
3899
|
+
};
|
|
3900
|
+
var DEFAULT_COVERAGE_DIRECTORY = (0, import_node_path2.join)(".kinde-testkit", "coverage");
|
|
3901
|
+
function add(map, key, value) {
|
|
3902
|
+
let set2 = map.get(key);
|
|
3903
|
+
if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
|
|
3904
|
+
set2.add(value);
|
|
3905
|
+
return set2;
|
|
3906
|
+
}
|
|
3907
|
+
function buildReport(hits) {
|
|
3908
|
+
const groups = COVERAGE_GROUPS.map((group) => {
|
|
3909
|
+
const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
|
|
3910
|
+
return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
|
|
3911
|
+
});
|
|
3912
|
+
return {
|
|
3913
|
+
covered: groups.reduce((sum, g) => sum + g.covered, 0),
|
|
3914
|
+
total: groups.reduce((sum, g) => sum + g.total, 0),
|
|
3915
|
+
groups
|
|
3916
|
+
};
|
|
3917
|
+
}
|
|
3918
|
+
function mergeSnapshots(snapshots) {
|
|
3919
|
+
const hits = {};
|
|
3920
|
+
for (const snapshot of snapshots) {
|
|
3921
|
+
for (const [id, count] of Object.entries(snapshot.hits ?? {})) hits[id] = (hits[id] ?? 0) + count;
|
|
3922
|
+
}
|
|
3923
|
+
return hits;
|
|
3924
|
+
}
|
|
3925
|
+
function readCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
3926
|
+
const folder = (0, import_node_path2.resolve)(directory);
|
|
3927
|
+
let names = [];
|
|
3928
|
+
try {
|
|
3929
|
+
names = (0, import_node_fs2.readdirSync)(folder).filter((name) => name.endsWith(".json"));
|
|
3930
|
+
} catch {
|
|
3931
|
+
}
|
|
3932
|
+
const snapshots = names.map((name) => JSON.parse((0, import_node_fs2.readFileSync)((0, import_node_path2.join)(folder, name), "utf8")));
|
|
3933
|
+
return { files: names.length, report: buildReport(mergeSnapshots(snapshots)) };
|
|
3934
|
+
}
|
|
3935
|
+
function clearCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
3936
|
+
(0, import_node_fs2.rmSync)((0, import_node_path2.resolve)(directory), { recursive: true, force: true });
|
|
3937
|
+
}
|
|
3938
|
+
function formatCoverageReport(report, options = {}) {
|
|
3939
|
+
const width = Math.max(...report.groups.map((g) => g.name.length)) + 3;
|
|
3940
|
+
const lines = ["Kinde authentication coverage", ""];
|
|
3941
|
+
for (const group of report.groups) {
|
|
3942
|
+
lines.push(`${group.name.padEnd(width)}${String(group.covered).padStart(2)}/${group.total}`);
|
|
3943
|
+
}
|
|
3944
|
+
lines.push("", `Overall: ${report.covered}/${report.total}`);
|
|
3945
|
+
if (options.missing !== false) {
|
|
3946
|
+
const missing = report.groups.flatMap((g) => g.items.filter((i) => !i.covered).map((i) => ({ group: g.name, ...i })));
|
|
3947
|
+
if (missing.length > 0) {
|
|
3948
|
+
lines.push("", "Not covered:");
|
|
3949
|
+
for (const item of missing) lines.push(` ${item.group}: ${item.label}. ${item.hint}`);
|
|
3950
|
+
}
|
|
3951
|
+
}
|
|
3952
|
+
return lines.join("\n");
|
|
3953
|
+
}
|
|
3954
|
+
|
|
3955
|
+
// src/dashboard.ts
|
|
3956
|
+
var STYLE2 = `
|
|
3957
|
+
:root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--ok:#1d7a46;--bad:#b42318;--soft:#f0f0ec}
|
|
3958
|
+
@media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--ok:#5cc78a;--bad:#f0817a;--soft:#232327}}
|
|
3959
|
+
*{box-sizing:border-box}
|
|
3960
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
3961
|
+
header{position:sticky;top:0;z-index:1;display:flex;flex-wrap:wrap;gap:16px;align-items:center;justify-content:space-between;padding:14px 28px;background:var(--card);border-bottom:1px solid var(--line)}
|
|
3962
|
+
header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
|
|
3963
|
+
header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
3964
|
+
nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
|
|
3965
|
+
nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
|
|
3966
|
+
main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
|
|
3967
|
+
section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
|
|
3968
|
+
h2{margin:0 0 4px;font-size:16px;font-weight:600}
|
|
3969
|
+
.sub{margin:0 0 14px;color:var(--muted);font-size:13px}
|
|
3970
|
+
table{width:100%;border-collapse:collapse;font-size:13px}
|
|
3971
|
+
th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
|
|
3972
|
+
td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
|
|
3973
|
+
tr:last-child td{border-bottom:0}
|
|
3974
|
+
code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
3975
|
+
.chips{display:flex;flex-wrap:wrap;gap:4px}
|
|
3976
|
+
.chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
|
|
3977
|
+
.ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
|
|
3978
|
+
.empty{color:var(--muted);font-size:13px;margin:0}
|
|
3979
|
+
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
|
|
3980
|
+
label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
|
|
3981
|
+
input,select{height:32px;padding:0 8px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:13px ui-sans-serif,system-ui,sans-serif}
|
|
3982
|
+
input[type=checkbox]{height:auto}
|
|
3983
|
+
button{height:32px;padding:0 12px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--ink);font:500 13px ui-sans-serif,system-ui,sans-serif;cursor:pointer}
|
|
3984
|
+
button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
|
|
3985
|
+
button:hover{border-color:var(--muted)}
|
|
3986
|
+
details summary{cursor:pointer;color:var(--muted)}
|
|
3987
|
+
pre{margin:8px 0 0;padding:10px;background:var(--soft);border-radius:6px;overflow:auto;max-height:320px;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-all}
|
|
3988
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
|
|
3989
|
+
.group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
|
|
3990
|
+
.group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
|
|
3991
|
+
.notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
|
|
3992
|
+
.split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
|
|
3993
|
+
`;
|
|
3994
|
+
function renderDashboard(data) {
|
|
3995
|
+
const e = escapeHtml;
|
|
3996
|
+
const { seed } = data;
|
|
3997
|
+
const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
|
|
3998
|
+
const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
|
|
3999
|
+
const users = seed.users.length ? table2(
|
|
4000
|
+
["User", "ID", "Organizations", "Sign-ins", "Status"],
|
|
4001
|
+
seed.users.map((user) => [
|
|
4002
|
+
e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
|
|
4003
|
+
`<code>${e(user.id)}</code>`,
|
|
4004
|
+
chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
|
|
4005
|
+
String(data.signIns(user.id)),
|
|
4006
|
+
data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
|
|
4007
|
+
])
|
|
4008
|
+
) : empty("No users yet. Seed some, or sign in with any email.");
|
|
4009
|
+
const organizations = seed.organizations.length ? table2(
|
|
4010
|
+
["Organization", "Code", "Members"],
|
|
4011
|
+
seed.organizations.map((org) => [
|
|
4012
|
+
e(org.name),
|
|
4013
|
+
`<code>${e(org.code)}</code>`,
|
|
4014
|
+
String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
|
|
4015
|
+
])
|
|
4016
|
+
) : empty("No organizations.");
|
|
4017
|
+
const memberships = seed.memberships.length ? table2(
|
|
4018
|
+
["User", "Organization", "Roles", "Permissions in the token"],
|
|
4019
|
+
seed.memberships.map((m) => [
|
|
4020
|
+
e(userLabel(m.userId)),
|
|
4021
|
+
e(orgName(m.organizationCode)),
|
|
4022
|
+
chips(m.roles),
|
|
4023
|
+
chips(effectivePermissions(seed, m))
|
|
4024
|
+
])
|
|
4025
|
+
) : empty("No memberships.");
|
|
4026
|
+
const applications = seed.applications.length ? table2(
|
|
4027
|
+
["Client ID", "Organization", "Scopes"],
|
|
4028
|
+
seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
|
|
4029
|
+
) : "";
|
|
4030
|
+
const tokens = data.tokens.length ? table2(
|
|
4031
|
+
["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
|
|
4032
|
+
[...data.tokens].reverse().slice(0, 50).map((t) => [
|
|
4033
|
+
time(t.at),
|
|
4034
|
+
t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
|
|
4035
|
+
`<code>${e(t.subject ?? "none")}</code>`,
|
|
4036
|
+
e(t.organization ?? "none"),
|
|
4037
|
+
chips(t.permissions),
|
|
4038
|
+
`<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
|
|
4039
|
+
])
|
|
4040
|
+
) : empty("No tokens issued yet.");
|
|
4041
|
+
const requests = data.requests.length ? table2(
|
|
4042
|
+
["Time", "Request", "Status", "Time taken"],
|
|
4043
|
+
[...data.requests].reverse().slice(0, 100).map((r) => [
|
|
4044
|
+
time(r.at),
|
|
4045
|
+
`<code>${e(r.method)} ${e(r.path)}</code>`,
|
|
4046
|
+
`<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
|
|
4047
|
+
`${r.durationMs} ms`
|
|
4048
|
+
])
|
|
4049
|
+
) : empty("No requests yet.");
|
|
4050
|
+
const deliveries = data.deliveries.length ? table2(
|
|
4051
|
+
["Event", "Endpoint", "Copy", "Result"],
|
|
4052
|
+
[...data.deliveries].reverse().slice(0, 50).map((d) => [
|
|
4053
|
+
`<code>${e(d.type)}</code>`,
|
|
4054
|
+
`<code>${e(d.url)}</code>`,
|
|
4055
|
+
String(d.copy),
|
|
4056
|
+
d.delivered ? `<span class="ok">Delivered</span>` : `<span class="bad">${e(d.attempts.map((a) => a.status === null ? a.error ?? "error" : String(a.status)).join(", ") || "Not sent")}</span>`
|
|
4057
|
+
])
|
|
4058
|
+
) : empty("No webhooks sent yet.");
|
|
4059
|
+
const endpoints = data.endpoints.length ? `<p class="sub">Endpoints: ${data.endpoints.map((x) => `<code>${e(x.url)}</code>`).join(", ")}</p>` : `<p class="sub">No webhook endpoints. Add one in the seed, with <code>start --webhook</code> or <code>addEndpoint()</code>.</p>`;
|
|
4060
|
+
const webhookForm = data.endpoints.length ? form(
|
|
4061
|
+
"/dashboard/webhooks",
|
|
4062
|
+
`<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
|
|
4063
|
+
<label>User<select name="user"><option value="">First seeded user</option>${seed.users.map((u) => `<option value="${e(u.id)}">${e(u.email ?? u.id)}</option>`).join("")}</select></label>
|
|
4064
|
+
<label>Variant<select name="invalid"><option value="">Valid</option><option>bad-signature</option><option>unknown-key</option><option>unsigned</option><option>stale</option></select></label>
|
|
4065
|
+
<label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
|
|
4066
|
+
<button class="primary">Send</button>`
|
|
4067
|
+
) : "";
|
|
4068
|
+
const failures = data.failures.length ? table2(
|
|
4069
|
+
["Path", "Method", "Effect", "Remaining", "Hits", ""],
|
|
4070
|
+
data.failures.map((f) => [
|
|
4071
|
+
`<code>${e(f.path)}</code>`,
|
|
4072
|
+
e(f.method ?? "any"),
|
|
4073
|
+
e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
|
|
4074
|
+
f.remaining === null ? "Until removed" : String(f.remaining),
|
|
4075
|
+
String(f.hits),
|
|
4076
|
+
form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
|
|
4077
|
+
])
|
|
4078
|
+
) : empty("No failure rules.");
|
|
4079
|
+
const coverage = `<div class="grid">${data.coverage.groups.map(
|
|
4080
|
+
(g) => `<div><div class="group"><span>${e(g.name)}</span><span class="${g.covered === g.total ? "ok" : "muted"}">${g.covered}/${g.total}</span></div><ul>${g.items.map((i) => `<li title="${e(i.hint)}"><span class="${i.covered ? "ok" : "muted"}">${i.covered ? "\u2713" : "\u25CB"}</span> ${e(i.label)}</li>`).join("")}</ul></div>`
|
|
4081
|
+
).join("")}</div>`;
|
|
4082
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4083
|
+
${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
|
|
4084
|
+
<title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
|
|
4085
|
+
<header>
|
|
4086
|
+
<div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
|
|
4087
|
+
<nav><a href="#users">Users</a><a href="#tokens">Tokens</a><a href="#requests">Requests</a><a href="#webhooks">Webhooks</a><a href="#failures">Failures</a><a href="#coverage">Coverage</a></nav>
|
|
4088
|
+
<div class="row">
|
|
4089
|
+
<a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
|
|
4090
|
+
${form("/dashboard/reset", `<button>Reset state</button>`)}
|
|
4091
|
+
</div>
|
|
4092
|
+
</header>
|
|
4093
|
+
<main>
|
|
4094
|
+
${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
|
|
4095
|
+
<section id="users"><h2>Users</h2><p class="sub">Seeded users, users created through the Management API, and emails that signed in.</p>${users}</section>
|
|
4096
|
+
<div class="split">
|
|
4097
|
+
<section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
|
|
4098
|
+
<section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
|
|
4099
|
+
</div>
|
|
4100
|
+
${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
|
|
4101
|
+
<section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
|
|
4102
|
+
<section id="requests"><h2>Requests</h2><p class="sub">The latest 100 requests your app and tests made. Codes, secrets and refresh tokens are hidden.</p>${requests}</section>
|
|
4103
|
+
<section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
|
|
4104
|
+
<section id="failures"><h2>Failures</h2><p class="sub">Make an endpoint fail, slow down or hang. Applies to Kinde endpoints, not <code>/testkit</code> or this page.</p>
|
|
4105
|
+
${form(
|
|
4106
|
+
"/dashboard/failures",
|
|
4107
|
+
`<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
|
|
4108
|
+
<label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
|
|
4109
|
+
<label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
|
|
4110
|
+
<label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
|
|
4111
|
+
<label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
|
|
4112
|
+
<label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
|
|
4113
|
+
<button class="primary">Add rule</button>`
|
|
4114
|
+
)}
|
|
4115
|
+
<div style="margin-top:14px">${failures}</div>
|
|
4116
|
+
${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
|
|
4117
|
+
</section>
|
|
4118
|
+
<section id="coverage"><h2>Coverage: ${data.coverage.covered}/${data.coverage.total}</h2><p class="sub">Authentication scenarios the testkit produced since it started or was reset. Hover an item to see how to cover it.</p>${coverage}
|
|
4119
|
+
<div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
|
|
4120
|
+
</main></body></html>`;
|
|
4121
|
+
}
|
|
4122
|
+
function table2(headers, rows) {
|
|
4123
|
+
return `<table><thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
|
|
4124
|
+
}
|
|
4125
|
+
function chips(values) {
|
|
4126
|
+
if (values.length === 0) return `<span class="muted">none</span>`;
|
|
4127
|
+
return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
|
|
4128
|
+
}
|
|
4129
|
+
function empty(text) {
|
|
4130
|
+
return `<p class="empty">${escapeHtml(text)}</p>`;
|
|
4131
|
+
}
|
|
4132
|
+
function time(iso) {
|
|
4133
|
+
return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
|
|
4134
|
+
}
|
|
4135
|
+
function form(action, body) {
|
|
4136
|
+
return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
|
|
4137
|
+
}
|
|
4138
|
+
|
|
4139
|
+
// src/seed-file.ts
|
|
4140
|
+
var import_node_fs3 = require("fs");
|
|
4141
|
+
var import_node_path3 = require("path");
|
|
4142
|
+
var import_node_url = require("url");
|
|
4143
|
+
var import_yaml = require("yaml");
|
|
4144
|
+
var DEFAULT_SEED_FILES = [
|
|
4145
|
+
"kinde-testkit.json",
|
|
4146
|
+
"kinde-testkit.yaml",
|
|
4147
|
+
"kinde-testkit.yml",
|
|
4148
|
+
"kinde-testkit.ts",
|
|
4149
|
+
"kinde-testkit.mts",
|
|
4150
|
+
"kinde-testkit.js",
|
|
4151
|
+
"kinde-testkit.mjs"
|
|
4152
|
+
];
|
|
4153
|
+
function findSeedFile(directory = ".") {
|
|
4154
|
+
return DEFAULT_SEED_FILES.map((name) => (0, import_node_path3.resolve)(directory, name)).find((path) => (0, import_node_fs3.existsSync)(path));
|
|
4155
|
+
}
|
|
4156
|
+
async function loadSeedFile(path) {
|
|
4157
|
+
const file = (0, import_node_path3.resolve)(path);
|
|
4158
|
+
const extension = (0, import_node_path3.extname)(file).toLowerCase();
|
|
4159
|
+
let value;
|
|
4160
|
+
try {
|
|
4161
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
4162
|
+
value = (0, import_yaml.parse)((0, import_node_fs3.readFileSync)(file, "utf8"));
|
|
4163
|
+
} else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
|
|
4164
|
+
const module2 = await import((0, import_node_url.pathToFileURL)(file).href);
|
|
4165
|
+
value = module2.seed ?? module2.default;
|
|
4166
|
+
if (value && typeof value === "object" && "default" in value && !("users" in value)) {
|
|
4167
|
+
value = value.default;
|
|
4168
|
+
}
|
|
4169
|
+
} else {
|
|
4170
|
+
value = JSON.parse((0, import_node_fs3.readFileSync)(file, "utf8"));
|
|
4171
|
+
}
|
|
4172
|
+
} catch (error) {
|
|
4173
|
+
const message2 = error instanceof Error ? error.message : String(error);
|
|
4174
|
+
const details = [message2];
|
|
4175
|
+
if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message2)) {
|
|
4176
|
+
details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
|
|
4177
|
+
}
|
|
4178
|
+
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
|
|
4179
|
+
}
|
|
4180
|
+
if (value === null || value === void 0) value = {};
|
|
4181
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
4182
|
+
throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
|
|
4183
|
+
}
|
|
4184
|
+
return value;
|
|
1489
4185
|
}
|
|
1490
4186
|
|
|
1491
4187
|
// src/server.ts
|
|
@@ -1500,33 +4196,74 @@ async function startKindeTestkit(options = {}) {
|
|
|
1500
4196
|
`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).`
|
|
1501
4197
|
);
|
|
1502
4198
|
}
|
|
1503
|
-
const
|
|
4199
|
+
const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
|
|
4200
|
+
const seed = resolveSeed(seedInput);
|
|
1504
4201
|
const failures = new FailureInjector();
|
|
1505
4202
|
let ready;
|
|
1506
|
-
const testkitReady = new Promise((
|
|
1507
|
-
const
|
|
4203
|
+
const testkitReady = new Promise((resolve4) => ready = resolve4);
|
|
4204
|
+
const listener = (req, res) => {
|
|
1508
4205
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
1509
|
-
}
|
|
1510
|
-
|
|
4206
|
+
};
|
|
4207
|
+
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
4208
|
+
const server = certificate ? (0, import_node_https.createServer)({ cert: certificate.cert, key: certificate.key }, listener) : (0, import_node_http.createServer)(listener);
|
|
4209
|
+
await new Promise((resolve4, reject) => {
|
|
1511
4210
|
server.once("error", reject);
|
|
1512
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
4211
|
+
server.listen(options.port ?? 4400, host, () => resolve4());
|
|
1513
4212
|
});
|
|
1514
4213
|
const { port } = server.address();
|
|
1515
|
-
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
1516
|
-
const url =
|
|
4214
|
+
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
4215
|
+
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
1517
4216
|
const testkit = await KindeTestkit.create({
|
|
1518
|
-
issuer: options.issuer ??
|
|
1519
|
-
audience: options.audience ??
|
|
1520
|
-
clientId: options.clientId ??
|
|
4217
|
+
issuer: options.issuer ?? seedInput.issuer ?? url,
|
|
4218
|
+
audience: options.audience ?? seedInput.audience,
|
|
4219
|
+
clientId: options.clientId ?? seedInput.clientId
|
|
4220
|
+
});
|
|
4221
|
+
const coverage = new CoverageRecorder();
|
|
4222
|
+
const activity = new ActivityLog();
|
|
4223
|
+
testkit.observe({
|
|
4224
|
+
accessToken(payload, invalid3, token) {
|
|
4225
|
+
coverage.observeAccessToken(payload, invalid3);
|
|
4226
|
+
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
4227
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid3, token);
|
|
4228
|
+
},
|
|
4229
|
+
idToken(payload, token) {
|
|
4230
|
+
coverage.hit("identity.id-token");
|
|
4231
|
+
activity.token("id", payload, void 0, token);
|
|
4232
|
+
},
|
|
4233
|
+
anonymous() {
|
|
4234
|
+
coverage.hit("identity.anonymous");
|
|
4235
|
+
}
|
|
1521
4236
|
});
|
|
4237
|
+
const observe = (id) => coverage.hit(id);
|
|
4238
|
+
const directory = new Directory(seed);
|
|
1522
4239
|
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
1523
|
-
|
|
4240
|
+
webhooks.observe = observe;
|
|
4241
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
|
|
4242
|
+
const management = new ManagementApi(testkit, directory, webhooks);
|
|
4243
|
+
const account = new AccountApi(testkit, directory);
|
|
1524
4244
|
const reset = () => {
|
|
1525
4245
|
auth.reset();
|
|
1526
4246
|
failures.clear();
|
|
1527
4247
|
webhooks.reset();
|
|
4248
|
+
directory.restore();
|
|
4249
|
+
};
|
|
4250
|
+
const loadSeed = (input) => {
|
|
4251
|
+
const next = resolveSeed(input);
|
|
4252
|
+
directory.load(next);
|
|
4253
|
+
webhooks.replaceSeededEndpoints(next.webhooks);
|
|
4254
|
+
reset();
|
|
1528
4255
|
};
|
|
1529
|
-
|
|
4256
|
+
let closed = false;
|
|
4257
|
+
const close = () => new Promise((resolve4, reject) => {
|
|
4258
|
+
if (closed) return resolve4();
|
|
4259
|
+
closed = true;
|
|
4260
|
+
if (options.coverage) {
|
|
4261
|
+
coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
|
|
4262
|
+
}
|
|
4263
|
+
server.closeAllConnections();
|
|
4264
|
+
server.close((error) => error ? reject(error) : resolve4());
|
|
4265
|
+
});
|
|
4266
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
|
|
1530
4267
|
return {
|
|
1531
4268
|
url,
|
|
1532
4269
|
issuer: testkit.issuer,
|
|
@@ -1536,84 +4273,224 @@ async function startKindeTestkit(options = {}) {
|
|
|
1536
4273
|
seed,
|
|
1537
4274
|
failures,
|
|
1538
4275
|
webhooks,
|
|
4276
|
+
directory,
|
|
4277
|
+
certificatePath: certificate?.certPath ?? null,
|
|
4278
|
+
coverage,
|
|
4279
|
+
activity,
|
|
4280
|
+
loadSeed,
|
|
1539
4281
|
reset,
|
|
1540
|
-
close
|
|
1541
|
-
server.closeAllConnections();
|
|
1542
|
-
server.close((error) => error ? reject(error) : resolve());
|
|
1543
|
-
})
|
|
4282
|
+
close
|
|
1544
4283
|
};
|
|
1545
4284
|
}
|
|
1546
4285
|
async function handle(req, res, context) {
|
|
1547
|
-
const { testkit, auth, seed, failures, webhooks } = context;
|
|
4286
|
+
const { testkit, auth, seed, failures, webhooks, coverage } = context;
|
|
1548
4287
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1549
4288
|
const { pathname } = url;
|
|
1550
4289
|
const method = req.method ?? "GET";
|
|
1551
|
-
|
|
4290
|
+
const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
|
|
4291
|
+
let injected = false;
|
|
4292
|
+
if (!internal && pathname !== "/favicon.ico") {
|
|
4293
|
+
const started = Date.now();
|
|
4294
|
+
res.once("close", () => {
|
|
4295
|
+
context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
|
|
4296
|
+
});
|
|
4297
|
+
}
|
|
4298
|
+
if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
|
|
4299
|
+
if (!internal) {
|
|
1552
4300
|
const failure = failures.take(method, pathname);
|
|
1553
4301
|
if (failure) {
|
|
4302
|
+
injected = true;
|
|
4303
|
+
if (failure.hang) coverage.hit("outage.timeout");
|
|
4304
|
+
else if (failure.status === 429) coverage.hit("outage.rate-limit");
|
|
4305
|
+
else if (failure.status !== null) coverage.hit("outage.error");
|
|
4306
|
+
if (failure.delayMs > 0) coverage.hit("outage.slow");
|
|
1554
4307
|
if (failure.hang) return;
|
|
1555
|
-
if (failure.delayMs > 0) await new Promise((
|
|
4308
|
+
if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
|
|
1556
4309
|
if (failure.status !== null) {
|
|
1557
4310
|
const headers = {};
|
|
1558
4311
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
1559
|
-
return
|
|
4312
|
+
return sendJson4(res, failure.status, failureBody(failure.status), headers);
|
|
1560
4313
|
}
|
|
1561
4314
|
}
|
|
1562
4315
|
}
|
|
1563
4316
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
4317
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) {
|
|
4318
|
+
if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
|
|
4319
|
+
else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
|
|
4320
|
+
return;
|
|
4321
|
+
}
|
|
4322
|
+
if (await context.account.handle(req, res, url)) {
|
|
4323
|
+
if (res.statusCode < 400) coverage.hit("api.account");
|
|
4324
|
+
return;
|
|
4325
|
+
}
|
|
4326
|
+
if (method === "GET" && pathname === "/testkit/portal") {
|
|
4327
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
4328
|
+
res.end(
|
|
4329
|
+
`<!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>`
|
|
4330
|
+
);
|
|
4331
|
+
return;
|
|
4332
|
+
}
|
|
1564
4333
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
1565
|
-
return
|
|
4334
|
+
return sendJson4(res, 200, discovery(testkit));
|
|
1566
4335
|
}
|
|
1567
4336
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
1568
|
-
return
|
|
4337
|
+
return sendJson4(res, 200, testkit.jwks());
|
|
1569
4338
|
}
|
|
1570
4339
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
1571
|
-
return
|
|
4340
|
+
return sendJson4(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
1572
4341
|
}
|
|
1573
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
4342
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson4(res, 200, seed.users);
|
|
1574
4343
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
1575
|
-
return
|
|
4344
|
+
return sendJson4(res, 200, seed.organizations);
|
|
1576
4345
|
}
|
|
1577
4346
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
1578
|
-
return
|
|
4347
|
+
return sendJson4(res, 200, seed.memberships);
|
|
1579
4348
|
}
|
|
1580
|
-
if (method === "GET" && pathname === "/testkit/failures") return
|
|
4349
|
+
if (method === "GET" && pathname === "/testkit/failures") return sendJson4(res, 200, failures.list());
|
|
1581
4350
|
if (method === "POST" && pathname === "/testkit/failures") {
|
|
1582
|
-
return
|
|
4351
|
+
return sendJson4(res, 201, failures.add(await readJson(req)));
|
|
1583
4352
|
}
|
|
1584
4353
|
if (method === "DELETE" && pathname === "/testkit/failures") {
|
|
1585
4354
|
failures.clear();
|
|
1586
|
-
return
|
|
4355
|
+
return sendJson4(res, 200, { ok: true });
|
|
1587
4356
|
}
|
|
1588
4357
|
if (method === "DELETE" && pathname.startsWith("/testkit/failures/")) {
|
|
1589
4358
|
const removed = failures.remove(decodeURIComponent(pathname.slice("/testkit/failures/".length)));
|
|
1590
|
-
return
|
|
4359
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1591
4360
|
}
|
|
1592
4361
|
if (method === "POST" && pathname === "/testkit/webhooks") {
|
|
1593
|
-
return
|
|
4362
|
+
return sendJson4(res, 200, await webhooks.send(await readJson(req)));
|
|
1594
4363
|
}
|
|
1595
4364
|
if (method === "GET" && pathname === "/testkit/webhooks/types") {
|
|
1596
|
-
return
|
|
4365
|
+
return sendJson4(res, 200, { built_in: WEBHOOK_EVENT_TYPES, billing: BILLING_EVENT_TYPES });
|
|
1597
4366
|
}
|
|
1598
|
-
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return
|
|
1599
|
-
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return
|
|
4367
|
+
if (method === "GET" && pathname === "/testkit/webhooks/deliveries") return sendJson4(res, 200, webhooks.deliveries());
|
|
4368
|
+
if (method === "GET" && pathname === "/testkit/webhooks/endpoints") return sendJson4(res, 200, webhooks.listEndpoints());
|
|
1600
4369
|
if (method === "POST" && pathname === "/testkit/webhooks/endpoints") {
|
|
1601
|
-
return
|
|
4370
|
+
return sendJson4(res, 201, webhooks.addEndpoint(await readJson(req)));
|
|
1602
4371
|
}
|
|
1603
4372
|
if (method === "DELETE" && pathname.startsWith("/testkit/webhooks/endpoints/")) {
|
|
1604
4373
|
const removed = webhooks.removeEndpoint(decodeURIComponent(pathname.slice("/testkit/webhooks/endpoints/".length)));
|
|
1605
|
-
return
|
|
4374
|
+
return sendJson4(res, removed ? 200 : 404, { ok: removed });
|
|
1606
4375
|
}
|
|
1607
4376
|
if (method === "POST" && pathname === "/testkit/reset") {
|
|
1608
4377
|
context.reset();
|
|
1609
|
-
return
|
|
4378
|
+
return sendJson4(res, 200, { ok: true });
|
|
1610
4379
|
}
|
|
1611
4380
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
1612
4381
|
const body = await readJson(req);
|
|
1613
|
-
|
|
1614
|
-
|
|
4382
|
+
let accessToken;
|
|
4383
|
+
try {
|
|
4384
|
+
accessToken = await issueToken(testkit, seed, body);
|
|
4385
|
+
} catch (error) {
|
|
4386
|
+
if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
|
|
4387
|
+
throw error;
|
|
4388
|
+
}
|
|
4389
|
+
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
4390
|
+
}
|
|
4391
|
+
if (method === "GET" && pathname === "/testkit/coverage") {
|
|
4392
|
+
return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
|
|
4393
|
+
}
|
|
4394
|
+
if (method === "DELETE" && pathname === "/testkit/coverage") {
|
|
4395
|
+
coverage.reset();
|
|
4396
|
+
return sendJson4(res, 200, { ok: true });
|
|
4397
|
+
}
|
|
4398
|
+
if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
|
|
4399
|
+
if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
|
|
4400
|
+
if (method === "POST" && pathname === "/testkit/seed") {
|
|
4401
|
+
const body = await readJson(req);
|
|
4402
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
4403
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
4404
|
+
}
|
|
4405
|
+
context.loadSeed(body);
|
|
4406
|
+
return sendJson4(res, 200, {
|
|
4407
|
+
ok: true,
|
|
4408
|
+
users: seed.users.length,
|
|
4409
|
+
organizations: seed.organizations.length,
|
|
4410
|
+
memberships: seed.memberships.length
|
|
4411
|
+
});
|
|
4412
|
+
}
|
|
4413
|
+
if (method === "POST" && pathname === "/testkit/stop") {
|
|
4414
|
+
sendJson4(res, 200, { ok: true });
|
|
4415
|
+
res.once("finish", () => void context.close().catch(() => void 0));
|
|
4416
|
+
return;
|
|
4417
|
+
}
|
|
4418
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
4419
|
+
}
|
|
4420
|
+
async function dashboard(req, res, url, context) {
|
|
4421
|
+
const method = req.method ?? "GET";
|
|
4422
|
+
const { pathname } = url;
|
|
4423
|
+
if (method === "GET" && pathname === "/dashboard") {
|
|
4424
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
4425
|
+
res.end(
|
|
4426
|
+
renderDashboard({
|
|
4427
|
+
issuer: context.testkit.issuer,
|
|
4428
|
+
seed: context.seed,
|
|
4429
|
+
suspended: (id) => context.directory.isSuspended(id),
|
|
4430
|
+
signIns: (id) => {
|
|
4431
|
+
const user = context.directory.user(id);
|
|
4432
|
+
return user ? context.directory.meta(user).totalSignIns : 0;
|
|
4433
|
+
},
|
|
4434
|
+
tokens: context.activity.tokens(),
|
|
4435
|
+
requests: context.activity.requests(),
|
|
4436
|
+
deliveries: context.webhooks.deliveries(),
|
|
4437
|
+
endpoints: context.webhooks.listEndpoints(),
|
|
4438
|
+
failures: context.failures.list(),
|
|
4439
|
+
coverage: context.coverage.report(),
|
|
4440
|
+
webhookTypes: WEBHOOK_EVENT_TYPES,
|
|
4441
|
+
live: url.searchParams.has("live"),
|
|
4442
|
+
notice: url.searchParams.get("notice")
|
|
4443
|
+
})
|
|
4444
|
+
);
|
|
4445
|
+
return;
|
|
4446
|
+
}
|
|
4447
|
+
if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
4448
|
+
const origin = req.headers.origin;
|
|
4449
|
+
if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
|
|
4450
|
+
return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
|
|
4451
|
+
}
|
|
4452
|
+
const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
|
|
4453
|
+
let notice = "Done.";
|
|
4454
|
+
try {
|
|
4455
|
+
if (pathname === "/dashboard/reset") {
|
|
4456
|
+
context.reset();
|
|
4457
|
+
notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
|
|
4458
|
+
} else if (pathname === "/dashboard/coverage/reset") {
|
|
4459
|
+
context.coverage.reset();
|
|
4460
|
+
notice = "Cleared coverage.";
|
|
4461
|
+
} else if (pathname === "/dashboard/failures/clear") {
|
|
4462
|
+
context.failures.clear();
|
|
4463
|
+
notice = "Removed every failure rule.";
|
|
4464
|
+
} else if (pathname === "/dashboard/failures") {
|
|
4465
|
+
const rule = { path: form2.path ?? "" };
|
|
4466
|
+
if (form2.method) rule.method = form2.method;
|
|
4467
|
+
if (form2.status) rule.status = Number(form2.status);
|
|
4468
|
+
if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
|
|
4469
|
+
if (form2.times) rule.times = Number(form2.times);
|
|
4470
|
+
if (form2.hang) rule.hang = true;
|
|
4471
|
+
const added = context.failures.add(rule);
|
|
4472
|
+
notice = `Added ${added.id} for ${added.path}.`;
|
|
4473
|
+
} else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
|
|
4474
|
+
const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
|
|
4475
|
+
notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
|
|
4476
|
+
} else if (pathname === "/dashboard/webhooks") {
|
|
4477
|
+
const deliveries = await context.webhooks.send({
|
|
4478
|
+
type: form2.type ?? "",
|
|
4479
|
+
user: form2.user || void 0,
|
|
4480
|
+
invalid: form2.invalid || void 0,
|
|
4481
|
+
duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
|
|
4482
|
+
});
|
|
4483
|
+
const delivered = deliveries.filter((d) => d.delivered).length;
|
|
4484
|
+
notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
|
|
4485
|
+
} else {
|
|
4486
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
|
|
4487
|
+
}
|
|
4488
|
+
} catch (error) {
|
|
4489
|
+
notice = error.message.replace(/\s+/g, " ").trim();
|
|
1615
4490
|
}
|
|
1616
|
-
|
|
4491
|
+
const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
|
|
4492
|
+
res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
|
|
4493
|
+
res.end();
|
|
1617
4494
|
}
|
|
1618
4495
|
function discovery(testkit) {
|
|
1619
4496
|
const base = testkit.issuer;
|
|
@@ -1640,9 +4517,9 @@ async function issueToken(testkit, seed, body) {
|
|
|
1640
4517
|
throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
|
|
1641
4518
|
}
|
|
1642
4519
|
const input = body;
|
|
1643
|
-
const
|
|
1644
|
-
if (
|
|
1645
|
-
throw new TestkitError("INVALID_REQUEST", `"${
|
|
4520
|
+
const invalid3 = optionalString(input, "invalid");
|
|
4521
|
+
if (invalid3 !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid3)) {
|
|
4522
|
+
throw new TestkitError("INVALID_REQUEST", `"${invalid3}" is not a known invalid token kind.`, [
|
|
1646
4523
|
`Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
|
|
1647
4524
|
]);
|
|
1648
4525
|
}
|
|
@@ -1659,7 +4536,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
1659
4536
|
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
1660
4537
|
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
1661
4538
|
expiresIn,
|
|
1662
|
-
invalid:
|
|
4539
|
+
invalid: invalid3
|
|
1663
4540
|
});
|
|
1664
4541
|
}
|
|
1665
4542
|
const permissions = optionalStrings(input, "permissions");
|
|
@@ -1672,7 +4549,11 @@ async function issueToken(testkit, seed, body) {
|
|
|
1672
4549
|
});
|
|
1673
4550
|
if (permissions) scenario2.permissions = permissions;
|
|
1674
4551
|
if (roles) scenario2.roles = roles;
|
|
1675
|
-
return await testkit.tokenFor(scenario2, {
|
|
4552
|
+
return await testkit.tokenFor(scenario2, {
|
|
4553
|
+
expiresIn,
|
|
4554
|
+
invalid: invalid3,
|
|
4555
|
+
featureFlags: featureFlagsFor(seed, scenario2.organization?.code ?? null)
|
|
4556
|
+
});
|
|
1676
4557
|
}
|
|
1677
4558
|
const options = {
|
|
1678
4559
|
subject: optionalString(input, "subject"),
|
|
@@ -1681,7 +4562,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
1681
4562
|
roles,
|
|
1682
4563
|
scopes: optionalStrings(input, "scopes"),
|
|
1683
4564
|
expiresIn,
|
|
1684
|
-
invalid:
|
|
4565
|
+
invalid: invalid3
|
|
1685
4566
|
};
|
|
1686
4567
|
if (typeof input.claims === "object" && input.claims !== null) {
|
|
1687
4568
|
options.claims = input.claims;
|
|
@@ -1737,7 +4618,7 @@ async function readText(req) {
|
|
|
1737
4618
|
}
|
|
1738
4619
|
return Buffer.concat(chunks).toString("utf8").trim();
|
|
1739
4620
|
}
|
|
1740
|
-
function
|
|
4621
|
+
function sendJson4(res, status, body, headers = {}) {
|
|
1741
4622
|
res.writeHead(status, {
|
|
1742
4623
|
"content-type": "application/json; charset=utf-8",
|
|
1743
4624
|
"cache-control": "no-store",
|
|
@@ -1751,17 +4632,16 @@ function sendError(res, error) {
|
|
|
1751
4632
|
return;
|
|
1752
4633
|
}
|
|
1753
4634
|
if (error instanceof TestkitError) {
|
|
1754
|
-
|
|
4635
|
+
sendJson4(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
1755
4636
|
return;
|
|
1756
4637
|
}
|
|
1757
|
-
|
|
4638
|
+
sendJson4(res, 500, {
|
|
1758
4639
|
error: "server_error",
|
|
1759
4640
|
error_description: error instanceof Error ? error.message : String(error)
|
|
1760
4641
|
});
|
|
1761
4642
|
}
|
|
1762
4643
|
|
|
1763
4644
|
// src/inspect.ts
|
|
1764
|
-
var import_jose2 = require("jose");
|
|
1765
4645
|
async function inspectToken(token, options = {}) {
|
|
1766
4646
|
const checks = [];
|
|
1767
4647
|
const trimmed = token.trim();
|
|
@@ -1772,8 +4652,8 @@ async function inspectToken(token, options = {}) {
|
|
|
1772
4652
|
return { kind: "unknown", header, payload, checks };
|
|
1773
4653
|
}
|
|
1774
4654
|
try {
|
|
1775
|
-
header =
|
|
1776
|
-
payload =
|
|
4655
|
+
header = decodeProtectedHeader(trimmed);
|
|
4656
|
+
payload = decodeJwt(trimmed);
|
|
1777
4657
|
} catch {
|
|
1778
4658
|
checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
|
|
1779
4659
|
return { kind: "unknown", header, payload, checks };
|
|
@@ -1803,7 +4683,7 @@ async function inspectToken(token, options = {}) {
|
|
|
1803
4683
|
checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
|
|
1804
4684
|
}
|
|
1805
4685
|
try {
|
|
1806
|
-
await
|
|
4686
|
+
await jwtVerify(trimmed, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
|
|
1807
4687
|
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
1808
4688
|
} catch (error) {
|
|
1809
4689
|
const code = error.code ?? "";
|
|
@@ -1901,6 +4781,15 @@ async function runDoctor(options) {
|
|
|
1901
4781
|
} else {
|
|
1902
4782
|
checks.push({ name: "KINDE_CLIENT_SECRET", status: "pass", detail: "Set, in the format Kinde's SDKs accept." });
|
|
1903
4783
|
}
|
|
4784
|
+
if (issuer?.startsWith("https://")) {
|
|
4785
|
+
checks.push(
|
|
4786
|
+
env.NODE_EXTRA_CA_CERTS ? { name: "NODE_EXTRA_CA_CERTS", status: "pass", detail: `${env.NODE_EXTRA_CA_CERTS}.` } : {
|
|
4787
|
+
name: "NODE_EXTRA_CA_CERTS",
|
|
4788
|
+
status: "warn",
|
|
4789
|
+
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."
|
|
4790
|
+
}
|
|
4791
|
+
);
|
|
4792
|
+
}
|
|
1904
4793
|
const site = env.KINDE_SITE_URL;
|
|
1905
4794
|
if (!site) {
|
|
1906
4795
|
checks.push({ name: "KINDE_SITE_URL", status: "warn", detail: "Not set. The Next.js SDK builds its callback URL from it." });
|
|
@@ -1909,7 +4798,7 @@ async function runDoctor(options) {
|
|
|
1909
4798
|
} else {
|
|
1910
4799
|
checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
|
|
1911
4800
|
}
|
|
1912
|
-
return { url, checks, ok: checks.every((
|
|
4801
|
+
return { url, checks, ok: checks.every((check2) => check2.status !== "fail") };
|
|
1913
4802
|
}
|
|
1914
4803
|
function parseEnvFile(text) {
|
|
1915
4804
|
const values = {};
|
|
@@ -1926,14 +4815,66 @@ function parseEnvFile(text) {
|
|
|
1926
4815
|
}
|
|
1927
4816
|
return values;
|
|
1928
4817
|
}
|
|
4818
|
+
|
|
4819
|
+
// src/handle.ts
|
|
4820
|
+
async function kindeTest(options) {
|
|
4821
|
+
const testkit = options.testkit ?? await getDefaultTestkit();
|
|
4822
|
+
const token = await testkit.tokenFor(options.scenario, options.token);
|
|
4823
|
+
const headers = token ? { authorization: `Bearer ${token}` } : {};
|
|
4824
|
+
return {
|
|
4825
|
+
token,
|
|
4826
|
+
headers,
|
|
4827
|
+
principal: testkit.principalFor(options.scenario),
|
|
4828
|
+
request: { headers }
|
|
4829
|
+
};
|
|
4830
|
+
}
|
|
4831
|
+
|
|
4832
|
+
// src/sign-in-flow.ts
|
|
4833
|
+
function appLoginUrl(loginPath, options) {
|
|
4834
|
+
const params = new URLSearchParams({ login_hint: options.user });
|
|
4835
|
+
if (options.org) params.set("org_code", options.org);
|
|
4836
|
+
return `${loginPath}${loginPath.includes("?") ? "&" : "?"}${params}`;
|
|
4837
|
+
}
|
|
4838
|
+
function readSignInRequest(html) {
|
|
4839
|
+
const match = /name="request" value="([^"]+)"/.exec(html);
|
|
4840
|
+
if (!match) {
|
|
4841
|
+
throw new Error("The page is not the kinde-testkit sign-in page. Check that the app's KINDE_ISSUER_URL points at the testkit.");
|
|
4842
|
+
}
|
|
4843
|
+
return decodeEntities(match[1]);
|
|
4844
|
+
}
|
|
4845
|
+
function signInForm(request, options) {
|
|
4846
|
+
const form2 = { request, email: options.user };
|
|
4847
|
+
if (options.org) form2.org = options.org;
|
|
4848
|
+
return form2;
|
|
4849
|
+
}
|
|
4850
|
+
function signInFailure(status, html, options) {
|
|
4851
|
+
if (status === 200 && html.includes("Choose an organization")) {
|
|
4852
|
+
return new Error(`${options.user} belongs to more than one organization. Pass one with { org: "org_..." }.`);
|
|
4853
|
+
}
|
|
4854
|
+
const alert = /role="alert"[^>]*>([\s\S]*?)<\//.exec(html)?.[1];
|
|
4855
|
+
const text = alert ? decodeEntities(alert.replace(/<[^>]+>/g, "")).trim() : `the sign-in page answered ${status}`;
|
|
4856
|
+
return new Error(`kinde-testkit refused the sign-in: ${text}`);
|
|
4857
|
+
}
|
|
4858
|
+
function resolveLocation(location, from) {
|
|
4859
|
+
return new URL(location, from).toString();
|
|
4860
|
+
}
|
|
4861
|
+
function decodeEntities(value) {
|
|
4862
|
+
return value.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
4863
|
+
}
|
|
1929
4864
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1930
4865
|
0 && (module.exports = {
|
|
4866
|
+
ActivityLog,
|
|
1931
4867
|
BILLING_EVENT_TYPES,
|
|
4868
|
+
COVERAGE_GROUPS,
|
|
4869
|
+
CoverageRecorder,
|
|
1932
4870
|
DEFAULT_AUTH_METHODS,
|
|
1933
4871
|
DEFAULT_CLIENT_ID,
|
|
4872
|
+
DEFAULT_COVERAGE_DIRECTORY,
|
|
1934
4873
|
DEFAULT_ISSUER,
|
|
1935
4874
|
DEFAULT_M2M_CLIENT_ID,
|
|
1936
4875
|
DEFAULT_SCOPES,
|
|
4876
|
+
DEFAULT_SEED_FILES,
|
|
4877
|
+
Directory,
|
|
1937
4878
|
FailureInjector,
|
|
1938
4879
|
INVALID_TOKEN_KINDS,
|
|
1939
4880
|
KindeTestkit,
|
|
@@ -1941,20 +4882,35 @@ function parseEnvFile(text) {
|
|
|
1941
4882
|
TestkitError,
|
|
1942
4883
|
WEBHOOK_EVENT_TYPES,
|
|
1943
4884
|
WebhookDispatcher,
|
|
4885
|
+
appLoginUrl,
|
|
4886
|
+
buildReport,
|
|
4887
|
+
clearCoverageDirectory,
|
|
1944
4888
|
createKindeOrganization,
|
|
1945
4889
|
createKindeToken,
|
|
1946
4890
|
createKindeUser,
|
|
4891
|
+
createLocalCertificate,
|
|
1947
4892
|
createMembership,
|
|
4893
|
+
ensureLocalCertificate,
|
|
4894
|
+
findSeedFile,
|
|
4895
|
+
formatCoverageReport,
|
|
1948
4896
|
getDefaultTestkit,
|
|
1949
4897
|
inspectToken,
|
|
1950
4898
|
isAuthenticated,
|
|
4899
|
+
kindeTest,
|
|
4900
|
+
loadSeedFile,
|
|
4901
|
+
mergeSnapshots,
|
|
1951
4902
|
parseEnvFile,
|
|
1952
4903
|
principalFromClaims,
|
|
4904
|
+
readCoverageDirectory,
|
|
4905
|
+
readSignInRequest,
|
|
1953
4906
|
resetFactories,
|
|
4907
|
+
resolveLocation,
|
|
1954
4908
|
resolveSeed,
|
|
1955
4909
|
runDoctor,
|
|
1956
4910
|
scenario,
|
|
1957
4911
|
seedScenario,
|
|
4912
|
+
signInFailure,
|
|
4913
|
+
signInForm,
|
|
1958
4914
|
startKindeTestkit,
|
|
1959
4915
|
toKindeRole
|
|
1960
4916
|
});
|