kinde-testkit 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +242 -12
- package/dist/chunk-33AHOLUN.js +183 -0
- package/dist/chunk-33AHOLUN.js.map +1 -0
- package/dist/chunk-GCOZVCZY.js +3430 -0
- package/dist/chunk-GCOZVCZY.js.map +1 -0
- package/dist/chunk-U2D47SCY.js +72 -0
- package/dist/chunk-U2D47SCY.js.map +1 -0
- package/dist/cli.js +178 -2849
- package/dist/cli.js.map +1 -0
- package/dist/cypress-support.js +119 -0
- package/dist/cypress-support.js.map +1 -0
- package/dist/cypress.cjs +4251 -0
- package/dist/cypress.d.cts +24 -0
- package/dist/cypress.d.ts +25 -0
- package/dist/cypress.js +23 -0
- package/dist/cypress.js.map +1 -0
- package/dist/handle-BERQZCyH.d.cts +32 -0
- package/dist/handle-Dh0UpIzG.d.ts +33 -0
- package/dist/index.cjs +2046 -101
- package/dist/index.d.cts +38 -463
- package/dist/index.d.ts +39 -463
- package/dist/index.js +90 -2822
- package/dist/index.js.map +1 -1
- package/dist/jest.cjs +4320 -0
- package/dist/jest.d.cts +17 -0
- package/dist/jest.d.ts +18 -0
- package/dist/jest.js +23 -0
- package/dist/jest.js.map +1 -0
- package/dist/playwright.d.ts +2 -54
- package/dist/server-BiODgeoB.d.ts +185 -0
- package/dist/server-ciWIscoQ.d.cts +579 -0
- package/dist/vitest.d.ts +7 -403
- package/dist/vitest.js +6 -2677
- package/dist/vitest.js.map +1 -1
- package/dist/webhooks-DJyCsbdF.d.ts +397 -0
- package/package.json +36 -4
- package/dist/index.cjs.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -20,12 +20,17 @@ 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,
|
|
29
34
|
Directory: () => Directory,
|
|
30
35
|
FailureInjector: () => FailureInjector,
|
|
31
36
|
INVALID_TOKEN_KINDS: () => INVALID_TOKEN_KINDS,
|
|
@@ -34,22 +39,35 @@ __export(src_exports, {
|
|
|
34
39
|
TestkitError: () => TestkitError,
|
|
35
40
|
WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
|
|
36
41
|
WebhookDispatcher: () => WebhookDispatcher,
|
|
42
|
+
appLoginUrl: () => appLoginUrl,
|
|
43
|
+
buildReport: () => buildReport,
|
|
44
|
+
clearCoverageDirectory: () => clearCoverageDirectory,
|
|
37
45
|
createKindeOrganization: () => createKindeOrganization,
|
|
38
46
|
createKindeToken: () => createKindeToken,
|
|
39
47
|
createKindeUser: () => createKindeUser,
|
|
40
48
|
createLocalCertificate: () => createLocalCertificate,
|
|
41
49
|
createMembership: () => createMembership,
|
|
42
50
|
ensureLocalCertificate: () => ensureLocalCertificate,
|
|
51
|
+
findSeedFile: () => findSeedFile,
|
|
52
|
+
formatCoverageReport: () => formatCoverageReport,
|
|
43
53
|
getDefaultTestkit: () => getDefaultTestkit,
|
|
44
54
|
inspectToken: () => inspectToken,
|
|
45
55
|
isAuthenticated: () => isAuthenticated,
|
|
56
|
+
kindeTest: () => kindeTest,
|
|
57
|
+
loadSeedFile: () => loadSeedFile,
|
|
58
|
+
mergeSnapshots: () => mergeSnapshots,
|
|
46
59
|
parseEnvFile: () => parseEnvFile,
|
|
47
60
|
principalFromClaims: () => principalFromClaims,
|
|
61
|
+
readCoverageDirectory: () => readCoverageDirectory,
|
|
62
|
+
readSignInRequest: () => readSignInRequest,
|
|
48
63
|
resetFactories: () => resetFactories,
|
|
64
|
+
resolveLocation: () => resolveLocation,
|
|
49
65
|
resolveSeed: () => resolveSeed,
|
|
50
66
|
runDoctor: () => runDoctor,
|
|
51
67
|
scenario: () => scenario,
|
|
52
68
|
seedScenario: () => seedScenario,
|
|
69
|
+
signInFailure: () => signInFailure,
|
|
70
|
+
signInForm: () => signInForm,
|
|
53
71
|
startKindeTestkit: () => startKindeTestkit,
|
|
54
72
|
toKindeRole: () => toKindeRole
|
|
55
73
|
});
|
|
@@ -176,19 +194,1154 @@ function isAuthenticated(value) {
|
|
|
176
194
|
|
|
177
195
|
// src/testkit.ts
|
|
178
196
|
var import_node_crypto2 = require("crypto");
|
|
179
|
-
|
|
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
|
+
}
|
|
180
1330
|
|
|
181
1331
|
// src/errors.ts
|
|
182
1332
|
var TestkitError = class extends Error {
|
|
183
1333
|
code;
|
|
184
1334
|
details;
|
|
185
|
-
|
|
186
|
-
|
|
1335
|
+
/** The message without the details list. */
|
|
1336
|
+
summary;
|
|
1337
|
+
constructor(code, message2, details = []) {
|
|
1338
|
+
super(details.length > 0 ? `${message2}
|
|
187
1339
|
|
|
188
|
-
${details.map((d) => ` - ${d}`).join("\n")}` :
|
|
1340
|
+
${details.map((d) => ` - ${d}`).join("\n")}` : message2);
|
|
189
1341
|
this.name = "TestkitError";
|
|
190
1342
|
this.code = code;
|
|
191
1343
|
this.details = details;
|
|
1344
|
+
this.summary = message2;
|
|
192
1345
|
}
|
|
193
1346
|
toString() {
|
|
194
1347
|
return `${this.code}
|
|
@@ -201,17 +1354,17 @@ ${this.message}`;
|
|
|
201
1354
|
var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
|
|
202
1355
|
function toSeconds(value) {
|
|
203
1356
|
if (typeof value === "number") {
|
|
204
|
-
if (!Number.isFinite(value) || value < 0) throw
|
|
1357
|
+
if (!Number.isFinite(value) || value < 0) throw invalid2(String(value));
|
|
205
1358
|
return Math.floor(value);
|
|
206
1359
|
}
|
|
207
1360
|
const match = /^(\d+)(s|m|h|d)$/.exec(value.trim());
|
|
208
1361
|
if (!match) {
|
|
209
1362
|
if (/^\d+$/.test(value.trim())) return Number(value.trim());
|
|
210
|
-
throw
|
|
1363
|
+
throw invalid2(value);
|
|
211
1364
|
}
|
|
212
1365
|
return Number(match[1]) * UNITS[match[2]];
|
|
213
1366
|
}
|
|
214
|
-
function
|
|
1367
|
+
function invalid2(value) {
|
|
215
1368
|
return new TestkitError(
|
|
216
1369
|
"INVALID_DURATION",
|
|
217
1370
|
`"${value}" is not a valid duration. Use seconds (3600) or a number with s, m, h or d ("15m", "1h").`
|
|
@@ -239,6 +1392,20 @@ var INVALID_TOKEN_KINDS = [
|
|
|
239
1392
|
var WRONG_ISSUER = "https://wrong-issuer.kinde-testkit.test";
|
|
240
1393
|
var WRONG_AUDIENCE = "https://wrong-audience.kinde-testkit.test";
|
|
241
1394
|
var KindeTestkit = class _KindeTestkit {
|
|
1395
|
+
observers = [];
|
|
1396
|
+
/** Calls the observer for every token signed from now on. Returns a function that stops it. */
|
|
1397
|
+
observe(observer) {
|
|
1398
|
+
this.observers.push(observer);
|
|
1399
|
+
return () => {
|
|
1400
|
+
this.observers = this.observers.filter((o) => o !== observer);
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
async signAccess(payload, invalid3, now) {
|
|
1404
|
+
const final = applyInvalidClaims(payload, invalid3, now);
|
|
1405
|
+
const token = await this.sign(final, invalid3);
|
|
1406
|
+
for (const observer of this.observers) observer.accessToken?.(final, invalid3, token);
|
|
1407
|
+
return token;
|
|
1408
|
+
}
|
|
242
1409
|
issuer;
|
|
243
1410
|
audience;
|
|
244
1411
|
clientId;
|
|
@@ -270,7 +1437,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
270
1437
|
return toSeconds(this.accessTokenExpiresIn);
|
|
271
1438
|
}
|
|
272
1439
|
async verify(token) {
|
|
273
|
-
const { payload } = await
|
|
1440
|
+
const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
|
|
274
1441
|
issuer: this.issuer,
|
|
275
1442
|
algorithms: ["RS256"]
|
|
276
1443
|
});
|
|
@@ -298,7 +1465,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
298
1465
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
299
1466
|
if (options.featureFlags) payload.feature_flags = options.featureFlags;
|
|
300
1467
|
Object.assign(payload, options.claims ?? {});
|
|
301
|
-
return this.
|
|
1468
|
+
return this.signAccess(payload, options.invalid, now);
|
|
302
1469
|
}
|
|
303
1470
|
async m2mToken(options = {}) {
|
|
304
1471
|
const now = this.clock();
|
|
@@ -319,10 +1486,13 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
319
1486
|
if (options.organizationCode) payload.org_code = options.organizationCode;
|
|
320
1487
|
if (options.permissions !== void 0) payload.permissions = [...options.permissions];
|
|
321
1488
|
Object.assign(payload, options.claims ?? {});
|
|
322
|
-
return this.
|
|
1489
|
+
return this.signAccess(payload, options.invalid, now);
|
|
323
1490
|
}
|
|
324
1491
|
async tokenFor(scenario2, overrides = {}) {
|
|
325
|
-
if (scenario2.kind === "unauthenticated")
|
|
1492
|
+
if (scenario2.kind === "unauthenticated") {
|
|
1493
|
+
for (const observer of this.observers) observer.anonymous?.();
|
|
1494
|
+
return null;
|
|
1495
|
+
}
|
|
326
1496
|
return this.token({
|
|
327
1497
|
subject: scenario2.user.id,
|
|
328
1498
|
organizationCode: scenario2.organization?.code ?? null,
|
|
@@ -364,7 +1534,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
364
1534
|
for (const key of Object.keys(payload)) {
|
|
365
1535
|
if (payload[key] === null || payload[key] === void 0) delete payload[key];
|
|
366
1536
|
}
|
|
367
|
-
|
|
1537
|
+
const token = await this.sign(payload);
|
|
1538
|
+
for (const observer of this.observers) observer.idToken?.(payload, token);
|
|
1539
|
+
return token;
|
|
368
1540
|
}
|
|
369
1541
|
async headersFor(scenario2, overrides = {}) {
|
|
370
1542
|
const token = await this.tokenFor(scenario2, overrides);
|
|
@@ -374,17 +1546,17 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
374
1546
|
if (scenario2.kind === "unauthenticated") return null;
|
|
375
1547
|
return scenarioPrincipal(scenario2, this.issuer);
|
|
376
1548
|
}
|
|
377
|
-
async signPayload(payload,
|
|
378
|
-
return this.sign(payload,
|
|
1549
|
+
async signPayload(payload, invalid3) {
|
|
1550
|
+
return this.sign(payload, invalid3);
|
|
379
1551
|
}
|
|
380
|
-
async sign(payload,
|
|
381
|
-
if (
|
|
382
|
-
const header =
|
|
383
|
-
return `${header}.${
|
|
1552
|
+
async sign(payload, invalid3) {
|
|
1553
|
+
if (invalid3 === "unsigned") {
|
|
1554
|
+
const header = base64url_exports.encode(JSON.stringify({ alg: "none", typ: "JWT" }));
|
|
1555
|
+
return `${header}.${base64url_exports.encode(JSON.stringify(payload))}.`;
|
|
384
1556
|
}
|
|
385
|
-
const key =
|
|
386
|
-
const jwt = await new
|
|
387
|
-
return
|
|
1557
|
+
const key = invalid3 === "unknown-key" ? await this.stranger() : this.signingKey;
|
|
1558
|
+
const jwt = await new SignJWT(payload).setProtectedHeader({ alg: "RS256", kid: key.kid, typ: "JWT" }).sign(key.privateKey);
|
|
1559
|
+
return invalid3 === "bad-signature" ? tamperSignature(jwt) : jwt;
|
|
388
1560
|
}
|
|
389
1561
|
stranger() {
|
|
390
1562
|
this.strangerKey ??= createSigningKey("kinde-testkit-unknown");
|
|
@@ -418,9 +1590,9 @@ function scenarioPrincipal(scenario2, issuer) {
|
|
|
418
1590
|
claims: { ...scenario2.claims }
|
|
419
1591
|
};
|
|
420
1592
|
}
|
|
421
|
-
function applyInvalidClaims(payload,
|
|
1593
|
+
function applyInvalidClaims(payload, invalid3, now) {
|
|
422
1594
|
const next = { ...payload };
|
|
423
|
-
switch (
|
|
1595
|
+
switch (invalid3) {
|
|
424
1596
|
case "expired":
|
|
425
1597
|
next.iat = now - 7200;
|
|
426
1598
|
next.exp = now - 3600;
|
|
@@ -450,16 +1622,16 @@ function applyInvalidClaims(payload, invalid2, now) {
|
|
|
450
1622
|
return next;
|
|
451
1623
|
}
|
|
452
1624
|
async function createSigningKey(prefix) {
|
|
453
|
-
const { privateKey, publicKey } = await
|
|
454
|
-
const jwk = await
|
|
455
|
-
const kid = `${prefix}-${(await
|
|
1625
|
+
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
|
1626
|
+
const jwk = await exportJWK(publicKey);
|
|
1627
|
+
const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
|
|
456
1628
|
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
457
1629
|
}
|
|
458
1630
|
function tamperSignature(jwt) {
|
|
459
1631
|
const [header, payload, signature] = jwt.split(".");
|
|
460
|
-
const bytes =
|
|
1632
|
+
const bytes = base64url_exports.decode(signature);
|
|
461
1633
|
bytes[0] = (bytes[0] ?? 0) ^ 255;
|
|
462
|
-
return `${header}.${payload}.${
|
|
1634
|
+
return `${header}.${payload}.${base64url_exports.encode(bytes)}`;
|
|
463
1635
|
}
|
|
464
1636
|
function toArray(value) {
|
|
465
1637
|
if (value === void 0) return [];
|
|
@@ -578,8 +1750,8 @@ function readTlv(buf, offset) {
|
|
|
578
1750
|
}
|
|
579
1751
|
return { start: offset + header, end: offset + header + len };
|
|
580
1752
|
}
|
|
581
|
-
function tlv(
|
|
582
|
-
return Buffer.concat([Buffer.from([
|
|
1753
|
+
function tlv(tag2, content) {
|
|
1754
|
+
return Buffer.concat([Buffer.from([tag2]), length(content.length), content]);
|
|
583
1755
|
}
|
|
584
1756
|
function length(n) {
|
|
585
1757
|
if (n < 128) return Buffer.from([n]);
|
|
@@ -668,8 +1840,8 @@ function renderSignIn(options) {
|
|
|
668
1840
|
const value = escapeHtml(user.email ?? user.id);
|
|
669
1841
|
const hasName = Boolean(user.givenName || user.familyName);
|
|
670
1842
|
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
671
|
-
const
|
|
672
|
-
return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${
|
|
1843
|
+
const tag2 = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
1844
|
+
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>`;
|
|
673
1845
|
}).join("");
|
|
674
1846
|
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
675
1847
|
return layout(
|
|
@@ -686,8 +1858,8 @@ function renderOrganizationPicker(options) {
|
|
|
686
1858
|
`<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>`
|
|
687
1859
|
);
|
|
688
1860
|
}
|
|
689
|
-
function renderMessage(title,
|
|
690
|
-
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(
|
|
1861
|
+
function renderMessage(title, message2) {
|
|
1862
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message2)}</p>`);
|
|
691
1863
|
}
|
|
692
1864
|
|
|
693
1865
|
// src/seed.ts
|
|
@@ -1014,16 +2186,18 @@ var OAuthError = class extends Error {
|
|
|
1014
2186
|
error;
|
|
1015
2187
|
};
|
|
1016
2188
|
var AuthorizationServer = class {
|
|
1017
|
-
constructor(testkit, seed, emit = () => void 0, directory) {
|
|
2189
|
+
constructor(testkit, seed, emit = () => void 0, directory, observe = () => void 0) {
|
|
1018
2190
|
this.testkit = testkit;
|
|
1019
2191
|
this.seed = seed;
|
|
1020
2192
|
this.emit = emit;
|
|
1021
2193
|
this.directory = directory;
|
|
2194
|
+
this.observe = observe;
|
|
1022
2195
|
}
|
|
1023
2196
|
testkit;
|
|
1024
2197
|
seed;
|
|
1025
2198
|
emit;
|
|
1026
2199
|
directory;
|
|
2200
|
+
observe;
|
|
1027
2201
|
codes = /* @__PURE__ */ new Map();
|
|
1028
2202
|
refreshTokens = /* @__PURE__ */ new Map();
|
|
1029
2203
|
signedUpUsers = /* @__PURE__ */ new Map();
|
|
@@ -1060,6 +2234,7 @@ var AuthorizationServer = class {
|
|
|
1060
2234
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
1061
2235
|
}
|
|
1062
2236
|
if (params.get("prompt") === "none") {
|
|
2237
|
+
this.observe("session.silent");
|
|
1063
2238
|
return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
1064
2239
|
}
|
|
1065
2240
|
sendHtml(
|
|
@@ -1073,15 +2248,15 @@ var AuthorizationServer = class {
|
|
|
1073
2248
|
})
|
|
1074
2249
|
);
|
|
1075
2250
|
}
|
|
1076
|
-
login(res,
|
|
2251
|
+
login(res, form2) {
|
|
1077
2252
|
let request;
|
|
1078
2253
|
try {
|
|
1079
|
-
request = decodeRequest(
|
|
2254
|
+
request = decodeRequest(form2.request ?? "");
|
|
1080
2255
|
} catch {
|
|
1081
2256
|
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
1082
2257
|
}
|
|
1083
2258
|
const encoded = encodeRequest(request);
|
|
1084
|
-
const ref = (
|
|
2259
|
+
const ref = (form2.user || form2.email || "").trim();
|
|
1085
2260
|
if (!ref) {
|
|
1086
2261
|
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." }));
|
|
1087
2262
|
}
|
|
@@ -1090,6 +2265,7 @@ var AuthorizationServer = class {
|
|
|
1090
2265
|
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
1091
2266
|
}
|
|
1092
2267
|
if (this.directory?.isSuspended(user.id)) {
|
|
2268
|
+
this.observe("identity.suspended");
|
|
1093
2269
|
return sendHtml(
|
|
1094
2270
|
res,
|
|
1095
2271
|
403,
|
|
@@ -1102,10 +2278,11 @@ var AuthorizationServer = class {
|
|
|
1102
2278
|
);
|
|
1103
2279
|
}
|
|
1104
2280
|
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
1105
|
-
const wanted = request.orgCode ??
|
|
2281
|
+
const wanted = request.orgCode ?? form2.org ?? null;
|
|
1106
2282
|
let organizationCode = null;
|
|
1107
2283
|
if (wanted) {
|
|
1108
2284
|
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
2285
|
+
this.observe("organization.non-member");
|
|
1109
2286
|
return sendHtml(
|
|
1110
2287
|
res,
|
|
1111
2288
|
403,
|
|
@@ -1160,18 +2337,20 @@ var AuthorizationServer = class {
|
|
|
1160
2337
|
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
1161
2338
|
redirect(res, target.toString());
|
|
1162
2339
|
}
|
|
1163
|
-
async token(req, res,
|
|
2340
|
+
async token(req, res, form2) {
|
|
1164
2341
|
try {
|
|
1165
|
-
const clientId = clientIdFrom(req,
|
|
1166
|
-
const grantType =
|
|
2342
|
+
const clientId = clientIdFrom(req, form2);
|
|
2343
|
+
const grantType = form2.grant_type;
|
|
1167
2344
|
if (grantType === "client_credentials") {
|
|
1168
|
-
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req,
|
|
2345
|
+
return sendJson(res, 200, await this.clientCredentials(clientId, clientSecretFrom(req, form2), form2));
|
|
1169
2346
|
}
|
|
1170
2347
|
let grant;
|
|
1171
2348
|
if (grantType === "authorization_code") {
|
|
1172
|
-
grant = this.redeemCode(
|
|
2349
|
+
grant = this.redeemCode(form2, clientId);
|
|
2350
|
+
this.observe("session.sign-in");
|
|
1173
2351
|
} else if (grantType === "refresh_token") {
|
|
1174
|
-
grant = this.redeemRefreshToken(
|
|
2352
|
+
grant = this.redeemRefreshToken(form2, clientId);
|
|
2353
|
+
this.observe("session.refresh");
|
|
1175
2354
|
} else {
|
|
1176
2355
|
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code, refresh_token and client_credentials, not "${grantType ?? ""}".`);
|
|
1177
2356
|
}
|
|
@@ -1183,14 +2362,14 @@ var AuthorizationServer = class {
|
|
|
1183
2362
|
throw error;
|
|
1184
2363
|
}
|
|
1185
2364
|
}
|
|
1186
|
-
async clientCredentials(clientId, clientSecret,
|
|
2365
|
+
async clientCredentials(clientId, clientSecret, form2) {
|
|
1187
2366
|
const app = this.seed.applications.find((a) => a.clientId === clientId);
|
|
1188
2367
|
if (app?.clientSecret && app.clientSecret !== clientSecret) {
|
|
1189
2368
|
throw new OAuthError(401, "invalid_client", `The client secret for ${clientId} is wrong.`);
|
|
1190
2369
|
}
|
|
1191
|
-
const requested = (
|
|
2370
|
+
const requested = (form2.scope ?? "").split(/\s+/).filter(Boolean);
|
|
1192
2371
|
const granted = app?.scopes ? requested.length === 0 ? [...app.scopes] : requested.filter((scope) => app.scopes.includes(scope)) : requested;
|
|
1193
|
-
const audience = (
|
|
2372
|
+
const audience = (form2.audience ?? "").split(/\s+/).filter(Boolean);
|
|
1194
2373
|
return {
|
|
1195
2374
|
access_token: await this.testkit.m2mToken({
|
|
1196
2375
|
clientId,
|
|
@@ -1210,8 +2389,8 @@ var AuthorizationServer = class {
|
|
|
1210
2389
|
this.refreshTokens.clear();
|
|
1211
2390
|
this.signedUpUsers.clear();
|
|
1212
2391
|
}
|
|
1213
|
-
redeemCode(
|
|
1214
|
-
const code =
|
|
2392
|
+
redeemCode(form2, clientId) {
|
|
2393
|
+
const code = form2.code ?? "";
|
|
1215
2394
|
const pending = this.codes.get(code);
|
|
1216
2395
|
this.codes.delete(code);
|
|
1217
2396
|
if (!pending || pending.expiresAt < Date.now()) {
|
|
@@ -1220,11 +2399,11 @@ var AuthorizationServer = class {
|
|
|
1220
2399
|
if (pending.clientId !== clientId) {
|
|
1221
2400
|
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
1222
2401
|
}
|
|
1223
|
-
if (
|
|
2402
|
+
if (form2.redirect_uri !== pending.redirectUri) {
|
|
1224
2403
|
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
1225
2404
|
}
|
|
1226
2405
|
if (pending.codeChallenge) {
|
|
1227
|
-
const verifier =
|
|
2406
|
+
const verifier = form2.code_verifier ?? "";
|
|
1228
2407
|
const expected = pending.codeChallengeMethod === "plain" ? verifier : (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
|
|
1229
2408
|
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
1230
2409
|
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
@@ -1232,8 +2411,8 @@ var AuthorizationServer = class {
|
|
|
1232
2411
|
}
|
|
1233
2412
|
return pending;
|
|
1234
2413
|
}
|
|
1235
|
-
redeemRefreshToken(
|
|
1236
|
-
const token =
|
|
2414
|
+
redeemRefreshToken(form2, clientId) {
|
|
2415
|
+
const token = form2.refresh_token ?? "";
|
|
1237
2416
|
const grant = this.refreshTokens.get(token);
|
|
1238
2417
|
this.refreshTokens.delete(token);
|
|
1239
2418
|
if (!grant) {
|
|
@@ -1307,11 +2486,13 @@ var AuthorizationServer = class {
|
|
|
1307
2486
|
phone: null
|
|
1308
2487
|
});
|
|
1309
2488
|
}
|
|
1310
|
-
revoke(res,
|
|
1311
|
-
if (
|
|
2489
|
+
revoke(res, form2) {
|
|
2490
|
+
if (form2.token) this.refreshTokens.delete(form2.token);
|
|
2491
|
+
this.observe("session.revoke");
|
|
1312
2492
|
sendJson(res, 200, {});
|
|
1313
2493
|
}
|
|
1314
2494
|
logout(res, params) {
|
|
2495
|
+
this.observe("session.sign-out");
|
|
1315
2496
|
const target = params.get("redirect");
|
|
1316
2497
|
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
1317
2498
|
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
@@ -1323,6 +2504,7 @@ var AuthorizationServer = class {
|
|
|
1323
2504
|
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
1324
2505
|
if (!this.signedUpUsers.has(user.id)) {
|
|
1325
2506
|
this.signedUpUsers.set(user.id, user);
|
|
2507
|
+
this.observe("identity.unseeded");
|
|
1326
2508
|
if (this.directory) this.seed.users.push(user);
|
|
1327
2509
|
this.emit("user.created", user);
|
|
1328
2510
|
}
|
|
@@ -1376,24 +2558,24 @@ function decodeRequest(value) {
|
|
|
1376
2558
|
}
|
|
1377
2559
|
return request;
|
|
1378
2560
|
}
|
|
1379
|
-
function clientIdFrom(req,
|
|
2561
|
+
function clientIdFrom(req, form2) {
|
|
1380
2562
|
const header = req.headers.authorization ?? "";
|
|
1381
2563
|
if (header.startsWith("Basic ")) {
|
|
1382
2564
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1383
2565
|
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
1384
2566
|
if (id) return id;
|
|
1385
2567
|
}
|
|
1386
|
-
if (
|
|
2568
|
+
if (form2.client_id) return form2.client_id;
|
|
1387
2569
|
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
1388
2570
|
}
|
|
1389
|
-
function clientSecretFrom(req,
|
|
2571
|
+
function clientSecretFrom(req, form2) {
|
|
1390
2572
|
const header = req.headers.authorization ?? "";
|
|
1391
2573
|
if (header.startsWith("Basic ")) {
|
|
1392
2574
|
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
1393
2575
|
const index = decoded.indexOf(":");
|
|
1394
2576
|
if (index >= 0) return decodeURIComponent(decoded.slice(index + 1));
|
|
1395
2577
|
}
|
|
1396
|
-
return
|
|
2578
|
+
return form2.client_secret ?? null;
|
|
1397
2579
|
}
|
|
1398
2580
|
function redirectWithError(res, request, error, description) {
|
|
1399
2581
|
const target = new URL(request.redirectUri);
|
|
@@ -1553,8 +2735,8 @@ function sendPage(res, url, field, items, extra) {
|
|
|
1553
2735
|
metadata: { has_more: hasMore, next_page_starting_after: page.at(-1)?.id ?? null }
|
|
1554
2736
|
});
|
|
1555
2737
|
}
|
|
1556
|
-
function errors(code,
|
|
1557
|
-
return { errors: [{ code, message }] };
|
|
2738
|
+
function errors(code, message2) {
|
|
2739
|
+
return { errors: [{ code, message: message2 }] };
|
|
1558
2740
|
}
|
|
1559
2741
|
function sendJson2(res, status, body) {
|
|
1560
2742
|
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
@@ -1580,6 +2762,22 @@ var Directory = class {
|
|
|
1580
2762
|
this.userMeta.clear();
|
|
1581
2763
|
this.orgMeta.clear();
|
|
1582
2764
|
}
|
|
2765
|
+
/** Replaces the whole seed with another resolved seed, and makes it the state reset() returns to. */
|
|
2766
|
+
load(next) {
|
|
2767
|
+
for (const key of Object.keys(next)) {
|
|
2768
|
+
const current = this.seed[key];
|
|
2769
|
+
if (Array.isArray(current)) {
|
|
2770
|
+
current.splice(0, current.length, ...next[key]);
|
|
2771
|
+
} else {
|
|
2772
|
+
const record = current;
|
|
2773
|
+
for (const name of Object.keys(record)) delete record[name];
|
|
2774
|
+
Object.assign(record, next[key]);
|
|
2775
|
+
}
|
|
2776
|
+
}
|
|
2777
|
+
this.snapshot = JSON.stringify(this.seed);
|
|
2778
|
+
this.userMeta.clear();
|
|
2779
|
+
this.orgMeta.clear();
|
|
2780
|
+
}
|
|
1583
2781
|
user(id) {
|
|
1584
2782
|
return this.seed.users.find((user) => user.id === id);
|
|
1585
2783
|
}
|
|
@@ -2099,11 +3297,11 @@ function paginate(items, query) {
|
|
|
2099
3297
|
const next = offset + size < items.length ? Buffer.from(String(offset + size)).toString("base64url") : null;
|
|
2100
3298
|
return { items: page, nextToken: next };
|
|
2101
3299
|
}
|
|
2102
|
-
function errors2(code,
|
|
2103
|
-
return { errors: [{ code, message }] };
|
|
3300
|
+
function errors2(code, message2) {
|
|
3301
|
+
return { errors: [{ code, message: message2 }] };
|
|
2104
3302
|
}
|
|
2105
|
-
function notFound(code,
|
|
2106
|
-
return [404, errors2(code,
|
|
3303
|
+
function notFound(code, message2) {
|
|
3304
|
+
return [404, errors2(code, message2)];
|
|
2107
3305
|
}
|
|
2108
3306
|
function str(value) {
|
|
2109
3307
|
return typeof value === "string" ? value : null;
|
|
@@ -2246,6 +3444,8 @@ var WebhookDispatcher = class {
|
|
|
2246
3444
|
nextEndpoint = 1;
|
|
2247
3445
|
retryDelaysMs;
|
|
2248
3446
|
timeoutMs;
|
|
3447
|
+
/** Set by the server to record coverage. */
|
|
3448
|
+
observe = () => void 0;
|
|
2249
3449
|
addEndpoint(input) {
|
|
2250
3450
|
if (!isHttpUrl2(input.url)) {
|
|
2251
3451
|
throw new TestkitError("INVALID_REQUEST", `Webhook URL "${String(input.url)}" must be an http or https URL.`);
|
|
@@ -2257,6 +3457,14 @@ var WebhookDispatcher = class {
|
|
|
2257
3457
|
this.endpoints.push(endpoint);
|
|
2258
3458
|
return { ...endpoint };
|
|
2259
3459
|
}
|
|
3460
|
+
/** Replaces the endpoints that came from the seed, as when a new seed is loaded. */
|
|
3461
|
+
replaceSeededEndpoints(endpoints) {
|
|
3462
|
+
const seeded = new Set(this.seededEndpoints.map((e) => e.id));
|
|
3463
|
+
this.endpoints = this.endpoints.filter((e) => !seeded.has(e.id));
|
|
3464
|
+
const added = endpoints.map((endpoint) => this.addEndpoint(endpoint));
|
|
3465
|
+
const ids = new Set(added.map((e) => e.id));
|
|
3466
|
+
this.seededEndpoints = this.endpoints.filter((e) => ids.has(e.id));
|
|
3467
|
+
}
|
|
2260
3468
|
removeEndpoint(id) {
|
|
2261
3469
|
const before = this.endpoints.length;
|
|
2262
3470
|
this.endpoints = this.endpoints.filter((e) => e.id !== id);
|
|
@@ -2307,6 +3515,9 @@ var WebhookDispatcher = class {
|
|
|
2307
3515
|
`No webhook endpoint listens for ${options.type}. Add one in the seed's "webhooks", with addEndpoint(), or pass "to".`
|
|
2308
3516
|
);
|
|
2309
3517
|
}
|
|
3518
|
+
if (copies > 1) this.observe("webhook.duplicate");
|
|
3519
|
+
if (options.invalid === "stale") this.observe("webhook.stale");
|
|
3520
|
+
else if (options.invalid) this.observe("webhook.forged");
|
|
2310
3521
|
if (options.delayMs) await sleep(Math.min(options.delayMs, 6e4));
|
|
2311
3522
|
const signed = await this.testkit.signPayload(
|
|
2312
3523
|
event,
|
|
@@ -2316,7 +3527,11 @@ var WebhookDispatcher = class {
|
|
|
2316
3527
|
const webhookId = `wh_${(0, import_node_crypto6.randomBytes)(12).toString("hex")}`;
|
|
2317
3528
|
return Array.from({ length: copies }, (_, index) => this.deliver(target.url, webhookId, signed, event, index + 1));
|
|
2318
3529
|
});
|
|
2319
|
-
|
|
3530
|
+
const deliveries = await Promise.all(jobs);
|
|
3531
|
+
if (!options.invalid) {
|
|
3532
|
+
for (const delivery of deliveries) this.observe(delivery.delivered ? "webhook.delivered" : "webhook.failed");
|
|
3533
|
+
}
|
|
3534
|
+
return deliveries;
|
|
2320
3535
|
}
|
|
2321
3536
|
async deliver(url, webhookId, body, event, copy) {
|
|
2322
3537
|
const delivery = {
|
|
@@ -2465,7 +3680,511 @@ function isHttpUrl2(value) {
|
|
|
2465
3680
|
}
|
|
2466
3681
|
}
|
|
2467
3682
|
function sleep(ms) {
|
|
2468
|
-
return new Promise((
|
|
3683
|
+
return new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
3684
|
+
}
|
|
3685
|
+
|
|
3686
|
+
// src/activity.ts
|
|
3687
|
+
var LIMIT = 200;
|
|
3688
|
+
var SECRET_PARAMS = ["code", "client_secret", "refresh_token", "code_verifier", "token"];
|
|
3689
|
+
var ActivityLog = class {
|
|
3690
|
+
requestLog = [];
|
|
3691
|
+
tokenLog = [];
|
|
3692
|
+
request(entry) {
|
|
3693
|
+
const query = new URLSearchParams(entry.query);
|
|
3694
|
+
for (const name of SECRET_PARAMS) if (query.has(name)) query.set(name, "\u2026");
|
|
3695
|
+
const search = query.toString();
|
|
3696
|
+
push(this.requestLog, {
|
|
3697
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3698
|
+
method: entry.method,
|
|
3699
|
+
path: search ? `${entry.path}?${search}` : entry.path,
|
|
3700
|
+
status: entry.status,
|
|
3701
|
+
durationMs: entry.durationMs,
|
|
3702
|
+
injected: entry.injected
|
|
3703
|
+
});
|
|
3704
|
+
}
|
|
3705
|
+
token(kind, claims, invalid3, token) {
|
|
3706
|
+
const roles = Array.isArray(claims.roles) ? claims.roles.map((r) => typeof r === "string" ? r : r.key ?? "") : [];
|
|
3707
|
+
push(this.tokenLog, {
|
|
3708
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3709
|
+
kind,
|
|
3710
|
+
subject: typeof claims.sub === "string" ? claims.sub : typeof claims.azp === "string" && kind === "m2m" ? claims.azp : null,
|
|
3711
|
+
organization: typeof claims.org_code === "string" ? claims.org_code : null,
|
|
3712
|
+
permissions: Array.isArray(claims.permissions) ? claims.permissions : [],
|
|
3713
|
+
roles,
|
|
3714
|
+
invalid: invalid3 ?? null,
|
|
3715
|
+
expiresAt: typeof claims.exp === "number" ? new Date(claims.exp * 1e3).toISOString() : null,
|
|
3716
|
+
claims,
|
|
3717
|
+
token
|
|
3718
|
+
});
|
|
3719
|
+
}
|
|
3720
|
+
requests() {
|
|
3721
|
+
return [...this.requestLog];
|
|
3722
|
+
}
|
|
3723
|
+
tokens() {
|
|
3724
|
+
return [...this.tokenLog];
|
|
3725
|
+
}
|
|
3726
|
+
reset() {
|
|
3727
|
+
this.requestLog = [];
|
|
3728
|
+
this.tokenLog = [];
|
|
3729
|
+
}
|
|
3730
|
+
};
|
|
3731
|
+
function push(list, entry) {
|
|
3732
|
+
list.push(entry);
|
|
3733
|
+
if (list.length > LIMIT) list.splice(0, list.length - LIMIT);
|
|
3734
|
+
}
|
|
3735
|
+
|
|
3736
|
+
// src/coverage.ts
|
|
3737
|
+
var import_node_fs2 = require("fs");
|
|
3738
|
+
var import_node_path2 = require("path");
|
|
3739
|
+
var COVERAGE_GROUPS = [
|
|
3740
|
+
{
|
|
3741
|
+
name: "Identity",
|
|
3742
|
+
items: [
|
|
3743
|
+
{ id: "identity.user", label: "Signed-in user", hint: "Mint a token for a seeded user or sign one in." },
|
|
3744
|
+
{ id: "identity.anonymous", label: "No user", hint: "Call a route with an unauthenticated scenario, which sends no token." },
|
|
3745
|
+
{ id: "identity.no-organization", label: "User with no organization", hint: "Mint a valid user token without org_code." },
|
|
3746
|
+
{ id: "identity.unseeded", label: "User not in the seed", hint: "Sign in with an email that is not seeded." },
|
|
3747
|
+
{ id: "identity.id-token", label: "ID token", hint: "Sign in through the sign-in page so the app gets an ID token." },
|
|
3748
|
+
{ id: "identity.suspended", label: "Suspended user refused", hint: "Suspend a user with the Management API, then sign them in." }
|
|
3749
|
+
]
|
|
3750
|
+
},
|
|
3751
|
+
{
|
|
3752
|
+
name: "Organizations",
|
|
3753
|
+
items: [
|
|
3754
|
+
{ id: "organization.token", label: "Token with an organization", hint: "Mint a token with org_code." },
|
|
3755
|
+
{ id: "organization.two-for-one-user", label: "One user in two organizations", hint: "Mint tokens for the same user in two organizations." },
|
|
3756
|
+
{ id: "organization.cross", label: "Users from different organizations", hint: "Mint tokens for users in two organizations to test cross-organization access." },
|
|
3757
|
+
{ 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." },
|
|
3758
|
+
{ id: "organization.missing", label: "Organization claim missing", hint: 'Mint a token with invalid: "missing-organization".' }
|
|
3759
|
+
]
|
|
3760
|
+
},
|
|
3761
|
+
{
|
|
3762
|
+
name: "Permissions",
|
|
3763
|
+
items: [
|
|
3764
|
+
{ id: "permission.granted", label: "Token with permissions", hint: "Mint a token that carries permissions." },
|
|
3765
|
+
{ 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." },
|
|
3766
|
+
{ id: "permission.roles", label: "Token with roles", hint: "Mint a token for a member with roles." },
|
|
3767
|
+
{ id: "permission.none", label: "Token with no permissions", hint: 'Mint a token with invalid: "missing-permissions", or for a member with none.' },
|
|
3768
|
+
{ id: "permission.feature-flags", label: "Token with feature flags", hint: "Seed featureFlags and mint a token for a seeded user." }
|
|
3769
|
+
]
|
|
3770
|
+
},
|
|
3771
|
+
{
|
|
3772
|
+
name: "Token validation",
|
|
3773
|
+
items: ["expired", "future-iat", "wrong-issuer", "wrong-audience", "bad-signature", "unknown-key", "unsigned", "missing-subject"].map(
|
|
3774
|
+
(kind) => ({ id: `token.${kind}`, label: tokenLabel(kind), hint: `Mint a token with invalid: "${kind}".` })
|
|
3775
|
+
)
|
|
3776
|
+
},
|
|
3777
|
+
{
|
|
3778
|
+
name: "Sessions",
|
|
3779
|
+
items: [
|
|
3780
|
+
{ id: "session.sign-in", label: "Sign-in through the sign-in page", hint: "Sign a user in through your app's login route." },
|
|
3781
|
+
{ id: "session.refresh", label: "Refresh", hint: "Let the app refresh its session, or call the refresh_token grant." },
|
|
3782
|
+
{ id: "session.sign-out", label: "Sign-out", hint: "Sign out through your app's logout route." },
|
|
3783
|
+
{ id: "session.revoke", label: "Refresh token revoked", hint: "Call /oauth2/revoke, as some SDKs do on sign-out." },
|
|
3784
|
+
{ id: "session.silent", label: "Silent sign-in with no session", hint: "Send prompt=none and handle login_required." }
|
|
3785
|
+
]
|
|
3786
|
+
},
|
|
3787
|
+
{
|
|
3788
|
+
name: "Machine-to-machine",
|
|
3789
|
+
items: [
|
|
3790
|
+
{ id: "m2m.token", label: "M2M token", hint: "Call the client_credentials grant or mint an M2M token." },
|
|
3791
|
+
{ id: "m2m.scopes", label: "M2M token with scopes", hint: "Seed an application with scopes and request a token." },
|
|
3792
|
+
{ id: "m2m.organization", label: "Organization-scoped M2M token", hint: "Seed an application with an organization." },
|
|
3793
|
+
{ id: "m2m.invalid", label: "Invalid M2M token", hint: "Mint an M2M token with an invalid kind." }
|
|
3794
|
+
]
|
|
3795
|
+
},
|
|
3796
|
+
{
|
|
3797
|
+
name: "Kinde APIs",
|
|
3798
|
+
items: [
|
|
3799
|
+
{ id: "api.management-read", label: "Management API read", hint: "Read users or organizations through the Management API." },
|
|
3800
|
+
{ id: "api.management-write", label: "Management API change", hint: "Create, update or delete through the Management API." },
|
|
3801
|
+
{ id: "api.management-denied", label: "Management API refused", hint: "Call the Management API with a missing scope or the wrong token." },
|
|
3802
|
+
{ id: "api.account", label: "Account API", hint: "Read permissions, roles or feature flags through the Account API." }
|
|
3803
|
+
]
|
|
3804
|
+
},
|
|
3805
|
+
{
|
|
3806
|
+
name: "Webhooks",
|
|
3807
|
+
items: [
|
|
3808
|
+
{ id: "webhook.delivered", label: "Event delivered", hint: "Send a webhook that your handler accepts." },
|
|
3809
|
+
{ id: "webhook.duplicate", label: "Duplicate delivery", hint: "Send a webhook with duplicate: 2." },
|
|
3810
|
+
{ id: "webhook.forged", label: "Forged signature", hint: 'Send a webhook with invalid: "bad-signature", "unknown-key" or "unsigned".' },
|
|
3811
|
+
{ id: "webhook.stale", label: "Stale event", hint: 'Send a webhook with invalid: "stale".' },
|
|
3812
|
+
{ id: "webhook.failed", label: "Delivery your handler refused", hint: "Send an event your handler answers with a status other than 200." }
|
|
3813
|
+
]
|
|
3814
|
+
},
|
|
3815
|
+
{
|
|
3816
|
+
name: "Outages",
|
|
3817
|
+
items: [
|
|
3818
|
+
{ id: "outage.error", label: "Kinde answers with an error", hint: "Inject a 500 or 503 on an endpoint the app calls." },
|
|
3819
|
+
{ id: "outage.rate-limit", label: "Rate limit", hint: "Inject a 429." },
|
|
3820
|
+
{ id: "outage.slow", label: "Slow answer", hint: "Inject a delay." },
|
|
3821
|
+
{ id: "outage.timeout", label: "No answer", hint: "Inject a hang so the client hits its timeout." }
|
|
3822
|
+
]
|
|
3823
|
+
}
|
|
3824
|
+
];
|
|
3825
|
+
var ALL_IDS = new Set(COVERAGE_GROUPS.flatMap((group) => group.items.map((item) => item.id)));
|
|
3826
|
+
function tokenLabel(kind) {
|
|
3827
|
+
return {
|
|
3828
|
+
expired: "Expired token",
|
|
3829
|
+
"future-iat": "Token issued in the future",
|
|
3830
|
+
"wrong-issuer": "Wrong issuer",
|
|
3831
|
+
"wrong-audience": "Wrong audience",
|
|
3832
|
+
"bad-signature": "Tampered signature",
|
|
3833
|
+
"unknown-key": "Unknown signing key",
|
|
3834
|
+
unsigned: "Unsigned token",
|
|
3835
|
+
"missing-subject": "No subject"
|
|
3836
|
+
}[kind];
|
|
3837
|
+
}
|
|
3838
|
+
var CoverageRecorder = class {
|
|
3839
|
+
hits = /* @__PURE__ */ new Map();
|
|
3840
|
+
userOrganizations = /* @__PURE__ */ new Map();
|
|
3841
|
+
organizationUsers = /* @__PURE__ */ new Map();
|
|
3842
|
+
organizationPermissionSets = /* @__PURE__ */ new Map();
|
|
3843
|
+
hit(id) {
|
|
3844
|
+
if (!ALL_IDS.has(id)) return;
|
|
3845
|
+
this.hits.set(id, (this.hits.get(id) ?? 0) + 1);
|
|
3846
|
+
}
|
|
3847
|
+
/** Called for every access token the testkit signs. */
|
|
3848
|
+
observeAccessToken(payload, invalid3) {
|
|
3849
|
+
if (Array.isArray(payload.gty) && payload.gty.includes("client_credentials")) {
|
|
3850
|
+
this.hit("m2m.token");
|
|
3851
|
+
if (typeof payload.scope === "string" && payload.scope.length > 0) this.hit("m2m.scopes");
|
|
3852
|
+
if (typeof payload.org_code === "string") this.hit("m2m.organization");
|
|
3853
|
+
if (invalid3) this.hit("m2m.invalid");
|
|
3854
|
+
return;
|
|
3855
|
+
}
|
|
3856
|
+
if (invalid3 === "missing-organization") return this.hit("organization.missing");
|
|
3857
|
+
if (invalid3 === "missing-permissions") return this.hit("permission.none");
|
|
3858
|
+
if (invalid3) return this.hit(`token.${invalid3}`);
|
|
3859
|
+
const subject = typeof payload.sub === "string" ? payload.sub : null;
|
|
3860
|
+
const organization = typeof payload.org_code === "string" ? payload.org_code : null;
|
|
3861
|
+
const permissions = Array.isArray(payload.permissions) ? payload.permissions : [];
|
|
3862
|
+
if (subject) this.hit("identity.user");
|
|
3863
|
+
if (!organization) this.hit("identity.no-organization");
|
|
3864
|
+
if (permissions.length > 0) this.hit("permission.granted");
|
|
3865
|
+
else this.hit("permission.none");
|
|
3866
|
+
if (Array.isArray(payload.roles) && payload.roles.length > 0) this.hit("permission.roles");
|
|
3867
|
+
if (payload.feature_flags && Object.keys(payload.feature_flags).length > 0) this.hit("permission.feature-flags");
|
|
3868
|
+
if (!organization) return;
|
|
3869
|
+
this.hit("organization.token");
|
|
3870
|
+
if (subject) {
|
|
3871
|
+
const organizations = add(this.userOrganizations, subject, organization);
|
|
3872
|
+
if (organizations.size > 1) this.hit("organization.two-for-one-user");
|
|
3873
|
+
add(this.organizationUsers, organization, subject);
|
|
3874
|
+
const organizationsWithUsers = [...this.organizationUsers.entries()].filter(([, users]) => users.size > 0);
|
|
3875
|
+
const distinctUsers = new Set(organizationsWithUsers.flatMap(([, users]) => [...users]));
|
|
3876
|
+
if (organizationsWithUsers.length > 1 && distinctUsers.size > 1) this.hit("organization.cross");
|
|
3877
|
+
}
|
|
3878
|
+
const sets = add(this.organizationPermissionSets, organization, [...permissions].sort().join(" "));
|
|
3879
|
+
if (sets.size > 1) this.hit("permission.different-sets");
|
|
3880
|
+
}
|
|
3881
|
+
report() {
|
|
3882
|
+
return buildReport(Object.fromEntries(this.hits));
|
|
3883
|
+
}
|
|
3884
|
+
snapshot() {
|
|
3885
|
+
return { version: 1, hits: Object.fromEntries(this.hits) };
|
|
3886
|
+
}
|
|
3887
|
+
reset() {
|
|
3888
|
+
this.hits.clear();
|
|
3889
|
+
this.userOrganizations.clear();
|
|
3890
|
+
this.organizationUsers.clear();
|
|
3891
|
+
this.organizationPermissionSets.clear();
|
|
3892
|
+
}
|
|
3893
|
+
/** Writes this run's snapshot to the coverage folder, so separate test files can be merged. */
|
|
3894
|
+
write(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
3895
|
+
const folder = (0, import_node_path2.resolve)(directory);
|
|
3896
|
+
(0, import_node_fs2.mkdirSync)(folder, { recursive: true });
|
|
3897
|
+
const file = (0, import_node_path2.join)(folder, `run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
|
|
3898
|
+
(0, import_node_fs2.writeFileSync)(file, `${JSON.stringify(this.snapshot())}
|
|
3899
|
+
`);
|
|
3900
|
+
return file;
|
|
3901
|
+
}
|
|
3902
|
+
};
|
|
3903
|
+
var DEFAULT_COVERAGE_DIRECTORY = (0, import_node_path2.join)(".kinde-testkit", "coverage");
|
|
3904
|
+
function add(map, key, value) {
|
|
3905
|
+
let set2 = map.get(key);
|
|
3906
|
+
if (!set2) map.set(key, set2 = /* @__PURE__ */ new Set());
|
|
3907
|
+
set2.add(value);
|
|
3908
|
+
return set2;
|
|
3909
|
+
}
|
|
3910
|
+
function buildReport(hits) {
|
|
3911
|
+
const groups = COVERAGE_GROUPS.map((group) => {
|
|
3912
|
+
const items = group.items.map((item) => ({ ...item, count: hits[item.id] ?? 0, covered: (hits[item.id] ?? 0) > 0 }));
|
|
3913
|
+
return { name: group.name, covered: items.filter((i) => i.covered).length, total: items.length, items };
|
|
3914
|
+
});
|
|
3915
|
+
return {
|
|
3916
|
+
covered: groups.reduce((sum, g) => sum + g.covered, 0),
|
|
3917
|
+
total: groups.reduce((sum, g) => sum + g.total, 0),
|
|
3918
|
+
groups
|
|
3919
|
+
};
|
|
3920
|
+
}
|
|
3921
|
+
function mergeSnapshots(snapshots) {
|
|
3922
|
+
const hits = {};
|
|
3923
|
+
for (const snapshot of snapshots) {
|
|
3924
|
+
for (const [id, count] of Object.entries(snapshot.hits ?? {})) hits[id] = (hits[id] ?? 0) + count;
|
|
3925
|
+
}
|
|
3926
|
+
return hits;
|
|
3927
|
+
}
|
|
3928
|
+
function readCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
3929
|
+
const folder = (0, import_node_path2.resolve)(directory);
|
|
3930
|
+
let names = [];
|
|
3931
|
+
try {
|
|
3932
|
+
names = (0, import_node_fs2.readdirSync)(folder).filter((name) => name.endsWith(".json"));
|
|
3933
|
+
} catch {
|
|
3934
|
+
}
|
|
3935
|
+
const snapshots = names.map((name) => JSON.parse((0, import_node_fs2.readFileSync)((0, import_node_path2.join)(folder, name), "utf8")));
|
|
3936
|
+
return { files: names.length, report: buildReport(mergeSnapshots(snapshots)) };
|
|
3937
|
+
}
|
|
3938
|
+
function clearCoverageDirectory(directory = DEFAULT_COVERAGE_DIRECTORY) {
|
|
3939
|
+
(0, import_node_fs2.rmSync)((0, import_node_path2.resolve)(directory), { recursive: true, force: true });
|
|
3940
|
+
}
|
|
3941
|
+
function formatCoverageReport(report, options = {}) {
|
|
3942
|
+
const width = Math.max(...report.groups.map((g) => g.name.length)) + 3;
|
|
3943
|
+
const lines = ["Kinde authentication coverage", ""];
|
|
3944
|
+
for (const group of report.groups) {
|
|
3945
|
+
lines.push(`${group.name.padEnd(width)}${String(group.covered).padStart(2)}/${group.total}`);
|
|
3946
|
+
}
|
|
3947
|
+
lines.push("", `Overall: ${report.covered}/${report.total}`);
|
|
3948
|
+
if (options.missing !== false) {
|
|
3949
|
+
const missing = report.groups.flatMap((g) => g.items.filter((i) => !i.covered).map((i) => ({ group: g.name, ...i })));
|
|
3950
|
+
if (missing.length > 0) {
|
|
3951
|
+
lines.push("", "Not covered:");
|
|
3952
|
+
for (const item of missing) lines.push(` ${item.group}: ${item.label}. ${item.hint}`);
|
|
3953
|
+
}
|
|
3954
|
+
}
|
|
3955
|
+
return lines.join("\n");
|
|
3956
|
+
}
|
|
3957
|
+
|
|
3958
|
+
// src/dashboard.ts
|
|
3959
|
+
var STYLE2 = `
|
|
3960
|
+
: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}
|
|
3961
|
+
@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}}
|
|
3962
|
+
*{box-sizing:border-box}
|
|
3963
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
3964
|
+
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)}
|
|
3965
|
+
header .brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;text-transform:uppercase;color:var(--muted)}
|
|
3966
|
+
header .issuer{font:13px ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
3967
|
+
nav{display:flex;flex-wrap:wrap;gap:14px;font-size:13px}
|
|
3968
|
+
nav a{color:var(--muted);text-decoration:none}nav a:hover{color:var(--ink)}
|
|
3969
|
+
main{max-width:1180px;margin:0 auto;padding:24px 28px 60px;display:grid;gap:22px}
|
|
3970
|
+
section{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:18px 20px;overflow:hidden}
|
|
3971
|
+
h2{margin:0 0 4px;font-size:16px;font-weight:600}
|
|
3972
|
+
.sub{margin:0 0 14px;color:var(--muted);font-size:13px}
|
|
3973
|
+
table{width:100%;border-collapse:collapse;font-size:13px}
|
|
3974
|
+
th{text-align:left;font-weight:500;color:var(--muted);border-bottom:1px solid var(--line);padding:6px 10px 6px 0;white-space:nowrap}
|
|
3975
|
+
td{border-bottom:1px solid var(--line);padding:7px 10px 7px 0;vertical-align:top}
|
|
3976
|
+
tr:last-child td{border-bottom:0}
|
|
3977
|
+
code,.mono{font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
3978
|
+
.chips{display:flex;flex-wrap:wrap;gap:4px}
|
|
3979
|
+
.chip{font:11px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--soft);border-radius:5px;padding:0 6px}
|
|
3980
|
+
.ok{color:var(--ok)}.bad{color:var(--bad)}.muted{color:var(--muted)}
|
|
3981
|
+
.empty{color:var(--muted);font-size:13px;margin:0}
|
|
3982
|
+
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:end}
|
|
3983
|
+
label{display:grid;gap:3px;font-size:12px;color:var(--muted)}
|
|
3984
|
+
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}
|
|
3985
|
+
input[type=checkbox]{height:auto}
|
|
3986
|
+
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}
|
|
3987
|
+
button.primary{background:var(--accent);color:var(--accent-ink);border-color:var(--accent)}
|
|
3988
|
+
button:hover{border-color:var(--muted)}
|
|
3989
|
+
details summary{cursor:pointer;color:var(--muted)}
|
|
3990
|
+
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}
|
|
3991
|
+
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 26px}
|
|
3992
|
+
.group{display:flex;justify-content:space-between;font-weight:500;margin-bottom:4px}
|
|
3993
|
+
.group+ul{list-style:none;margin:0 0 10px;padding:0;font-size:13px}
|
|
3994
|
+
.notice{padding:10px 14px;border-radius:8px;background:var(--soft);font-size:13px}
|
|
3995
|
+
.split{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:22px}
|
|
3996
|
+
`;
|
|
3997
|
+
function renderDashboard(data) {
|
|
3998
|
+
const e = escapeHtml;
|
|
3999
|
+
const { seed } = data;
|
|
4000
|
+
const orgName = (code) => seed.organizations.find((o) => o.code === code)?.name ?? code;
|
|
4001
|
+
const userLabel = (id) => seed.users.find((u) => u.id === id)?.email ?? id;
|
|
4002
|
+
const users = seed.users.length ? table2(
|
|
4003
|
+
["User", "ID", "Organizations", "Sign-ins", "Status"],
|
|
4004
|
+
seed.users.map((user) => [
|
|
4005
|
+
e([user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id) + (user.email ? `<div class="muted">${e(user.email)}</div>` : ""),
|
|
4006
|
+
`<code>${e(user.id)}</code>`,
|
|
4007
|
+
chips(seed.memberships.filter((m) => m.userId === user.id).map((m) => m.organizationCode)),
|
|
4008
|
+
String(data.signIns(user.id)),
|
|
4009
|
+
data.suspended(user.id) ? `<span class="bad">Suspended</span>` : `<span class="ok">Active</span>`
|
|
4010
|
+
])
|
|
4011
|
+
) : empty("No users yet. Seed some, or sign in with any email.");
|
|
4012
|
+
const organizations = seed.organizations.length ? table2(
|
|
4013
|
+
["Organization", "Code", "Members"],
|
|
4014
|
+
seed.organizations.map((org) => [
|
|
4015
|
+
e(org.name),
|
|
4016
|
+
`<code>${e(org.code)}</code>`,
|
|
4017
|
+
String(seed.memberships.filter((m) => m.organizationCode === org.code).length)
|
|
4018
|
+
])
|
|
4019
|
+
) : empty("No organizations.");
|
|
4020
|
+
const memberships = seed.memberships.length ? table2(
|
|
4021
|
+
["User", "Organization", "Roles", "Permissions in the token"],
|
|
4022
|
+
seed.memberships.map((m) => [
|
|
4023
|
+
e(userLabel(m.userId)),
|
|
4024
|
+
e(orgName(m.organizationCode)),
|
|
4025
|
+
chips(m.roles),
|
|
4026
|
+
chips(effectivePermissions(seed, m))
|
|
4027
|
+
])
|
|
4028
|
+
) : empty("No memberships.");
|
|
4029
|
+
const applications = seed.applications.length ? table2(
|
|
4030
|
+
["Client ID", "Organization", "Scopes"],
|
|
4031
|
+
seed.applications.map((a) => [`<code>${e(a.clientId)}</code>`, e(a.organizationCode ?? "none"), chips(a.scopes ?? [])])
|
|
4032
|
+
) : "";
|
|
4033
|
+
const tokens = data.tokens.length ? table2(
|
|
4034
|
+
["Issued", "Kind", "Subject", "Organization", "Permissions", ""],
|
|
4035
|
+
[...data.tokens].reverse().slice(0, 50).map((t) => [
|
|
4036
|
+
time(t.at),
|
|
4037
|
+
t.invalid ? `${e(t.kind)} <span class="bad">${e(t.invalid)}</span>` : e(t.kind),
|
|
4038
|
+
`<code>${e(t.subject ?? "none")}</code>`,
|
|
4039
|
+
e(t.organization ?? "none"),
|
|
4040
|
+
chips(t.permissions),
|
|
4041
|
+
`<details><summary>Claims</summary><pre>${e(JSON.stringify(t.claims, null, 2))}</pre><pre>${e(t.token)}</pre></details>`
|
|
4042
|
+
])
|
|
4043
|
+
) : empty("No tokens issued yet.");
|
|
4044
|
+
const requests = data.requests.length ? table2(
|
|
4045
|
+
["Time", "Request", "Status", "Time taken"],
|
|
4046
|
+
[...data.requests].reverse().slice(0, 100).map((r) => [
|
|
4047
|
+
time(r.at),
|
|
4048
|
+
`<code>${e(r.method)} ${e(r.path)}</code>`,
|
|
4049
|
+
`<span class="${r.status >= 400 ? "bad" : "ok"}">${r.status}</span>${r.injected ? ` <span class="muted">injected</span>` : ""}`,
|
|
4050
|
+
`${r.durationMs} ms`
|
|
4051
|
+
])
|
|
4052
|
+
) : empty("No requests yet.");
|
|
4053
|
+
const deliveries = data.deliveries.length ? table2(
|
|
4054
|
+
["Event", "Endpoint", "Copy", "Result"],
|
|
4055
|
+
[...data.deliveries].reverse().slice(0, 50).map((d) => [
|
|
4056
|
+
`<code>${e(d.type)}</code>`,
|
|
4057
|
+
`<code>${e(d.url)}</code>`,
|
|
4058
|
+
String(d.copy),
|
|
4059
|
+
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>`
|
|
4060
|
+
])
|
|
4061
|
+
) : empty("No webhooks sent yet.");
|
|
4062
|
+
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>`;
|
|
4063
|
+
const webhookForm = data.endpoints.length ? form(
|
|
4064
|
+
"/dashboard/webhooks",
|
|
4065
|
+
`<label>Event<select name="type">${data.webhookTypes.map((t) => `<option>${e(t)}</option>`).join("")}</select></label>
|
|
4066
|
+
<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>
|
|
4067
|
+
<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>
|
|
4068
|
+
<label>Copies<input name="duplicate" type="number" min="1" max="10" value="1" style="width:70px"></label>
|
|
4069
|
+
<button class="primary">Send</button>`
|
|
4070
|
+
) : "";
|
|
4071
|
+
const failures = data.failures.length ? table2(
|
|
4072
|
+
["Path", "Method", "Effect", "Remaining", "Hits", ""],
|
|
4073
|
+
data.failures.map((f) => [
|
|
4074
|
+
`<code>${e(f.path)}</code>`,
|
|
4075
|
+
e(f.method ?? "any"),
|
|
4076
|
+
e(f.hang ? "Hang" : [f.status !== null ? `Status ${f.status}` : "", f.delayMs ? `Delay ${f.delayMs} ms` : ""].filter(Boolean).join(", ")),
|
|
4077
|
+
f.remaining === null ? "Until removed" : String(f.remaining),
|
|
4078
|
+
String(f.hits),
|
|
4079
|
+
form(`/dashboard/failures/${encodeURIComponent(f.id)}/remove`, `<button>Remove</button>`)
|
|
4080
|
+
])
|
|
4081
|
+
) : empty("No failure rules.");
|
|
4082
|
+
const coverage = `<div class="grid">${data.coverage.groups.map(
|
|
4083
|
+
(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>`
|
|
4084
|
+
).join("")}</div>`;
|
|
4085
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4086
|
+
${data.live ? `<meta http-equiv="refresh" content="3">` : ""}
|
|
4087
|
+
<title>kinde-testkit dashboard</title><style>${STYLE2}</style></head><body>
|
|
4088
|
+
<header>
|
|
4089
|
+
<div><div class="brand">kinde-testkit</div><div class="issuer">${e(data.issuer)}</div></div>
|
|
4090
|
+
<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>
|
|
4091
|
+
<div class="row">
|
|
4092
|
+
<a href="${data.live ? "/dashboard" : "/dashboard?live=1"}"><button type="button">${data.live ? "Stop live updates" : "Live updates"}</button></a>
|
|
4093
|
+
${form("/dashboard/reset", `<button>Reset state</button>`)}
|
|
4094
|
+
</div>
|
|
4095
|
+
</header>
|
|
4096
|
+
<main>
|
|
4097
|
+
${data.notice ? `<div class="notice">${e(data.notice)}</div>` : ""}
|
|
4098
|
+
<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>
|
|
4099
|
+
<div class="split">
|
|
4100
|
+
<section><h2>Organizations</h2><p class="sub">Codes your app sees in <code>org_code</code>.</p>${organizations}</section>
|
|
4101
|
+
<section><h2>Memberships</h2><p class="sub">Role permissions are added to the member's own.</p>${memberships}</section>
|
|
4102
|
+
</div>
|
|
4103
|
+
${applications ? `<section><h2>Machine-to-machine applications</h2><p class="sub">Clients that call the client_credentials grant.</p>${applications}</section>` : ""}
|
|
4104
|
+
<section id="tokens"><h2>Issued tokens</h2><p class="sub">The latest 50 access, ID and machine-to-machine tokens.</p>${tokens}</section>
|
|
4105
|
+
<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>
|
|
4106
|
+
<section id="webhooks"><h2>Webhook deliveries</h2>${endpoints}${webhookForm}<div style="margin-top:14px">${deliveries}</div></section>
|
|
4107
|
+
<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>
|
|
4108
|
+
${form(
|
|
4109
|
+
"/dashboard/failures",
|
|
4110
|
+
`<label>Path<input name="path" value="/oauth2/token" required style="width:200px"></label>
|
|
4111
|
+
<label>Method<select name="method"><option value="">Any</option><option>GET</option><option>POST</option><option>PATCH</option><option>DELETE</option></select></label>
|
|
4112
|
+
<label>Status<input name="status" type="number" min="100" max="599" placeholder="503" style="width:80px"></label>
|
|
4113
|
+
<label>Delay ms<input name="delayMs" type="number" min="0" max="60000" style="width:90px"></label>
|
|
4114
|
+
<label>Times<input name="times" type="number" min="1" placeholder="all" style="width:70px"></label>
|
|
4115
|
+
<label><span>Hang</span><input name="hang" type="checkbox" value="1"></label>
|
|
4116
|
+
<button class="primary">Add rule</button>`
|
|
4117
|
+
)}
|
|
4118
|
+
<div style="margin-top:14px">${failures}</div>
|
|
4119
|
+
${data.failures.length ? `<div style="margin-top:10px">${form("/dashboard/failures/clear", `<button>Remove all</button>`)}</div>` : ""}
|
|
4120
|
+
</section>
|
|
4121
|
+
<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}
|
|
4122
|
+
<div style="margin-top:6px">${form("/dashboard/coverage/reset", `<button>Clear coverage</button>`)}</div></section>
|
|
4123
|
+
</main></body></html>`;
|
|
4124
|
+
}
|
|
4125
|
+
function table2(headers, rows) {
|
|
4126
|
+
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>`;
|
|
4127
|
+
}
|
|
4128
|
+
function chips(values) {
|
|
4129
|
+
if (values.length === 0) return `<span class="muted">none</span>`;
|
|
4130
|
+
return `<div class="chips">${values.map((v) => `<span class="chip">${escapeHtml(v)}</span>`).join("")}</div>`;
|
|
4131
|
+
}
|
|
4132
|
+
function empty(text) {
|
|
4133
|
+
return `<p class="empty">${escapeHtml(text)}</p>`;
|
|
4134
|
+
}
|
|
4135
|
+
function time(iso) {
|
|
4136
|
+
return `<span class="mono">${escapeHtml(iso.slice(11, 19))}</span>`;
|
|
4137
|
+
}
|
|
4138
|
+
function form(action, body) {
|
|
4139
|
+
return `<form method="post" action="${escapeHtml(action)}" class="row">${body}</form>`;
|
|
4140
|
+
}
|
|
4141
|
+
|
|
4142
|
+
// src/seed-file.ts
|
|
4143
|
+
var import_node_fs3 = require("fs");
|
|
4144
|
+
var import_node_path3 = require("path");
|
|
4145
|
+
var import_node_url = require("url");
|
|
4146
|
+
var import_yaml = require("yaml");
|
|
4147
|
+
var DEFAULT_SEED_FILES = [
|
|
4148
|
+
"kinde-testkit.json",
|
|
4149
|
+
"kinde-testkit.yaml",
|
|
4150
|
+
"kinde-testkit.yml",
|
|
4151
|
+
"kinde-testkit.ts",
|
|
4152
|
+
"kinde-testkit.mts",
|
|
4153
|
+
"kinde-testkit.js",
|
|
4154
|
+
"kinde-testkit.mjs"
|
|
4155
|
+
];
|
|
4156
|
+
function findSeedFile(directory = ".") {
|
|
4157
|
+
return DEFAULT_SEED_FILES.map((name) => (0, import_node_path3.resolve)(directory, name)).find((path) => (0, import_node_fs3.existsSync)(path));
|
|
4158
|
+
}
|
|
4159
|
+
async function loadSeedFile(path) {
|
|
4160
|
+
const file = (0, import_node_path3.resolve)(path);
|
|
4161
|
+
const extension = (0, import_node_path3.extname)(file).toLowerCase();
|
|
4162
|
+
let value;
|
|
4163
|
+
try {
|
|
4164
|
+
if (extension === ".yaml" || extension === ".yml") {
|
|
4165
|
+
value = (0, import_yaml.parse)((0, import_node_fs3.readFileSync)(file, "utf8"));
|
|
4166
|
+
} else if ([".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"].includes(extension)) {
|
|
4167
|
+
const module2 = await import((0, import_node_url.pathToFileURL)(file).href);
|
|
4168
|
+
value = module2.seed ?? module2.default;
|
|
4169
|
+
if (value && typeof value === "object" && "default" in value && !("users" in value)) {
|
|
4170
|
+
value = value.default;
|
|
4171
|
+
}
|
|
4172
|
+
} else {
|
|
4173
|
+
value = JSON.parse((0, import_node_fs3.readFileSync)(file, "utf8"));
|
|
4174
|
+
}
|
|
4175
|
+
} catch (error) {
|
|
4176
|
+
const message2 = error instanceof Error ? error.message : String(error);
|
|
4177
|
+
const details = [message2];
|
|
4178
|
+
if (extension.endsWith("ts") && /Unknown file extension|ERR_UNKNOWN_FILE_EXTENSION|strip/i.test(message2)) {
|
|
4179
|
+
details.push("Your Node version cannot run TypeScript files. Use Node 22.18 or later, or a .js, .json or .yaml seed.");
|
|
4180
|
+
}
|
|
4181
|
+
throw new TestkitError("SEED_INVALID", `Could not read the seed file at ${file}.`, details);
|
|
4182
|
+
}
|
|
4183
|
+
if (value === null || value === void 0) value = {};
|
|
4184
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
4185
|
+
throw new TestkitError("SEED_INVALID", `The seed file at ${file} must contain an object with users, organizations and memberships.`);
|
|
4186
|
+
}
|
|
4187
|
+
return value;
|
|
2469
4188
|
}
|
|
2470
4189
|
|
|
2471
4190
|
// src/server.ts
|
|
@@ -2480,30 +4199,49 @@ async function startKindeTestkit(options = {}) {
|
|
|
2480
4199
|
`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).`
|
|
2481
4200
|
);
|
|
2482
4201
|
}
|
|
2483
|
-
const
|
|
4202
|
+
const seedInput = typeof options.seed === "string" ? await loadSeedFile(options.seed) : options.seed ?? {};
|
|
4203
|
+
const seed = resolveSeed(seedInput);
|
|
2484
4204
|
const failures = new FailureInjector();
|
|
2485
4205
|
let ready;
|
|
2486
|
-
const testkitReady = new Promise((
|
|
4206
|
+
const testkitReady = new Promise((resolve4) => ready = resolve4);
|
|
2487
4207
|
const listener = (req, res) => {
|
|
2488
4208
|
testkitReady.then((context) => handle(req, res, context)).catch((error) => sendError(res, error));
|
|
2489
4209
|
};
|
|
2490
4210
|
const certificate = options.https ? ensureLocalCertificate(typeof options.https === "object" ? options.https.certDirectory : void 0) : null;
|
|
2491
4211
|
const server = certificate ? (0, import_node_https.createServer)({ cert: certificate.cert, key: certificate.key }, listener) : (0, import_node_http.createServer)(listener);
|
|
2492
|
-
await new Promise((
|
|
4212
|
+
await new Promise((resolve4, reject) => {
|
|
2493
4213
|
server.once("error", reject);
|
|
2494
|
-
server.listen(options.port ?? 4400, host, () =>
|
|
4214
|
+
server.listen(options.port ?? 4400, host, () => resolve4());
|
|
2495
4215
|
});
|
|
2496
4216
|
const { port } = server.address();
|
|
2497
|
-
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" ? "localhost" : host;
|
|
4217
|
+
const urlHost = host === "::1" ? "[::1]" : host === "127.0.0.1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
2498
4218
|
const url = `${certificate ? "https" : "http"}://${urlHost}:${port}`;
|
|
2499
4219
|
const testkit = await KindeTestkit.create({
|
|
2500
|
-
issuer: options.issuer ??
|
|
2501
|
-
audience: options.audience ??
|
|
2502
|
-
clientId: options.clientId ??
|
|
4220
|
+
issuer: options.issuer ?? seedInput.issuer ?? url,
|
|
4221
|
+
audience: options.audience ?? seedInput.audience,
|
|
4222
|
+
clientId: options.clientId ?? seedInput.clientId
|
|
2503
4223
|
});
|
|
4224
|
+
const coverage = new CoverageRecorder();
|
|
4225
|
+
const activity = new ActivityLog();
|
|
4226
|
+
testkit.observe({
|
|
4227
|
+
accessToken(payload, invalid3, token) {
|
|
4228
|
+
coverage.observeAccessToken(payload, invalid3);
|
|
4229
|
+
const m2m = Array.isArray(payload.gty) && payload.gty.includes("client_credentials");
|
|
4230
|
+
activity.token(m2m ? "m2m" : "access", payload, invalid3, token);
|
|
4231
|
+
},
|
|
4232
|
+
idToken(payload, token) {
|
|
4233
|
+
coverage.hit("identity.id-token");
|
|
4234
|
+
activity.token("id", payload, void 0, token);
|
|
4235
|
+
},
|
|
4236
|
+
anonymous() {
|
|
4237
|
+
coverage.hit("identity.anonymous");
|
|
4238
|
+
}
|
|
4239
|
+
});
|
|
4240
|
+
const observe = (id) => coverage.hit(id);
|
|
2504
4241
|
const directory = new Directory(seed);
|
|
2505
4242
|
const webhooks = new WebhookDispatcher(testkit, seed, seed.webhooks, options.webhooks);
|
|
2506
|
-
|
|
4243
|
+
webhooks.observe = observe;
|
|
4244
|
+
const auth = new AuthorizationServer(testkit, seed, (type, user) => webhooks.emitForUser(type, user), directory, observe);
|
|
2507
4245
|
const management = new ManagementApi(testkit, directory, webhooks);
|
|
2508
4246
|
const account = new AccountApi(testkit, directory);
|
|
2509
4247
|
const reset = () => {
|
|
@@ -2512,7 +4250,23 @@ async function startKindeTestkit(options = {}) {
|
|
|
2512
4250
|
webhooks.reset();
|
|
2513
4251
|
directory.restore();
|
|
2514
4252
|
};
|
|
2515
|
-
|
|
4253
|
+
const loadSeed = (input) => {
|
|
4254
|
+
const next = resolveSeed(input);
|
|
4255
|
+
directory.load(next);
|
|
4256
|
+
webhooks.replaceSeededEndpoints(next.webhooks);
|
|
4257
|
+
reset();
|
|
4258
|
+
};
|
|
4259
|
+
let closed = false;
|
|
4260
|
+
const close = () => new Promise((resolve4, reject) => {
|
|
4261
|
+
if (closed) return resolve4();
|
|
4262
|
+
closed = true;
|
|
4263
|
+
if (options.coverage) {
|
|
4264
|
+
coverage.write(typeof options.coverage === "object" ? options.coverage.directory : DEFAULT_COVERAGE_DIRECTORY);
|
|
4265
|
+
}
|
|
4266
|
+
server.closeAllConnections();
|
|
4267
|
+
server.close((error) => error ? reject(error) : resolve4());
|
|
4268
|
+
});
|
|
4269
|
+
ready({ testkit, auth, seed, failures, webhooks, management, account, reset, coverage, activity, directory, loadSeed, close });
|
|
2516
4270
|
return {
|
|
2517
4271
|
url,
|
|
2518
4272
|
issuer: testkit.issuer,
|
|
@@ -2524,23 +4278,37 @@ async function startKindeTestkit(options = {}) {
|
|
|
2524
4278
|
webhooks,
|
|
2525
4279
|
directory,
|
|
2526
4280
|
certificatePath: certificate?.certPath ?? null,
|
|
4281
|
+
coverage,
|
|
4282
|
+
activity,
|
|
4283
|
+
loadSeed,
|
|
2527
4284
|
reset,
|
|
2528
|
-
close
|
|
2529
|
-
server.closeAllConnections();
|
|
2530
|
-
server.close((error) => error ? reject(error) : resolve2());
|
|
2531
|
-
})
|
|
4285
|
+
close
|
|
2532
4286
|
};
|
|
2533
4287
|
}
|
|
2534
4288
|
async function handle(req, res, context) {
|
|
2535
|
-
const { testkit, auth, seed, failures, webhooks } = context;
|
|
4289
|
+
const { testkit, auth, seed, failures, webhooks, coverage } = context;
|
|
2536
4290
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
2537
4291
|
const { pathname } = url;
|
|
2538
4292
|
const method = req.method ?? "GET";
|
|
2539
|
-
|
|
4293
|
+
const internal = pathname.startsWith("/testkit/") || pathname === "/dashboard" || pathname.startsWith("/dashboard/");
|
|
4294
|
+
let injected = false;
|
|
4295
|
+
if (!internal && pathname !== "/favicon.ico") {
|
|
4296
|
+
const started = Date.now();
|
|
4297
|
+
res.once("close", () => {
|
|
4298
|
+
context.activity.request({ method, path: pathname, query: url.searchParams, status: res.statusCode, durationMs: Date.now() - started, injected });
|
|
4299
|
+
});
|
|
4300
|
+
}
|
|
4301
|
+
if (pathname === "/dashboard" || pathname.startsWith("/dashboard/")) return dashboard(req, res, url, context);
|
|
4302
|
+
if (!internal) {
|
|
2540
4303
|
const failure = failures.take(method, pathname);
|
|
2541
4304
|
if (failure) {
|
|
4305
|
+
injected = true;
|
|
4306
|
+
if (failure.hang) coverage.hit("outage.timeout");
|
|
4307
|
+
else if (failure.status === 429) coverage.hit("outage.rate-limit");
|
|
4308
|
+
else if (failure.status !== null) coverage.hit("outage.error");
|
|
4309
|
+
if (failure.delayMs > 0) coverage.hit("outage.slow");
|
|
2542
4310
|
if (failure.hang) return;
|
|
2543
|
-
if (failure.delayMs > 0) await new Promise((
|
|
4311
|
+
if (failure.delayMs > 0) await new Promise((resolve4) => setTimeout(resolve4, failure.delayMs));
|
|
2544
4312
|
if (failure.status !== null) {
|
|
2545
4313
|
const headers = {};
|
|
2546
4314
|
if (failure.status === 429 || failure.status === 503) headers["retry-after"] = String(failure.retryAfter);
|
|
@@ -2549,8 +4317,15 @@ async function handle(req, res, context) {
|
|
|
2549
4317
|
}
|
|
2550
4318
|
}
|
|
2551
4319
|
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
2552
|
-
if (await context.management.handle(req, res, url, async () => await readJson(req)))
|
|
2553
|
-
|
|
4320
|
+
if (await context.management.handle(req, res, url, async () => await readJson(req))) {
|
|
4321
|
+
if (res.statusCode === 401 || res.statusCode === 403) coverage.hit("api.management-denied");
|
|
4322
|
+
else if (res.statusCode < 400) coverage.hit(method === "GET" ? "api.management-read" : "api.management-write");
|
|
4323
|
+
return;
|
|
4324
|
+
}
|
|
4325
|
+
if (await context.account.handle(req, res, url)) {
|
|
4326
|
+
if (res.statusCode < 400) coverage.hit("api.account");
|
|
4327
|
+
return;
|
|
4328
|
+
}
|
|
2554
4329
|
if (method === "GET" && pathname === "/testkit/portal") {
|
|
2555
4330
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
2556
4331
|
res.end(
|
|
@@ -2607,11 +4382,119 @@ async function handle(req, res, context) {
|
|
|
2607
4382
|
}
|
|
2608
4383
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
2609
4384
|
const body = await readJson(req);
|
|
2610
|
-
|
|
4385
|
+
let accessToken;
|
|
4386
|
+
try {
|
|
4387
|
+
accessToken = await issueToken(testkit, seed, body);
|
|
4388
|
+
} catch (error) {
|
|
4389
|
+
if (error instanceof TestkitError && error.code === "SEED_NO_MEMBERSHIP") coverage.hit("organization.non-member");
|
|
4390
|
+
throw error;
|
|
4391
|
+
}
|
|
2611
4392
|
return sendJson4(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
2612
4393
|
}
|
|
4394
|
+
if (method === "GET" && pathname === "/testkit/coverage") {
|
|
4395
|
+
return sendJson4(res, 200, { report: coverage.report(), snapshot: coverage.snapshot() });
|
|
4396
|
+
}
|
|
4397
|
+
if (method === "DELETE" && pathname === "/testkit/coverage") {
|
|
4398
|
+
coverage.reset();
|
|
4399
|
+
return sendJson4(res, 200, { ok: true });
|
|
4400
|
+
}
|
|
4401
|
+
if (method === "GET" && pathname === "/testkit/requests") return sendJson4(res, 200, context.activity.requests());
|
|
4402
|
+
if (method === "GET" && pathname === "/testkit/tokens") return sendJson4(res, 200, context.activity.tokens());
|
|
4403
|
+
if (method === "POST" && pathname === "/testkit/seed") {
|
|
4404
|
+
const body = await readJson(req);
|
|
4405
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
4406
|
+
throw new TestkitError("SEED_INVALID", "The seed must be a JSON object.");
|
|
4407
|
+
}
|
|
4408
|
+
context.loadSeed(body);
|
|
4409
|
+
return sendJson4(res, 200, {
|
|
4410
|
+
ok: true,
|
|
4411
|
+
users: seed.users.length,
|
|
4412
|
+
organizations: seed.organizations.length,
|
|
4413
|
+
memberships: seed.memberships.length
|
|
4414
|
+
});
|
|
4415
|
+
}
|
|
4416
|
+
if (method === "POST" && pathname === "/testkit/stop") {
|
|
4417
|
+
sendJson4(res, 200, { ok: true });
|
|
4418
|
+
res.once("finish", () => void context.close().catch(() => void 0));
|
|
4419
|
+
return;
|
|
4420
|
+
}
|
|
2613
4421
|
return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
2614
4422
|
}
|
|
4423
|
+
async function dashboard(req, res, url, context) {
|
|
4424
|
+
const method = req.method ?? "GET";
|
|
4425
|
+
const { pathname } = url;
|
|
4426
|
+
if (method === "GET" && pathname === "/dashboard") {
|
|
4427
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
4428
|
+
res.end(
|
|
4429
|
+
renderDashboard({
|
|
4430
|
+
issuer: context.testkit.issuer,
|
|
4431
|
+
seed: context.seed,
|
|
4432
|
+
suspended: (id) => context.directory.isSuspended(id),
|
|
4433
|
+
signIns: (id) => {
|
|
4434
|
+
const user = context.directory.user(id);
|
|
4435
|
+
return user ? context.directory.meta(user).totalSignIns : 0;
|
|
4436
|
+
},
|
|
4437
|
+
tokens: context.activity.tokens(),
|
|
4438
|
+
requests: context.activity.requests(),
|
|
4439
|
+
deliveries: context.webhooks.deliveries(),
|
|
4440
|
+
endpoints: context.webhooks.listEndpoints(),
|
|
4441
|
+
failures: context.failures.list(),
|
|
4442
|
+
coverage: context.coverage.report(),
|
|
4443
|
+
webhookTypes: WEBHOOK_EVENT_TYPES,
|
|
4444
|
+
live: url.searchParams.has("live"),
|
|
4445
|
+
notice: url.searchParams.get("notice")
|
|
4446
|
+
})
|
|
4447
|
+
);
|
|
4448
|
+
return;
|
|
4449
|
+
}
|
|
4450
|
+
if (method !== "POST") return sendJson4(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
4451
|
+
const origin = req.headers.origin;
|
|
4452
|
+
if (origin && origin !== "null" && new URL(origin).host !== req.headers.host) {
|
|
4453
|
+
return sendJson4(res, 403, { error: "forbidden", error_description: "Dashboard actions only work from the dashboard page." });
|
|
4454
|
+
}
|
|
4455
|
+
const form2 = Object.fromEntries(new URLSearchParams(await readText(req)));
|
|
4456
|
+
let notice = "Done.";
|
|
4457
|
+
try {
|
|
4458
|
+
if (pathname === "/dashboard/reset") {
|
|
4459
|
+
context.reset();
|
|
4460
|
+
notice = "Reset sign-in sessions, failure rules, webhook deliveries, runtime endpoints and Management API changes.";
|
|
4461
|
+
} else if (pathname === "/dashboard/coverage/reset") {
|
|
4462
|
+
context.coverage.reset();
|
|
4463
|
+
notice = "Cleared coverage.";
|
|
4464
|
+
} else if (pathname === "/dashboard/failures/clear") {
|
|
4465
|
+
context.failures.clear();
|
|
4466
|
+
notice = "Removed every failure rule.";
|
|
4467
|
+
} else if (pathname === "/dashboard/failures") {
|
|
4468
|
+
const rule = { path: form2.path ?? "" };
|
|
4469
|
+
if (form2.method) rule.method = form2.method;
|
|
4470
|
+
if (form2.status) rule.status = Number(form2.status);
|
|
4471
|
+
if (form2.delayMs) rule.delayMs = Number(form2.delayMs);
|
|
4472
|
+
if (form2.times) rule.times = Number(form2.times);
|
|
4473
|
+
if (form2.hang) rule.hang = true;
|
|
4474
|
+
const added = context.failures.add(rule);
|
|
4475
|
+
notice = `Added ${added.id} for ${added.path}.`;
|
|
4476
|
+
} else if (pathname.startsWith("/dashboard/failures/") && pathname.endsWith("/remove")) {
|
|
4477
|
+
const id = decodeURIComponent(pathname.slice("/dashboard/failures/".length, -"/remove".length));
|
|
4478
|
+
notice = context.failures.remove(id) ? `Removed ${id}.` : `${id} was already gone.`;
|
|
4479
|
+
} else if (pathname === "/dashboard/webhooks") {
|
|
4480
|
+
const deliveries = await context.webhooks.send({
|
|
4481
|
+
type: form2.type ?? "",
|
|
4482
|
+
user: form2.user || void 0,
|
|
4483
|
+
invalid: form2.invalid || void 0,
|
|
4484
|
+
duplicate: form2.duplicate ? Number(form2.duplicate) : void 0
|
|
4485
|
+
});
|
|
4486
|
+
const delivered = deliveries.filter((d) => d.delivered).length;
|
|
4487
|
+
notice = `Sent ${form2.type}: ${delivered} of ${deliveries.length} deliveries got a 200.`;
|
|
4488
|
+
} else {
|
|
4489
|
+
return sendJson4(res, 404, { error: "not_found", error_description: `POST ${pathname} does not exist.` });
|
|
4490
|
+
}
|
|
4491
|
+
} catch (error) {
|
|
4492
|
+
notice = error.message.replace(/\s+/g, " ").trim();
|
|
4493
|
+
}
|
|
4494
|
+
const anchor = pathname.includes("failures") ? "#failures" : pathname.includes("webhooks") ? "#webhooks" : pathname.includes("coverage") ? "#coverage" : "";
|
|
4495
|
+
res.writeHead(303, { location: `/dashboard?notice=${encodeURIComponent(notice)}${anchor}` });
|
|
4496
|
+
res.end();
|
|
4497
|
+
}
|
|
2615
4498
|
function discovery(testkit) {
|
|
2616
4499
|
const base = testkit.issuer;
|
|
2617
4500
|
return {
|
|
@@ -2637,9 +4520,9 @@ async function issueToken(testkit, seed, body) {
|
|
|
2637
4520
|
throw new TestkitError("INVALID_REQUEST", "The request body must be a JSON object.");
|
|
2638
4521
|
}
|
|
2639
4522
|
const input = body;
|
|
2640
|
-
const
|
|
2641
|
-
if (
|
|
2642
|
-
throw new TestkitError("INVALID_REQUEST", `"${
|
|
4523
|
+
const invalid3 = optionalString(input, "invalid");
|
|
4524
|
+
if (invalid3 !== void 0 && !INVALID_TOKEN_KINDS.includes(invalid3)) {
|
|
4525
|
+
throw new TestkitError("INVALID_REQUEST", `"${invalid3}" is not a known invalid token kind.`, [
|
|
2643
4526
|
`Use one of: ${INVALID_TOKEN_KINDS.join(", ")}`
|
|
2644
4527
|
]);
|
|
2645
4528
|
}
|
|
@@ -2656,7 +4539,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
2656
4539
|
audience: optionalStrings(input, "audience") ?? app?.audience ?? void 0,
|
|
2657
4540
|
permissions: optionalStrings(input, "permissions") ?? app?.permissions ?? void 0,
|
|
2658
4541
|
expiresIn,
|
|
2659
|
-
invalid:
|
|
4542
|
+
invalid: invalid3
|
|
2660
4543
|
});
|
|
2661
4544
|
}
|
|
2662
4545
|
const permissions = optionalStrings(input, "permissions");
|
|
@@ -2671,7 +4554,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
2671
4554
|
if (roles) scenario2.roles = roles;
|
|
2672
4555
|
return await testkit.tokenFor(scenario2, {
|
|
2673
4556
|
expiresIn,
|
|
2674
|
-
invalid:
|
|
4557
|
+
invalid: invalid3,
|
|
2675
4558
|
featureFlags: featureFlagsFor(seed, scenario2.organization?.code ?? null)
|
|
2676
4559
|
});
|
|
2677
4560
|
}
|
|
@@ -2682,7 +4565,7 @@ async function issueToken(testkit, seed, body) {
|
|
|
2682
4565
|
roles,
|
|
2683
4566
|
scopes: optionalStrings(input, "scopes"),
|
|
2684
4567
|
expiresIn,
|
|
2685
|
-
invalid:
|
|
4568
|
+
invalid: invalid3
|
|
2686
4569
|
};
|
|
2687
4570
|
if (typeof input.claims === "object" && input.claims !== null) {
|
|
2688
4571
|
options.claims = input.claims;
|
|
@@ -2752,7 +4635,7 @@ function sendError(res, error) {
|
|
|
2752
4635
|
return;
|
|
2753
4636
|
}
|
|
2754
4637
|
if (error instanceof TestkitError) {
|
|
2755
|
-
sendJson4(res, 400, { error: error.code, error_description: error.
|
|
4638
|
+
sendJson4(res, 400, { error: error.code, error_description: error.summary, details: error.details });
|
|
2756
4639
|
return;
|
|
2757
4640
|
}
|
|
2758
4641
|
sendJson4(res, 500, {
|
|
@@ -2762,7 +4645,6 @@ function sendError(res, error) {
|
|
|
2762
4645
|
}
|
|
2763
4646
|
|
|
2764
4647
|
// src/inspect.ts
|
|
2765
|
-
var import_jose2 = require("jose");
|
|
2766
4648
|
async function inspectToken(token, options = {}) {
|
|
2767
4649
|
const checks = [];
|
|
2768
4650
|
const trimmed = token.trim();
|
|
@@ -2773,8 +4655,8 @@ async function inspectToken(token, options = {}) {
|
|
|
2773
4655
|
return { kind: "unknown", header, payload, checks };
|
|
2774
4656
|
}
|
|
2775
4657
|
try {
|
|
2776
|
-
header =
|
|
2777
|
-
payload =
|
|
4658
|
+
header = decodeProtectedHeader(trimmed);
|
|
4659
|
+
payload = decodeJwt(trimmed);
|
|
2778
4660
|
} catch {
|
|
2779
4661
|
checks.push({ name: "Format", status: "fail", detail: "The header or payload is not valid base64url JSON." });
|
|
2780
4662
|
return { kind: "unknown", header, payload, checks };
|
|
@@ -2804,7 +4686,7 @@ async function inspectToken(token, options = {}) {
|
|
|
2804
4686
|
checks.push({ name: "Issuer", status: "pass", detail: `Issued by ${issuer}.` });
|
|
2805
4687
|
}
|
|
2806
4688
|
try {
|
|
2807
|
-
await
|
|
4689
|
+
await jwtVerify(trimmed, createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`)), { algorithms: ["RS256"] });
|
|
2808
4690
|
checks.push({ name: "Signature", status: "pass", detail: `Verified against ${issuer}/.well-known/jwks.json.` });
|
|
2809
4691
|
} catch (error) {
|
|
2810
4692
|
const code = error.code ?? "";
|
|
@@ -2919,7 +4801,7 @@ async function runDoctor(options) {
|
|
|
2919
4801
|
} else {
|
|
2920
4802
|
checks.push({ name: "KINDE_SITE_URL", status: "pass", detail: `${site}.` });
|
|
2921
4803
|
}
|
|
2922
|
-
return { url, checks, ok: checks.every((
|
|
4804
|
+
return { url, checks, ok: checks.every((check2) => check2.status !== "fail") };
|
|
2923
4805
|
}
|
|
2924
4806
|
function parseEnvFile(text) {
|
|
2925
4807
|
const values = {};
|
|
@@ -2936,14 +4818,65 @@ function parseEnvFile(text) {
|
|
|
2936
4818
|
}
|
|
2937
4819
|
return values;
|
|
2938
4820
|
}
|
|
4821
|
+
|
|
4822
|
+
// src/handle.ts
|
|
4823
|
+
async function kindeTest(options) {
|
|
4824
|
+
const testkit = options.testkit ?? await getDefaultTestkit();
|
|
4825
|
+
const token = await testkit.tokenFor(options.scenario, options.token);
|
|
4826
|
+
const headers = token ? { authorization: `Bearer ${token}` } : {};
|
|
4827
|
+
return {
|
|
4828
|
+
token,
|
|
4829
|
+
headers,
|
|
4830
|
+
principal: testkit.principalFor(options.scenario),
|
|
4831
|
+
request: { headers }
|
|
4832
|
+
};
|
|
4833
|
+
}
|
|
4834
|
+
|
|
4835
|
+
// src/sign-in-flow.ts
|
|
4836
|
+
function appLoginUrl(loginPath, options) {
|
|
4837
|
+
const params = new URLSearchParams({ login_hint: options.user });
|
|
4838
|
+
if (options.org) params.set("org_code", options.org);
|
|
4839
|
+
return `${loginPath}${loginPath.includes("?") ? "&" : "?"}${params}`;
|
|
4840
|
+
}
|
|
4841
|
+
function readSignInRequest(html) {
|
|
4842
|
+
const match = /name="request" value="([^"]+)"/.exec(html);
|
|
4843
|
+
if (!match) {
|
|
4844
|
+
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.");
|
|
4845
|
+
}
|
|
4846
|
+
return decodeEntities(match[1]);
|
|
4847
|
+
}
|
|
4848
|
+
function signInForm(request, options) {
|
|
4849
|
+
const form2 = { request, email: options.user };
|
|
4850
|
+
if (options.org) form2.org = options.org;
|
|
4851
|
+
return form2;
|
|
4852
|
+
}
|
|
4853
|
+
function signInFailure(status, html, options) {
|
|
4854
|
+
if (status === 200 && html.includes("Choose an organization")) {
|
|
4855
|
+
return new Error(`${options.user} belongs to more than one organization. Pass one with { org: "org_..." }.`);
|
|
4856
|
+
}
|
|
4857
|
+
const alert = /role="alert"[^>]*>([\s\S]*?)<\//.exec(html)?.[1];
|
|
4858
|
+
const text = alert ? decodeEntities(alert.replace(/<[^>]+>/g, "")).trim() : `the sign-in page answered ${status}`;
|
|
4859
|
+
return new Error(`kinde-testkit refused the sign-in: ${text}`);
|
|
4860
|
+
}
|
|
4861
|
+
function resolveLocation(location, from) {
|
|
4862
|
+
return new URL(location, from).toString();
|
|
4863
|
+
}
|
|
4864
|
+
function decodeEntities(value) {
|
|
4865
|
+
return value.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
4866
|
+
}
|
|
2939
4867
|
// Annotate the CommonJS export names for ESM import in node:
|
|
2940
4868
|
0 && (module.exports = {
|
|
4869
|
+
ActivityLog,
|
|
2941
4870
|
BILLING_EVENT_TYPES,
|
|
4871
|
+
COVERAGE_GROUPS,
|
|
4872
|
+
CoverageRecorder,
|
|
2942
4873
|
DEFAULT_AUTH_METHODS,
|
|
2943
4874
|
DEFAULT_CLIENT_ID,
|
|
4875
|
+
DEFAULT_COVERAGE_DIRECTORY,
|
|
2944
4876
|
DEFAULT_ISSUER,
|
|
2945
4877
|
DEFAULT_M2M_CLIENT_ID,
|
|
2946
4878
|
DEFAULT_SCOPES,
|
|
4879
|
+
DEFAULT_SEED_FILES,
|
|
2947
4880
|
Directory,
|
|
2948
4881
|
FailureInjector,
|
|
2949
4882
|
INVALID_TOKEN_KINDS,
|
|
@@ -2952,23 +4885,35 @@ function parseEnvFile(text) {
|
|
|
2952
4885
|
TestkitError,
|
|
2953
4886
|
WEBHOOK_EVENT_TYPES,
|
|
2954
4887
|
WebhookDispatcher,
|
|
4888
|
+
appLoginUrl,
|
|
4889
|
+
buildReport,
|
|
4890
|
+
clearCoverageDirectory,
|
|
2955
4891
|
createKindeOrganization,
|
|
2956
4892
|
createKindeToken,
|
|
2957
4893
|
createKindeUser,
|
|
2958
4894
|
createLocalCertificate,
|
|
2959
4895
|
createMembership,
|
|
2960
4896
|
ensureLocalCertificate,
|
|
4897
|
+
findSeedFile,
|
|
4898
|
+
formatCoverageReport,
|
|
2961
4899
|
getDefaultTestkit,
|
|
2962
4900
|
inspectToken,
|
|
2963
4901
|
isAuthenticated,
|
|
4902
|
+
kindeTest,
|
|
4903
|
+
loadSeedFile,
|
|
4904
|
+
mergeSnapshots,
|
|
2964
4905
|
parseEnvFile,
|
|
2965
4906
|
principalFromClaims,
|
|
4907
|
+
readCoverageDirectory,
|
|
4908
|
+
readSignInRequest,
|
|
2966
4909
|
resetFactories,
|
|
4910
|
+
resolveLocation,
|
|
2967
4911
|
resolveSeed,
|
|
2968
4912
|
runDoctor,
|
|
2969
4913
|
scenario,
|
|
2970
4914
|
seedScenario,
|
|
4915
|
+
signInFailure,
|
|
4916
|
+
signInForm,
|
|
2971
4917
|
startKindeTestkit,
|
|
2972
4918
|
toKindeRole
|
|
2973
4919
|
});
|
|
2974
|
-
//# sourceMappingURL=index.cjs.map
|