kinde-testkit 0.1.0 → 0.2.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 +19 -0
- package/README.md +122 -9
- package/dist/cli.js +501 -37
- package/dist/index.cjs +497 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -8
- package/dist/index.d.ts +15 -8
- package/dist/index.js +499 -36
- package/dist/index.js.map +1 -1
- package/dist/playwright.d.ts +30 -0
- package/dist/playwright.js +68 -0
- package/dist/playwright.js.map +1 -0
- package/dist/vitest.d.ts +14 -7
- package/dist/vitest.js +499 -36
- package/dist/vitest.js.map +1 -1
- package/package.json +22 -5
package/dist/cli.js
CHANGED
|
@@ -34,7 +34,8 @@ import {
|
|
|
34
34
|
base64url,
|
|
35
35
|
calculateJwkThumbprint,
|
|
36
36
|
exportJWK,
|
|
37
|
-
generateKeyPair
|
|
37
|
+
generateKeyPair,
|
|
38
|
+
jwtVerify
|
|
38
39
|
} from "jose";
|
|
39
40
|
|
|
40
41
|
// src/ids.ts
|
|
@@ -161,6 +162,16 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
161
162
|
get keyId() {
|
|
162
163
|
return this.signingKey.kid;
|
|
163
164
|
}
|
|
165
|
+
get accessTokenLifetime() {
|
|
166
|
+
return toSeconds(this.accessTokenExpiresIn);
|
|
167
|
+
}
|
|
168
|
+
async verify(token2) {
|
|
169
|
+
const { payload } = await jwtVerify(token2, this.signingKey.publicKey, {
|
|
170
|
+
issuer: this.issuer,
|
|
171
|
+
algorithms: ["RS256"]
|
|
172
|
+
});
|
|
173
|
+
return payload;
|
|
174
|
+
}
|
|
164
175
|
jwks() {
|
|
165
176
|
return { keys: [{ ...this.signingKey.publicJwk }] };
|
|
166
177
|
}
|
|
@@ -168,9 +179,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
168
179
|
const now = this.clock();
|
|
169
180
|
const payload = {
|
|
170
181
|
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
171
|
-
aud: [...this.audience],
|
|
182
|
+
aud: [...options.audience ?? this.audience],
|
|
172
183
|
auth_time: options.authTime ?? now,
|
|
173
|
-
azp: this.clientId,
|
|
184
|
+
azp: options.clientId ?? this.clientId,
|
|
174
185
|
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
175
186
|
iat: now,
|
|
176
187
|
iss: this.issuer,
|
|
@@ -202,11 +213,12 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
202
213
|
const now = this.clock();
|
|
203
214
|
const authTime = options.authTime ?? now;
|
|
204
215
|
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
216
|
+
const clientId = options.clientId ?? this.clientId;
|
|
205
217
|
const payload = {
|
|
206
218
|
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
207
|
-
aud: [
|
|
219
|
+
aud: [clientId],
|
|
208
220
|
auth_time: authTime,
|
|
209
|
-
azp:
|
|
221
|
+
azp: clientId,
|
|
210
222
|
email: user.email,
|
|
211
223
|
email_verified: user.emailVerified,
|
|
212
224
|
exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
|
|
@@ -216,6 +228,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
216
228
|
iss: this.issuer,
|
|
217
229
|
jti: randomUUID(),
|
|
218
230
|
name: name || null,
|
|
231
|
+
nonce: options.nonce,
|
|
219
232
|
org_codes: organization ? [organization.code] : void 0,
|
|
220
233
|
picture: user.picture,
|
|
221
234
|
rat: authTime,
|
|
@@ -295,7 +308,7 @@ async function createSigningKey(prefix) {
|
|
|
295
308
|
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
|
296
309
|
const jwk = await exportJWK(publicKey);
|
|
297
310
|
const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
|
|
298
|
-
return { kid, privateKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
311
|
+
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
299
312
|
}
|
|
300
313
|
function tamperSignature(jwt) {
|
|
301
314
|
const [header, payload, signature] = jwt.split(".");
|
|
@@ -447,11 +460,445 @@ function isRecord(value) {
|
|
|
447
460
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
448
461
|
}
|
|
449
462
|
|
|
463
|
+
// src/oauth.ts
|
|
464
|
+
import { createHash as createHash2, randomBytes, timingSafeEqual } from "crypto";
|
|
465
|
+
|
|
466
|
+
// src/login-page.ts
|
|
467
|
+
var STYLE = `
|
|
468
|
+
:root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#16161a;--muted:#6b6b76;--line:#e4e4e0;--accent:#16161a;--accent-ink:#fff;--warn:#8a5a00;--warn-bg:#fff6e0}
|
|
469
|
+
@media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1d;--ink:#ececf0;--muted:#9b9ba6;--line:#2c2c31;--accent:#ececf0;--accent-ink:#111113;--warn:#f0c46a;--warn-bg:#2a2210}}
|
|
470
|
+
*{box-sizing:border-box}
|
|
471
|
+
body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--ink);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;padding:24px}
|
|
472
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
473
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
474
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
475
|
+
p{margin:0;color:var(--muted)}
|
|
476
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
477
|
+
form{margin:0}
|
|
478
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
479
|
+
input[type=email]{width:100%;height:42px;padding:0 12px;border-radius:8px;border:1px solid var(--line);background:transparent;color:var(--ink);font:inherit}
|
|
480
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
481
|
+
.primary{margin-top:12px;width:100%;height:42px;border:0;border-radius:8px;background:var(--accent);color:var(--accent-ink);font-family:inherit;font-size:15px;font-weight:600;cursor:pointer}
|
|
482
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
483
|
+
.list{display:grid;gap:8px}
|
|
484
|
+
.option{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;text-align:left;padding:11px 12px;border:1px solid var(--line);border-radius:8px;background:transparent;color:var(--ink);font:inherit;cursor:pointer}
|
|
485
|
+
.option:hover{border-color:var(--muted)}
|
|
486
|
+
.option strong{display:block;font-weight:500}
|
|
487
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
488
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
489
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
490
|
+
`;
|
|
491
|
+
function escapeHtml(value) {
|
|
492
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
493
|
+
}
|
|
494
|
+
function layout(title, body) {
|
|
495
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)}</title><style>${STYLE}</style></head><body><main><div class="brand">kinde-testkit</div>${body}</main></body></html>`;
|
|
496
|
+
}
|
|
497
|
+
function displayName(user) {
|
|
498
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
499
|
+
}
|
|
500
|
+
function renderSignIn(options) {
|
|
501
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
502
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
503
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
504
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
505
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
506
|
+
return `<button class="option" type="submit" name="user" value="${value}"><span><strong>${escapeHtml(displayName(user))}</strong><small>${detail}</small></span><span class="tag">${tag}</span></button>`;
|
|
507
|
+
}).join("");
|
|
508
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
509
|
+
return layout(
|
|
510
|
+
"Sign in",
|
|
511
|
+
`<h1>Sign in</h1><p>Test sign-in. Tokens are signed with a local key and are only valid for this issuer.</p>${orgNote}${options.error ? `<div class="error" role="alert">${escapeHtml(options.error)}</div>` : ""}<form method="post" action="/oauth2/auth/login"><input type="hidden" name="request" value="${escapeHtml(options.request)}"><label for="email">Email</label><input id="email" name="email" type="email" autocomplete="off" value="${escapeHtml(options.loginHint ?? "")}" placeholder="name@example.test"><button class="primary" type="submit">Continue</button>${users ? `<h2>Seeded users</h2><div class="list">${users}</div>` : ""}</form>`
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
function renderOrganizationPicker(options) {
|
|
515
|
+
const choices = options.organizations.map(
|
|
516
|
+
(org) => `<button class="option" type="submit" name="org" value="${escapeHtml(org.code)}"><span><strong>${escapeHtml(org.name)}</strong><small>${escapeHtml(org.code)}</small></span></button>`
|
|
517
|
+
).join("");
|
|
518
|
+
return layout(
|
|
519
|
+
"Choose an organization",
|
|
520
|
+
`<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>`
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
function renderMessage(title, message) {
|
|
524
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// src/oauth.ts
|
|
528
|
+
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
529
|
+
var OAuthError = class extends Error {
|
|
530
|
+
constructor(status, error, description) {
|
|
531
|
+
super(description);
|
|
532
|
+
this.status = status;
|
|
533
|
+
this.error = error;
|
|
534
|
+
}
|
|
535
|
+
status;
|
|
536
|
+
error;
|
|
537
|
+
};
|
|
538
|
+
var AuthorizationServer = class {
|
|
539
|
+
constructor(testkit, seed) {
|
|
540
|
+
this.testkit = testkit;
|
|
541
|
+
this.seed = seed;
|
|
542
|
+
}
|
|
543
|
+
testkit;
|
|
544
|
+
seed;
|
|
545
|
+
codes = /* @__PURE__ */ new Map();
|
|
546
|
+
refreshTokens = /* @__PURE__ */ new Map();
|
|
547
|
+
signedUpUsers = /* @__PURE__ */ new Map();
|
|
548
|
+
async handle(req, res, url, readBody) {
|
|
549
|
+
const method = req.method ?? "GET";
|
|
550
|
+
switch (`${method} ${url.pathname}`) {
|
|
551
|
+
case "GET /oauth2/auth":
|
|
552
|
+
this.authorize(res, url.searchParams);
|
|
553
|
+
return true;
|
|
554
|
+
case "POST /oauth2/auth/login":
|
|
555
|
+
this.login(res, await readBody());
|
|
556
|
+
return true;
|
|
557
|
+
case "POST /oauth2/token":
|
|
558
|
+
await this.token(req, res, await readBody());
|
|
559
|
+
return true;
|
|
560
|
+
case "GET /oauth2/v2/user_profile":
|
|
561
|
+
await this.profile(req, res);
|
|
562
|
+
return true;
|
|
563
|
+
case "POST /oauth2/revoke":
|
|
564
|
+
this.revoke(res, await readBody());
|
|
565
|
+
return true;
|
|
566
|
+
case "GET /logout":
|
|
567
|
+
this.logout(res, url.searchParams);
|
|
568
|
+
return true;
|
|
569
|
+
default:
|
|
570
|
+
return false;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
authorize(res, params) {
|
|
574
|
+
let request2;
|
|
575
|
+
try {
|
|
576
|
+
request2 = parseAuthorizeRequest(params);
|
|
577
|
+
} catch (error) {
|
|
578
|
+
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
579
|
+
}
|
|
580
|
+
if (params.get("prompt") === "none") {
|
|
581
|
+
return redirectWithError(res, request2, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
582
|
+
}
|
|
583
|
+
sendHtml(
|
|
584
|
+
res,
|
|
585
|
+
200,
|
|
586
|
+
renderSignIn({
|
|
587
|
+
request: encodeRequest(request2),
|
|
588
|
+
users: this.loginPageUsers(),
|
|
589
|
+
loginHint: request2.loginHint ?? void 0,
|
|
590
|
+
requiredOrganization: request2.orgCode ?? void 0
|
|
591
|
+
})
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
login(res, form) {
|
|
595
|
+
let request2;
|
|
596
|
+
try {
|
|
597
|
+
request2 = decodeRequest(form.request ?? "");
|
|
598
|
+
} catch {
|
|
599
|
+
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
600
|
+
}
|
|
601
|
+
const encoded = encodeRequest(request2);
|
|
602
|
+
const ref = (form.user || form.email || "").trim();
|
|
603
|
+
if (!ref) {
|
|
604
|
+
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: "Enter an email address or pick a seeded user." }));
|
|
605
|
+
}
|
|
606
|
+
const user = this.resolveUser(ref);
|
|
607
|
+
if (!user) {
|
|
608
|
+
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request2.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
609
|
+
}
|
|
610
|
+
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
611
|
+
const wanted = request2.orgCode ?? form.org ?? null;
|
|
612
|
+
let organizationCode = null;
|
|
613
|
+
if (wanted) {
|
|
614
|
+
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
615
|
+
return sendHtml(
|
|
616
|
+
res,
|
|
617
|
+
403,
|
|
618
|
+
renderSignIn({
|
|
619
|
+
request: encoded,
|
|
620
|
+
users: this.loginPageUsers(),
|
|
621
|
+
requiredOrganization: request2.orgCode ?? void 0,
|
|
622
|
+
error: `${user.email ?? user.id} is not a member of ${wanted}.`
|
|
623
|
+
})
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
organizationCode = wanted;
|
|
627
|
+
} else if (memberships.length === 1) {
|
|
628
|
+
organizationCode = memberships[0].organizationCode;
|
|
629
|
+
} else if (memberships.length > 1) {
|
|
630
|
+
return sendHtml(
|
|
631
|
+
res,
|
|
632
|
+
200,
|
|
633
|
+
renderOrganizationPicker({
|
|
634
|
+
request: encoded,
|
|
635
|
+
user,
|
|
636
|
+
organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
637
|
+
})
|
|
638
|
+
);
|
|
639
|
+
}
|
|
640
|
+
const membership = memberships.find((m) => m.organizationCode === organizationCode);
|
|
641
|
+
const scenario = {
|
|
642
|
+
kind: "authenticated",
|
|
643
|
+
user,
|
|
644
|
+
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
645
|
+
roles: [...membership?.roles ?? []],
|
|
646
|
+
permissions: [...membership?.permissions ?? []],
|
|
647
|
+
claims: {}
|
|
648
|
+
};
|
|
649
|
+
const code = randomToken();
|
|
650
|
+
this.codes.set(code, {
|
|
651
|
+
clientId: request2.clientId,
|
|
652
|
+
redirectUri: request2.redirectUri,
|
|
653
|
+
scenario,
|
|
654
|
+
scope: request2.scope,
|
|
655
|
+
audience: request2.audience,
|
|
656
|
+
nonce: request2.nonce,
|
|
657
|
+
authTime: Math.floor(Date.now() / 1e3),
|
|
658
|
+
codeChallenge: request2.codeChallenge,
|
|
659
|
+
codeChallengeMethod: request2.codeChallengeMethod,
|
|
660
|
+
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
661
|
+
});
|
|
662
|
+
const target = new URL(request2.redirectUri);
|
|
663
|
+
target.searchParams.set("code", code);
|
|
664
|
+
if (request2.state !== null) target.searchParams.set("state", request2.state);
|
|
665
|
+
redirect(res, target.toString());
|
|
666
|
+
}
|
|
667
|
+
async token(req, res, form) {
|
|
668
|
+
try {
|
|
669
|
+
const clientId = clientIdFrom(req, form);
|
|
670
|
+
const grantType = form.grant_type;
|
|
671
|
+
let grant;
|
|
672
|
+
if (grantType === "authorization_code") {
|
|
673
|
+
grant = this.redeemCode(form, clientId);
|
|
674
|
+
} else if (grantType === "refresh_token") {
|
|
675
|
+
grant = this.redeemRefreshToken(form, clientId);
|
|
676
|
+
} else {
|
|
677
|
+
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and refresh_token, not "${grantType ?? ""}".`);
|
|
678
|
+
}
|
|
679
|
+
sendJson(res, 200, await this.issueTokens(grant));
|
|
680
|
+
} catch (error) {
|
|
681
|
+
if (error instanceof OAuthError) {
|
|
682
|
+
return sendJson(res, error.status, { error: error.error, error_description: error.message });
|
|
683
|
+
}
|
|
684
|
+
throw error;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
redeemCode(form, clientId) {
|
|
688
|
+
const code = form.code ?? "";
|
|
689
|
+
const pending = this.codes.get(code);
|
|
690
|
+
this.codes.delete(code);
|
|
691
|
+
if (!pending || pending.expiresAt < Date.now()) {
|
|
692
|
+
throw new OAuthError(400, "invalid_grant", "The authorization code is unknown, expired or already used.");
|
|
693
|
+
}
|
|
694
|
+
if (pending.clientId !== clientId) {
|
|
695
|
+
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
696
|
+
}
|
|
697
|
+
if (form.redirect_uri !== pending.redirectUri) {
|
|
698
|
+
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
699
|
+
}
|
|
700
|
+
if (pending.codeChallenge) {
|
|
701
|
+
const verifier = form.code_verifier ?? "";
|
|
702
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash2("sha256").update(verifier).digest("base64url");
|
|
703
|
+
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
704
|
+
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
return pending;
|
|
708
|
+
}
|
|
709
|
+
redeemRefreshToken(form, clientId) {
|
|
710
|
+
const token2 = form.refresh_token ?? "";
|
|
711
|
+
const grant = this.refreshTokens.get(token2);
|
|
712
|
+
this.refreshTokens.delete(token2);
|
|
713
|
+
if (!grant) {
|
|
714
|
+
throw new OAuthError(400, "invalid_grant", "The refresh token is unknown, revoked or already used.");
|
|
715
|
+
}
|
|
716
|
+
if (grant.clientId !== clientId) {
|
|
717
|
+
throw new OAuthError(400, "invalid_grant", "The refresh token was issued to a different client.");
|
|
718
|
+
}
|
|
719
|
+
return grant;
|
|
720
|
+
}
|
|
721
|
+
async issueTokens(grant) {
|
|
722
|
+
const { scenario } = grant;
|
|
723
|
+
const body = {
|
|
724
|
+
access_token: await this.testkit.token({
|
|
725
|
+
subject: scenario.user.id,
|
|
726
|
+
organizationCode: scenario.organization?.code ?? null,
|
|
727
|
+
roles: scenario.roles.length > 0 ? scenario.roles : void 0,
|
|
728
|
+
permissions: scenario.permissions.length > 0 ? scenario.permissions : void 0,
|
|
729
|
+
scopes: grant.scope,
|
|
730
|
+
clientId: grant.clientId,
|
|
731
|
+
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
732
|
+
authTime: grant.authTime
|
|
733
|
+
}),
|
|
734
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
735
|
+
scope: grant.scope.join(" "),
|
|
736
|
+
token_type: "bearer"
|
|
737
|
+
};
|
|
738
|
+
if (grant.scope.includes("openid")) {
|
|
739
|
+
body.id_token = await this.testkit.idTokenFor(scenario, {
|
|
740
|
+
clientId: grant.clientId,
|
|
741
|
+
nonce: grant.nonce ?? void 0,
|
|
742
|
+
authTime: grant.authTime
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
if (grant.scope.includes("offline")) {
|
|
746
|
+
const refreshToken = randomToken();
|
|
747
|
+
this.refreshTokens.set(refreshToken, { ...grant, nonce: null });
|
|
748
|
+
body.refresh_token = refreshToken;
|
|
749
|
+
}
|
|
750
|
+
return body;
|
|
751
|
+
}
|
|
752
|
+
async profile(req, res) {
|
|
753
|
+
const header = req.headers.authorization ?? "";
|
|
754
|
+
if (!header.startsWith("Bearer ")) {
|
|
755
|
+
return sendJson(res, 401, { error: "invalid_token", error_description: "Send the access token as a Bearer token." });
|
|
756
|
+
}
|
|
757
|
+
let sub;
|
|
758
|
+
try {
|
|
759
|
+
sub = String((await this.testkit.verify(header.slice(7))).sub ?? "");
|
|
760
|
+
} catch {
|
|
761
|
+
return sendJson(res, 401, { error: "invalid_token", error_description: "The access token is not valid for this issuer." });
|
|
762
|
+
}
|
|
763
|
+
const user = this.seed.users.find((u) => u.id === sub) ?? this.signedUpUsers.get(sub);
|
|
764
|
+
if (!user) {
|
|
765
|
+
return sendJson(res, 404, { error: "not_found", error_description: `No user has the id ${sub}.` });
|
|
766
|
+
}
|
|
767
|
+
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
768
|
+
sendJson(res, 200, {
|
|
769
|
+
id: user.id,
|
|
770
|
+
sub: user.id,
|
|
771
|
+
provided_id: null,
|
|
772
|
+
name: name || null,
|
|
773
|
+
given_name: user.givenName,
|
|
774
|
+
family_name: user.familyName,
|
|
775
|
+
updated_at: Math.floor(Date.now() / 1e3),
|
|
776
|
+
email: user.email,
|
|
777
|
+
email_verified: user.emailVerified,
|
|
778
|
+
picture: user.picture,
|
|
779
|
+
preferred_username: null,
|
|
780
|
+
phone: null
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
revoke(res, form) {
|
|
784
|
+
if (form.token) this.refreshTokens.delete(form.token);
|
|
785
|
+
sendJson(res, 200, {});
|
|
786
|
+
}
|
|
787
|
+
logout(res, params) {
|
|
788
|
+
const target = params.get("redirect");
|
|
789
|
+
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
790
|
+
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
791
|
+
}
|
|
792
|
+
resolveUser(ref) {
|
|
793
|
+
const seeded = findUser(this.seed.users, ref);
|
|
794
|
+
if (seeded) return seeded;
|
|
795
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
796
|
+
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
797
|
+
this.signedUpUsers.set(user.id, user);
|
|
798
|
+
return user;
|
|
799
|
+
}
|
|
800
|
+
organization(code) {
|
|
801
|
+
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
802
|
+
}
|
|
803
|
+
loginPageUsers() {
|
|
804
|
+
return this.seed.users.map((user) => ({
|
|
805
|
+
user,
|
|
806
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
807
|
+
}));
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
function parseAuthorizeRequest(params) {
|
|
811
|
+
const clientId = params.get("client_id");
|
|
812
|
+
const redirectUri = params.get("redirect_uri");
|
|
813
|
+
if (!clientId) throw new Error("client_id is missing.");
|
|
814
|
+
if (!redirectUri || !isHttpUrl(redirectUri)) {
|
|
815
|
+
throw new Error("redirect_uri must be an absolute http or https URL.");
|
|
816
|
+
}
|
|
817
|
+
if (params.get("response_type") !== "code") {
|
|
818
|
+
throw new Error('response_type must be "code".');
|
|
819
|
+
}
|
|
820
|
+
const method = params.get("code_challenge_method");
|
|
821
|
+
const challenge = params.get("code_challenge");
|
|
822
|
+
if (challenge && method && method !== "S256" && method !== "plain") {
|
|
823
|
+
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
824
|
+
}
|
|
825
|
+
return {
|
|
826
|
+
clientId,
|
|
827
|
+
redirectUri,
|
|
828
|
+
state: params.get("state"),
|
|
829
|
+
scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
|
|
830
|
+
nonce: params.get("nonce"),
|
|
831
|
+
audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
|
|
832
|
+
orgCode: params.get("org_code"),
|
|
833
|
+
loginHint: params.get("login_hint"),
|
|
834
|
+
codeChallenge: challenge,
|
|
835
|
+
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
function encodeRequest(request2) {
|
|
839
|
+
return Buffer.from(JSON.stringify(request2)).toString("base64url");
|
|
840
|
+
}
|
|
841
|
+
function decodeRequest(value) {
|
|
842
|
+
const request2 = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
843
|
+
if (!request2.clientId || !request2.redirectUri || !isHttpUrl(request2.redirectUri)) {
|
|
844
|
+
throw new Error("invalid request");
|
|
845
|
+
}
|
|
846
|
+
return request2;
|
|
847
|
+
}
|
|
848
|
+
function clientIdFrom(req, form) {
|
|
849
|
+
const header = req.headers.authorization ?? "";
|
|
850
|
+
if (header.startsWith("Basic ")) {
|
|
851
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
852
|
+
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
853
|
+
if (id) return id;
|
|
854
|
+
}
|
|
855
|
+
if (form.client_id) return form.client_id;
|
|
856
|
+
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
857
|
+
}
|
|
858
|
+
function redirectWithError(res, request2, error, description) {
|
|
859
|
+
const target = new URL(request2.redirectUri);
|
|
860
|
+
target.searchParams.set("error", error);
|
|
861
|
+
target.searchParams.set("error_description", description);
|
|
862
|
+
if (request2.state !== null) target.searchParams.set("state", request2.state);
|
|
863
|
+
redirect(res, target.toString());
|
|
864
|
+
}
|
|
865
|
+
function isHttpUrl(value) {
|
|
866
|
+
try {
|
|
867
|
+
const { protocol } = new URL(value);
|
|
868
|
+
return protocol === "http:" || protocol === "https:";
|
|
869
|
+
} catch {
|
|
870
|
+
return false;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
function randomToken() {
|
|
874
|
+
return randomBytes(32).toString("base64url");
|
|
875
|
+
}
|
|
876
|
+
function safeEqual(a, b) {
|
|
877
|
+
const left = Buffer.from(a);
|
|
878
|
+
const right = Buffer.from(b);
|
|
879
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
880
|
+
}
|
|
881
|
+
function redirect(res, location) {
|
|
882
|
+
res.writeHead(303, { location, "cache-control": "no-store" });
|
|
883
|
+
res.end();
|
|
884
|
+
}
|
|
885
|
+
function sendHtml(res, status, html) {
|
|
886
|
+
res.writeHead(status, {
|
|
887
|
+
"content-type": "text/html; charset=utf-8",
|
|
888
|
+
"cache-control": "no-store",
|
|
889
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
890
|
+
});
|
|
891
|
+
res.end(html);
|
|
892
|
+
}
|
|
893
|
+
function sendJson(res, status, body) {
|
|
894
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
895
|
+
res.end(JSON.stringify(body));
|
|
896
|
+
}
|
|
897
|
+
|
|
450
898
|
// src/server.ts
|
|
451
899
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
452
900
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
453
901
|
var JWKS_PATHS = /* @__PURE__ */ new Set(["/.well-known/jwks", "/.well-known/jwks.json"]);
|
|
454
|
-
var NOT_IMPLEMENTED = /* @__PURE__ */ new Set(["/oauth2/auth", "/oauth2/token", "/oauth2/v2/user_profile", "/logout"]);
|
|
455
902
|
async function startKindeTestkit(options = {}) {
|
|
456
903
|
const host = options.host ?? "127.0.0.1";
|
|
457
904
|
if (!LOOPBACK_HOSTS.has(host) && !options.allowPublic) {
|
|
@@ -462,9 +909,11 @@ async function startKindeTestkit(options = {}) {
|
|
|
462
909
|
}
|
|
463
910
|
const seed = resolveSeed(options.seed ?? {});
|
|
464
911
|
let ready;
|
|
465
|
-
const testkitReady = new Promise(
|
|
912
|
+
const testkitReady = new Promise(
|
|
913
|
+
(resolve2) => ready = resolve2
|
|
914
|
+
);
|
|
466
915
|
const server = createServer((req, res) => {
|
|
467
|
-
testkitReady.then((testkit2) => handle(req, res, testkit2, seed)).catch((error) => sendError(res, error));
|
|
916
|
+
testkitReady.then(({ testkit: testkit2, auth }) => handle(req, res, testkit2, auth, seed)).catch((error) => sendError(res, error));
|
|
468
917
|
});
|
|
469
918
|
await new Promise((resolve2, reject) => {
|
|
470
919
|
server.once("error", reject);
|
|
@@ -478,7 +927,7 @@ async function startKindeTestkit(options = {}) {
|
|
|
478
927
|
audience: options.audience ?? options.seed?.audience,
|
|
479
928
|
clientId: options.clientId ?? options.seed?.clientId
|
|
480
929
|
});
|
|
481
|
-
ready(testkit);
|
|
930
|
+
ready({ testkit, auth: new AuthorizationServer(testkit, seed) });
|
|
482
931
|
return {
|
|
483
932
|
url,
|
|
484
933
|
issuer: testkit.issuer,
|
|
@@ -492,37 +941,33 @@ async function startKindeTestkit(options = {}) {
|
|
|
492
941
|
})
|
|
493
942
|
};
|
|
494
943
|
}
|
|
495
|
-
async function handle(req, res, testkit, seed) {
|
|
496
|
-
const
|
|
944
|
+
async function handle(req, res, testkit, auth, seed) {
|
|
945
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
946
|
+
const { pathname } = url;
|
|
497
947
|
const method = req.method ?? "GET";
|
|
948
|
+
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
498
949
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
499
|
-
return
|
|
950
|
+
return sendJson2(res, 200, discovery(testkit));
|
|
500
951
|
}
|
|
501
952
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
502
|
-
return
|
|
953
|
+
return sendJson2(res, 200, testkit.jwks());
|
|
503
954
|
}
|
|
504
955
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
505
|
-
return
|
|
956
|
+
return sendJson2(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
506
957
|
}
|
|
507
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
958
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson2(res, 200, seed.users);
|
|
508
959
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
509
|
-
return
|
|
960
|
+
return sendJson2(res, 200, seed.organizations);
|
|
510
961
|
}
|
|
511
962
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
512
|
-
return
|
|
963
|
+
return sendJson2(res, 200, seed.memberships);
|
|
513
964
|
}
|
|
514
965
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
515
966
|
const body = await readJson(req);
|
|
516
967
|
const accessToken = await issueToken(testkit, seed, body);
|
|
517
|
-
return
|
|
518
|
-
}
|
|
519
|
-
if (NOT_IMPLEMENTED.has(pathname)) {
|
|
520
|
-
return sendJson(res, 501, {
|
|
521
|
-
error: "not_implemented",
|
|
522
|
-
error_description: `${pathname} is not part of this kinde-testkit release. Use POST /testkit/token to mint tokens.`
|
|
523
|
-
});
|
|
968
|
+
return sendJson2(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
524
969
|
}
|
|
525
|
-
return
|
|
970
|
+
return sendJson2(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
526
971
|
}
|
|
527
972
|
function discovery(testkit) {
|
|
528
973
|
const base = testkit.issuer;
|
|
@@ -532,8 +977,11 @@ function discovery(testkit) {
|
|
|
532
977
|
token_endpoint: `${base}/oauth2/token`,
|
|
533
978
|
userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
|
|
534
979
|
end_session_endpoint: `${base}/logout`,
|
|
980
|
+
revocation_endpoint: `${base}/oauth2/revoke`,
|
|
535
981
|
jwks_uri: `${base}/.well-known/jwks`,
|
|
536
982
|
response_types_supported: ["code"],
|
|
983
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
984
|
+
code_challenge_methods_supported: ["S256", "plain"],
|
|
537
985
|
subject_types_supported: ["public"],
|
|
538
986
|
id_token_signing_alg_values_supported: ["RS256"],
|
|
539
987
|
scopes_supported: ["openid", "profile", "email", "offline"],
|
|
@@ -595,7 +1043,28 @@ function optionalStrings(input, field) {
|
|
|
595
1043
|
}
|
|
596
1044
|
return value;
|
|
597
1045
|
}
|
|
1046
|
+
async function readForm(req) {
|
|
1047
|
+
const text = await readText(req);
|
|
1048
|
+
if ((req.headers["content-type"] ?? "").includes("application/json")) {
|
|
1049
|
+
try {
|
|
1050
|
+
const parsed = JSON.parse(text || "{}");
|
|
1051
|
+
return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));
|
|
1052
|
+
} catch {
|
|
1053
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
1057
|
+
}
|
|
598
1058
|
async function readJson(req) {
|
|
1059
|
+
const text = await readText(req);
|
|
1060
|
+
if (text.length === 0) return {};
|
|
1061
|
+
try {
|
|
1062
|
+
return JSON.parse(text);
|
|
1063
|
+
} catch {
|
|
1064
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
async function readText(req) {
|
|
599
1068
|
const chunks = [];
|
|
600
1069
|
let size = 0;
|
|
601
1070
|
for await (const chunk of req) {
|
|
@@ -605,15 +1074,9 @@ async function readJson(req) {
|
|
|
605
1074
|
}
|
|
606
1075
|
chunks.push(chunk);
|
|
607
1076
|
}
|
|
608
|
-
|
|
609
|
-
if (text.length === 0) return {};
|
|
610
|
-
try {
|
|
611
|
-
return JSON.parse(text);
|
|
612
|
-
} catch {
|
|
613
|
-
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
614
|
-
}
|
|
1077
|
+
return Buffer.concat(chunks).toString("utf8").trim();
|
|
615
1078
|
}
|
|
616
|
-
function
|
|
1079
|
+
function sendJson2(res, status, body) {
|
|
617
1080
|
res.writeHead(status, {
|
|
618
1081
|
"content-type": "application/json; charset=utf-8",
|
|
619
1082
|
"cache-control": "no-store"
|
|
@@ -626,10 +1089,10 @@ function sendError(res, error) {
|
|
|
626
1089
|
return;
|
|
627
1090
|
}
|
|
628
1091
|
if (error instanceof TestkitError) {
|
|
629
|
-
|
|
1092
|
+
sendJson2(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
630
1093
|
return;
|
|
631
1094
|
}
|
|
632
|
-
|
|
1095
|
+
sendJson2(res, 500, {
|
|
633
1096
|
error: "server_error",
|
|
634
1097
|
error_description: error instanceof Error ? error.message : String(error)
|
|
635
1098
|
});
|
|
@@ -638,7 +1101,7 @@ function sendError(res, error) {
|
|
|
638
1101
|
// src/cli.ts
|
|
639
1102
|
var DEFAULT_URL = process.env.KINDE_TESTKIT_URL ?? "http://localhost:4400";
|
|
640
1103
|
var DEFAULT_SEED_FILE = "kinde-testkit.json";
|
|
641
|
-
var HELP = `kinde-testkit: a local issuer for testing
|
|
1104
|
+
var HELP = `kinde-testkit: a local Kinde issuer for testing apps
|
|
642
1105
|
|
|
643
1106
|
Usage
|
|
644
1107
|
kinde-testkit start [options] Start the local issuer
|
|
@@ -738,6 +1201,7 @@ async function start(args) {
|
|
|
738
1201
|
`Issuer: ${running.issuer}`,
|
|
739
1202
|
`Discovery: ${running.discoveryUrl}`,
|
|
740
1203
|
`JWKS: ${running.jwksUri}`,
|
|
1204
|
+
`Sign-in page: ${running.url}/oauth2/auth`,
|
|
741
1205
|
`Token: POST ${running.url}/testkit/token`,
|
|
742
1206
|
"",
|
|
743
1207
|
`Seed: ${seedPath ? resolve(seedPath) : "none"}`,
|