kinde-testkit 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +119 -8
- 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 +19 -5
package/dist/index.js
CHANGED
|
@@ -124,7 +124,8 @@ import {
|
|
|
124
124
|
base64url,
|
|
125
125
|
calculateJwkThumbprint,
|
|
126
126
|
exportJWK,
|
|
127
|
-
generateKeyPair
|
|
127
|
+
generateKeyPair,
|
|
128
|
+
jwtVerify
|
|
128
129
|
} from "jose";
|
|
129
130
|
|
|
130
131
|
// src/errors.ts
|
|
@@ -214,6 +215,16 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
214
215
|
get keyId() {
|
|
215
216
|
return this.signingKey.kid;
|
|
216
217
|
}
|
|
218
|
+
get accessTokenLifetime() {
|
|
219
|
+
return toSeconds(this.accessTokenExpiresIn);
|
|
220
|
+
}
|
|
221
|
+
async verify(token) {
|
|
222
|
+
const { payload } = await jwtVerify(token, this.signingKey.publicKey, {
|
|
223
|
+
issuer: this.issuer,
|
|
224
|
+
algorithms: ["RS256"]
|
|
225
|
+
});
|
|
226
|
+
return payload;
|
|
227
|
+
}
|
|
217
228
|
jwks() {
|
|
218
229
|
return { keys: [{ ...this.signingKey.publicJwk }] };
|
|
219
230
|
}
|
|
@@ -221,9 +232,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
221
232
|
const now = this.clock();
|
|
222
233
|
const payload = {
|
|
223
234
|
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
224
|
-
aud: [...this.audience],
|
|
235
|
+
aud: [...options.audience ?? this.audience],
|
|
225
236
|
auth_time: options.authTime ?? now,
|
|
226
|
-
azp: this.clientId,
|
|
237
|
+
azp: options.clientId ?? this.clientId,
|
|
227
238
|
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
228
239
|
iat: now,
|
|
229
240
|
iss: this.issuer,
|
|
@@ -255,11 +266,12 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
255
266
|
const now = this.clock();
|
|
256
267
|
const authTime = options.authTime ?? now;
|
|
257
268
|
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
269
|
+
const clientId = options.clientId ?? this.clientId;
|
|
258
270
|
const payload = {
|
|
259
271
|
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
260
|
-
aud: [
|
|
272
|
+
aud: [clientId],
|
|
261
273
|
auth_time: authTime,
|
|
262
|
-
azp:
|
|
274
|
+
azp: clientId,
|
|
263
275
|
email: user.email,
|
|
264
276
|
email_verified: user.emailVerified,
|
|
265
277
|
exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
|
|
@@ -269,6 +281,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
269
281
|
iss: this.issuer,
|
|
270
282
|
jti: randomUUID(),
|
|
271
283
|
name: name || null,
|
|
284
|
+
nonce: options.nonce,
|
|
272
285
|
org_codes: organization ? [organization.code] : void 0,
|
|
273
286
|
picture: user.picture,
|
|
274
287
|
rat: authTime,
|
|
@@ -362,7 +375,7 @@ async function createSigningKey(prefix) {
|
|
|
362
375
|
const { privateKey, publicKey } = await generateKeyPair("RS256");
|
|
363
376
|
const jwk = await exportJWK(publicKey);
|
|
364
377
|
const kid = `${prefix}-${(await calculateJwkThumbprint(jwk)).slice(0, 16)}`;
|
|
365
|
-
return { kid, privateKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
378
|
+
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
366
379
|
}
|
|
367
380
|
function tamperSignature(jwt) {
|
|
368
381
|
const [header, payload, signature] = jwt.split(".");
|
|
@@ -528,11 +541,445 @@ function isRecord(value) {
|
|
|
528
541
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
529
542
|
}
|
|
530
543
|
|
|
544
|
+
// src/oauth.ts
|
|
545
|
+
import { createHash as createHash2, randomBytes, timingSafeEqual } from "crypto";
|
|
546
|
+
|
|
547
|
+
// src/login-page.ts
|
|
548
|
+
var STYLE = `
|
|
549
|
+
: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}
|
|
550
|
+
@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}}
|
|
551
|
+
*{box-sizing:border-box}
|
|
552
|
+
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}
|
|
553
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
554
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
555
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
556
|
+
p{margin:0;color:var(--muted)}
|
|
557
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
558
|
+
form{margin:0}
|
|
559
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
560
|
+
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}
|
|
561
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
562
|
+
.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}
|
|
563
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
564
|
+
.list{display:grid;gap:8px}
|
|
565
|
+
.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}
|
|
566
|
+
.option:hover{border-color:var(--muted)}
|
|
567
|
+
.option strong{display:block;font-weight:500}
|
|
568
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
569
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
570
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
571
|
+
`;
|
|
572
|
+
function escapeHtml(value) {
|
|
573
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
574
|
+
}
|
|
575
|
+
function layout(title, body) {
|
|
576
|
+
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>`;
|
|
577
|
+
}
|
|
578
|
+
function displayName(user) {
|
|
579
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
580
|
+
}
|
|
581
|
+
function renderSignIn(options) {
|
|
582
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
583
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
584
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
585
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
586
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
587
|
+
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>`;
|
|
588
|
+
}).join("");
|
|
589
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
590
|
+
return layout(
|
|
591
|
+
"Sign in",
|
|
592
|
+
`<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>`
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
function renderOrganizationPicker(options) {
|
|
596
|
+
const choices = options.organizations.map(
|
|
597
|
+
(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>`
|
|
598
|
+
).join("");
|
|
599
|
+
return layout(
|
|
600
|
+
"Choose an organization",
|
|
601
|
+
`<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>`
|
|
602
|
+
);
|
|
603
|
+
}
|
|
604
|
+
function renderMessage(title, message) {
|
|
605
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// src/oauth.ts
|
|
609
|
+
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
610
|
+
var OAuthError = class extends Error {
|
|
611
|
+
constructor(status, error, description) {
|
|
612
|
+
super(description);
|
|
613
|
+
this.status = status;
|
|
614
|
+
this.error = error;
|
|
615
|
+
}
|
|
616
|
+
status;
|
|
617
|
+
error;
|
|
618
|
+
};
|
|
619
|
+
var AuthorizationServer = class {
|
|
620
|
+
constructor(testkit, seed) {
|
|
621
|
+
this.testkit = testkit;
|
|
622
|
+
this.seed = seed;
|
|
623
|
+
}
|
|
624
|
+
testkit;
|
|
625
|
+
seed;
|
|
626
|
+
codes = /* @__PURE__ */ new Map();
|
|
627
|
+
refreshTokens = /* @__PURE__ */ new Map();
|
|
628
|
+
signedUpUsers = /* @__PURE__ */ new Map();
|
|
629
|
+
async handle(req, res, url, readBody) {
|
|
630
|
+
const method = req.method ?? "GET";
|
|
631
|
+
switch (`${method} ${url.pathname}`) {
|
|
632
|
+
case "GET /oauth2/auth":
|
|
633
|
+
this.authorize(res, url.searchParams);
|
|
634
|
+
return true;
|
|
635
|
+
case "POST /oauth2/auth/login":
|
|
636
|
+
this.login(res, await readBody());
|
|
637
|
+
return true;
|
|
638
|
+
case "POST /oauth2/token":
|
|
639
|
+
await this.token(req, res, await readBody());
|
|
640
|
+
return true;
|
|
641
|
+
case "GET /oauth2/v2/user_profile":
|
|
642
|
+
await this.profile(req, res);
|
|
643
|
+
return true;
|
|
644
|
+
case "POST /oauth2/revoke":
|
|
645
|
+
this.revoke(res, await readBody());
|
|
646
|
+
return true;
|
|
647
|
+
case "GET /logout":
|
|
648
|
+
this.logout(res, url.searchParams);
|
|
649
|
+
return true;
|
|
650
|
+
default:
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
authorize(res, params) {
|
|
655
|
+
let request;
|
|
656
|
+
try {
|
|
657
|
+
request = parseAuthorizeRequest(params);
|
|
658
|
+
} catch (error) {
|
|
659
|
+
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
660
|
+
}
|
|
661
|
+
if (params.get("prompt") === "none") {
|
|
662
|
+
return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
663
|
+
}
|
|
664
|
+
sendHtml(
|
|
665
|
+
res,
|
|
666
|
+
200,
|
|
667
|
+
renderSignIn({
|
|
668
|
+
request: encodeRequest(request),
|
|
669
|
+
users: this.loginPageUsers(),
|
|
670
|
+
loginHint: request.loginHint ?? void 0,
|
|
671
|
+
requiredOrganization: request.orgCode ?? void 0
|
|
672
|
+
})
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
login(res, form) {
|
|
676
|
+
let request;
|
|
677
|
+
try {
|
|
678
|
+
request = decodeRequest(form.request ?? "");
|
|
679
|
+
} catch {
|
|
680
|
+
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
681
|
+
}
|
|
682
|
+
const encoded = encodeRequest(request);
|
|
683
|
+
const ref = (form.user || form.email || "").trim();
|
|
684
|
+
if (!ref) {
|
|
685
|
+
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." }));
|
|
686
|
+
}
|
|
687
|
+
const user = this.resolveUser(ref);
|
|
688
|
+
if (!user) {
|
|
689
|
+
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
690
|
+
}
|
|
691
|
+
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
692
|
+
const wanted = request.orgCode ?? form.org ?? null;
|
|
693
|
+
let organizationCode = null;
|
|
694
|
+
if (wanted) {
|
|
695
|
+
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
696
|
+
return sendHtml(
|
|
697
|
+
res,
|
|
698
|
+
403,
|
|
699
|
+
renderSignIn({
|
|
700
|
+
request: encoded,
|
|
701
|
+
users: this.loginPageUsers(),
|
|
702
|
+
requiredOrganization: request.orgCode ?? void 0,
|
|
703
|
+
error: `${user.email ?? user.id} is not a member of ${wanted}.`
|
|
704
|
+
})
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
organizationCode = wanted;
|
|
708
|
+
} else if (memberships.length === 1) {
|
|
709
|
+
organizationCode = memberships[0].organizationCode;
|
|
710
|
+
} else if (memberships.length > 1) {
|
|
711
|
+
return sendHtml(
|
|
712
|
+
res,
|
|
713
|
+
200,
|
|
714
|
+
renderOrganizationPicker({
|
|
715
|
+
request: encoded,
|
|
716
|
+
user,
|
|
717
|
+
organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
718
|
+
})
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
const membership = memberships.find((m) => m.organizationCode === organizationCode);
|
|
722
|
+
const scenario2 = {
|
|
723
|
+
kind: "authenticated",
|
|
724
|
+
user,
|
|
725
|
+
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
726
|
+
roles: [...membership?.roles ?? []],
|
|
727
|
+
permissions: [...membership?.permissions ?? []],
|
|
728
|
+
claims: {}
|
|
729
|
+
};
|
|
730
|
+
const code = randomToken();
|
|
731
|
+
this.codes.set(code, {
|
|
732
|
+
clientId: request.clientId,
|
|
733
|
+
redirectUri: request.redirectUri,
|
|
734
|
+
scenario: scenario2,
|
|
735
|
+
scope: request.scope,
|
|
736
|
+
audience: request.audience,
|
|
737
|
+
nonce: request.nonce,
|
|
738
|
+
authTime: Math.floor(Date.now() / 1e3),
|
|
739
|
+
codeChallenge: request.codeChallenge,
|
|
740
|
+
codeChallengeMethod: request.codeChallengeMethod,
|
|
741
|
+
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
742
|
+
});
|
|
743
|
+
const target = new URL(request.redirectUri);
|
|
744
|
+
target.searchParams.set("code", code);
|
|
745
|
+
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
746
|
+
redirect(res, target.toString());
|
|
747
|
+
}
|
|
748
|
+
async token(req, res, form) {
|
|
749
|
+
try {
|
|
750
|
+
const clientId = clientIdFrom(req, form);
|
|
751
|
+
const grantType = form.grant_type;
|
|
752
|
+
let grant;
|
|
753
|
+
if (grantType === "authorization_code") {
|
|
754
|
+
grant = this.redeemCode(form, clientId);
|
|
755
|
+
} else if (grantType === "refresh_token") {
|
|
756
|
+
grant = this.redeemRefreshToken(form, clientId);
|
|
757
|
+
} else {
|
|
758
|
+
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and refresh_token, not "${grantType ?? ""}".`);
|
|
759
|
+
}
|
|
760
|
+
sendJson(res, 200, await this.issueTokens(grant));
|
|
761
|
+
} catch (error) {
|
|
762
|
+
if (error instanceof OAuthError) {
|
|
763
|
+
return sendJson(res, error.status, { error: error.error, error_description: error.message });
|
|
764
|
+
}
|
|
765
|
+
throw error;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
redeemCode(form, clientId) {
|
|
769
|
+
const code = form.code ?? "";
|
|
770
|
+
const pending = this.codes.get(code);
|
|
771
|
+
this.codes.delete(code);
|
|
772
|
+
if (!pending || pending.expiresAt < Date.now()) {
|
|
773
|
+
throw new OAuthError(400, "invalid_grant", "The authorization code is unknown, expired or already used.");
|
|
774
|
+
}
|
|
775
|
+
if (pending.clientId !== clientId) {
|
|
776
|
+
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
777
|
+
}
|
|
778
|
+
if (form.redirect_uri !== pending.redirectUri) {
|
|
779
|
+
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
780
|
+
}
|
|
781
|
+
if (pending.codeChallenge) {
|
|
782
|
+
const verifier = form.code_verifier ?? "";
|
|
783
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : createHash2("sha256").update(verifier).digest("base64url");
|
|
784
|
+
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
785
|
+
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
return pending;
|
|
789
|
+
}
|
|
790
|
+
redeemRefreshToken(form, clientId) {
|
|
791
|
+
const token = form.refresh_token ?? "";
|
|
792
|
+
const grant = this.refreshTokens.get(token);
|
|
793
|
+
this.refreshTokens.delete(token);
|
|
794
|
+
if (!grant) {
|
|
795
|
+
throw new OAuthError(400, "invalid_grant", "The refresh token is unknown, revoked or already used.");
|
|
796
|
+
}
|
|
797
|
+
if (grant.clientId !== clientId) {
|
|
798
|
+
throw new OAuthError(400, "invalid_grant", "The refresh token was issued to a different client.");
|
|
799
|
+
}
|
|
800
|
+
return grant;
|
|
801
|
+
}
|
|
802
|
+
async issueTokens(grant) {
|
|
803
|
+
const { scenario: scenario2 } = grant;
|
|
804
|
+
const body = {
|
|
805
|
+
access_token: await this.testkit.token({
|
|
806
|
+
subject: scenario2.user.id,
|
|
807
|
+
organizationCode: scenario2.organization?.code ?? null,
|
|
808
|
+
roles: scenario2.roles.length > 0 ? scenario2.roles : void 0,
|
|
809
|
+
permissions: scenario2.permissions.length > 0 ? scenario2.permissions : void 0,
|
|
810
|
+
scopes: grant.scope,
|
|
811
|
+
clientId: grant.clientId,
|
|
812
|
+
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
813
|
+
authTime: grant.authTime
|
|
814
|
+
}),
|
|
815
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
816
|
+
scope: grant.scope.join(" "),
|
|
817
|
+
token_type: "bearer"
|
|
818
|
+
};
|
|
819
|
+
if (grant.scope.includes("openid")) {
|
|
820
|
+
body.id_token = await this.testkit.idTokenFor(scenario2, {
|
|
821
|
+
clientId: grant.clientId,
|
|
822
|
+
nonce: grant.nonce ?? void 0,
|
|
823
|
+
authTime: grant.authTime
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
if (grant.scope.includes("offline")) {
|
|
827
|
+
const refreshToken = randomToken();
|
|
828
|
+
this.refreshTokens.set(refreshToken, { ...grant, nonce: null });
|
|
829
|
+
body.refresh_token = refreshToken;
|
|
830
|
+
}
|
|
831
|
+
return body;
|
|
832
|
+
}
|
|
833
|
+
async profile(req, res) {
|
|
834
|
+
const header = req.headers.authorization ?? "";
|
|
835
|
+
if (!header.startsWith("Bearer ")) {
|
|
836
|
+
return sendJson(res, 401, { error: "invalid_token", error_description: "Send the access token as a Bearer token." });
|
|
837
|
+
}
|
|
838
|
+
let sub;
|
|
839
|
+
try {
|
|
840
|
+
sub = String((await this.testkit.verify(header.slice(7))).sub ?? "");
|
|
841
|
+
} catch {
|
|
842
|
+
return sendJson(res, 401, { error: "invalid_token", error_description: "The access token is not valid for this issuer." });
|
|
843
|
+
}
|
|
844
|
+
const user = this.seed.users.find((u) => u.id === sub) ?? this.signedUpUsers.get(sub);
|
|
845
|
+
if (!user) {
|
|
846
|
+
return sendJson(res, 404, { error: "not_found", error_description: `No user has the id ${sub}.` });
|
|
847
|
+
}
|
|
848
|
+
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
849
|
+
sendJson(res, 200, {
|
|
850
|
+
id: user.id,
|
|
851
|
+
sub: user.id,
|
|
852
|
+
provided_id: null,
|
|
853
|
+
name: name || null,
|
|
854
|
+
given_name: user.givenName,
|
|
855
|
+
family_name: user.familyName,
|
|
856
|
+
updated_at: Math.floor(Date.now() / 1e3),
|
|
857
|
+
email: user.email,
|
|
858
|
+
email_verified: user.emailVerified,
|
|
859
|
+
picture: user.picture,
|
|
860
|
+
preferred_username: null,
|
|
861
|
+
phone: null
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
revoke(res, form) {
|
|
865
|
+
if (form.token) this.refreshTokens.delete(form.token);
|
|
866
|
+
sendJson(res, 200, {});
|
|
867
|
+
}
|
|
868
|
+
logout(res, params) {
|
|
869
|
+
const target = params.get("redirect");
|
|
870
|
+
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
871
|
+
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
872
|
+
}
|
|
873
|
+
resolveUser(ref) {
|
|
874
|
+
const seeded = findUser(this.seed.users, ref);
|
|
875
|
+
if (seeded) return seeded;
|
|
876
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
877
|
+
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
878
|
+
this.signedUpUsers.set(user.id, user);
|
|
879
|
+
return user;
|
|
880
|
+
}
|
|
881
|
+
organization(code) {
|
|
882
|
+
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
883
|
+
}
|
|
884
|
+
loginPageUsers() {
|
|
885
|
+
return this.seed.users.map((user) => ({
|
|
886
|
+
user,
|
|
887
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
888
|
+
}));
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
function parseAuthorizeRequest(params) {
|
|
892
|
+
const clientId = params.get("client_id");
|
|
893
|
+
const redirectUri = params.get("redirect_uri");
|
|
894
|
+
if (!clientId) throw new Error("client_id is missing.");
|
|
895
|
+
if (!redirectUri || !isHttpUrl(redirectUri)) {
|
|
896
|
+
throw new Error("redirect_uri must be an absolute http or https URL.");
|
|
897
|
+
}
|
|
898
|
+
if (params.get("response_type") !== "code") {
|
|
899
|
+
throw new Error('response_type must be "code".');
|
|
900
|
+
}
|
|
901
|
+
const method = params.get("code_challenge_method");
|
|
902
|
+
const challenge = params.get("code_challenge");
|
|
903
|
+
if (challenge && method && method !== "S256" && method !== "plain") {
|
|
904
|
+
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
905
|
+
}
|
|
906
|
+
return {
|
|
907
|
+
clientId,
|
|
908
|
+
redirectUri,
|
|
909
|
+
state: params.get("state"),
|
|
910
|
+
scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
|
|
911
|
+
nonce: params.get("nonce"),
|
|
912
|
+
audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
|
|
913
|
+
orgCode: params.get("org_code"),
|
|
914
|
+
loginHint: params.get("login_hint"),
|
|
915
|
+
codeChallenge: challenge,
|
|
916
|
+
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
function encodeRequest(request) {
|
|
920
|
+
return Buffer.from(JSON.stringify(request)).toString("base64url");
|
|
921
|
+
}
|
|
922
|
+
function decodeRequest(value) {
|
|
923
|
+
const request = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
924
|
+
if (!request.clientId || !request.redirectUri || !isHttpUrl(request.redirectUri)) {
|
|
925
|
+
throw new Error("invalid request");
|
|
926
|
+
}
|
|
927
|
+
return request;
|
|
928
|
+
}
|
|
929
|
+
function clientIdFrom(req, form) {
|
|
930
|
+
const header = req.headers.authorization ?? "";
|
|
931
|
+
if (header.startsWith("Basic ")) {
|
|
932
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
933
|
+
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
934
|
+
if (id) return id;
|
|
935
|
+
}
|
|
936
|
+
if (form.client_id) return form.client_id;
|
|
937
|
+
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
938
|
+
}
|
|
939
|
+
function redirectWithError(res, request, error, description) {
|
|
940
|
+
const target = new URL(request.redirectUri);
|
|
941
|
+
target.searchParams.set("error", error);
|
|
942
|
+
target.searchParams.set("error_description", description);
|
|
943
|
+
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
944
|
+
redirect(res, target.toString());
|
|
945
|
+
}
|
|
946
|
+
function isHttpUrl(value) {
|
|
947
|
+
try {
|
|
948
|
+
const { protocol } = new URL(value);
|
|
949
|
+
return protocol === "http:" || protocol === "https:";
|
|
950
|
+
} catch {
|
|
951
|
+
return false;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
function randomToken() {
|
|
955
|
+
return randomBytes(32).toString("base64url");
|
|
956
|
+
}
|
|
957
|
+
function safeEqual(a, b) {
|
|
958
|
+
const left = Buffer.from(a);
|
|
959
|
+
const right = Buffer.from(b);
|
|
960
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
961
|
+
}
|
|
962
|
+
function redirect(res, location) {
|
|
963
|
+
res.writeHead(303, { location, "cache-control": "no-store" });
|
|
964
|
+
res.end();
|
|
965
|
+
}
|
|
966
|
+
function sendHtml(res, status, html) {
|
|
967
|
+
res.writeHead(status, {
|
|
968
|
+
"content-type": "text/html; charset=utf-8",
|
|
969
|
+
"cache-control": "no-store",
|
|
970
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
971
|
+
});
|
|
972
|
+
res.end(html);
|
|
973
|
+
}
|
|
974
|
+
function sendJson(res, status, body) {
|
|
975
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
976
|
+
res.end(JSON.stringify(body));
|
|
977
|
+
}
|
|
978
|
+
|
|
531
979
|
// src/server.ts
|
|
532
980
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
533
981
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
534
982
|
var JWKS_PATHS = /* @__PURE__ */ new Set(["/.well-known/jwks", "/.well-known/jwks.json"]);
|
|
535
|
-
var NOT_IMPLEMENTED = /* @__PURE__ */ new Set(["/oauth2/auth", "/oauth2/token", "/oauth2/v2/user_profile", "/logout"]);
|
|
536
983
|
async function startKindeTestkit(options = {}) {
|
|
537
984
|
const host = options.host ?? "127.0.0.1";
|
|
538
985
|
if (!LOOPBACK_HOSTS.has(host) && !options.allowPublic) {
|
|
@@ -543,9 +990,11 @@ async function startKindeTestkit(options = {}) {
|
|
|
543
990
|
}
|
|
544
991
|
const seed = resolveSeed(options.seed ?? {});
|
|
545
992
|
let ready;
|
|
546
|
-
const testkitReady = new Promise(
|
|
993
|
+
const testkitReady = new Promise(
|
|
994
|
+
(resolve) => ready = resolve
|
|
995
|
+
);
|
|
547
996
|
const server = createServer((req, res) => {
|
|
548
|
-
testkitReady.then((testkit2) => handle(req, res, testkit2, seed)).catch((error) => sendError(res, error));
|
|
997
|
+
testkitReady.then(({ testkit: testkit2, auth }) => handle(req, res, testkit2, auth, seed)).catch((error) => sendError(res, error));
|
|
549
998
|
});
|
|
550
999
|
await new Promise((resolve, reject) => {
|
|
551
1000
|
server.once("error", reject);
|
|
@@ -559,7 +1008,7 @@ async function startKindeTestkit(options = {}) {
|
|
|
559
1008
|
audience: options.audience ?? options.seed?.audience,
|
|
560
1009
|
clientId: options.clientId ?? options.seed?.clientId
|
|
561
1010
|
});
|
|
562
|
-
ready(testkit);
|
|
1011
|
+
ready({ testkit, auth: new AuthorizationServer(testkit, seed) });
|
|
563
1012
|
return {
|
|
564
1013
|
url,
|
|
565
1014
|
issuer: testkit.issuer,
|
|
@@ -573,37 +1022,33 @@ async function startKindeTestkit(options = {}) {
|
|
|
573
1022
|
})
|
|
574
1023
|
};
|
|
575
1024
|
}
|
|
576
|
-
async function handle(req, res, testkit, seed) {
|
|
577
|
-
const
|
|
1025
|
+
async function handle(req, res, testkit, auth, seed) {
|
|
1026
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1027
|
+
const { pathname } = url;
|
|
578
1028
|
const method = req.method ?? "GET";
|
|
1029
|
+
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
579
1030
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
580
|
-
return
|
|
1031
|
+
return sendJson2(res, 200, discovery(testkit));
|
|
581
1032
|
}
|
|
582
1033
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
583
|
-
return
|
|
1034
|
+
return sendJson2(res, 200, testkit.jwks());
|
|
584
1035
|
}
|
|
585
1036
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
586
|
-
return
|
|
1037
|
+
return sendJson2(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
587
1038
|
}
|
|
588
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
1039
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson2(res, 200, seed.users);
|
|
589
1040
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
590
|
-
return
|
|
1041
|
+
return sendJson2(res, 200, seed.organizations);
|
|
591
1042
|
}
|
|
592
1043
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
593
|
-
return
|
|
1044
|
+
return sendJson2(res, 200, seed.memberships);
|
|
594
1045
|
}
|
|
595
1046
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
596
1047
|
const body = await readJson(req);
|
|
597
1048
|
const accessToken = await issueToken(testkit, seed, body);
|
|
598
|
-
return
|
|
599
|
-
}
|
|
600
|
-
if (NOT_IMPLEMENTED.has(pathname)) {
|
|
601
|
-
return sendJson(res, 501, {
|
|
602
|
-
error: "not_implemented",
|
|
603
|
-
error_description: `${pathname} is not part of this kinde-testkit release. Use POST /testkit/token to mint tokens.`
|
|
604
|
-
});
|
|
1049
|
+
return sendJson2(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
605
1050
|
}
|
|
606
|
-
return
|
|
1051
|
+
return sendJson2(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
607
1052
|
}
|
|
608
1053
|
function discovery(testkit) {
|
|
609
1054
|
const base = testkit.issuer;
|
|
@@ -613,8 +1058,11 @@ function discovery(testkit) {
|
|
|
613
1058
|
token_endpoint: `${base}/oauth2/token`,
|
|
614
1059
|
userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
|
|
615
1060
|
end_session_endpoint: `${base}/logout`,
|
|
1061
|
+
revocation_endpoint: `${base}/oauth2/revoke`,
|
|
616
1062
|
jwks_uri: `${base}/.well-known/jwks`,
|
|
617
1063
|
response_types_supported: ["code"],
|
|
1064
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
1065
|
+
code_challenge_methods_supported: ["S256", "plain"],
|
|
618
1066
|
subject_types_supported: ["public"],
|
|
619
1067
|
id_token_signing_alg_values_supported: ["RS256"],
|
|
620
1068
|
scopes_supported: ["openid", "profile", "email", "offline"],
|
|
@@ -676,7 +1124,28 @@ function optionalStrings(input, field) {
|
|
|
676
1124
|
}
|
|
677
1125
|
return value;
|
|
678
1126
|
}
|
|
1127
|
+
async function readForm(req) {
|
|
1128
|
+
const text = await readText(req);
|
|
1129
|
+
if ((req.headers["content-type"] ?? "").includes("application/json")) {
|
|
1130
|
+
try {
|
|
1131
|
+
const parsed = JSON.parse(text || "{}");
|
|
1132
|
+
return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));
|
|
1133
|
+
} catch {
|
|
1134
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
1138
|
+
}
|
|
679
1139
|
async function readJson(req) {
|
|
1140
|
+
const text = await readText(req);
|
|
1141
|
+
if (text.length === 0) return {};
|
|
1142
|
+
try {
|
|
1143
|
+
return JSON.parse(text);
|
|
1144
|
+
} catch {
|
|
1145
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
async function readText(req) {
|
|
680
1149
|
const chunks = [];
|
|
681
1150
|
let size = 0;
|
|
682
1151
|
for await (const chunk of req) {
|
|
@@ -686,15 +1155,9 @@ async function readJson(req) {
|
|
|
686
1155
|
}
|
|
687
1156
|
chunks.push(chunk);
|
|
688
1157
|
}
|
|
689
|
-
|
|
690
|
-
if (text.length === 0) return {};
|
|
691
|
-
try {
|
|
692
|
-
return JSON.parse(text);
|
|
693
|
-
} catch {
|
|
694
|
-
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
695
|
-
}
|
|
1158
|
+
return Buffer.concat(chunks).toString("utf8").trim();
|
|
696
1159
|
}
|
|
697
|
-
function
|
|
1160
|
+
function sendJson2(res, status, body) {
|
|
698
1161
|
res.writeHead(status, {
|
|
699
1162
|
"content-type": "application/json; charset=utf-8",
|
|
700
1163
|
"cache-control": "no-store"
|
|
@@ -707,10 +1170,10 @@ function sendError(res, error) {
|
|
|
707
1170
|
return;
|
|
708
1171
|
}
|
|
709
1172
|
if (error instanceof TestkitError) {
|
|
710
|
-
|
|
1173
|
+
sendJson2(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
711
1174
|
return;
|
|
712
1175
|
}
|
|
713
|
-
|
|
1176
|
+
sendJson2(res, 500, {
|
|
714
1177
|
error: "server_error",
|
|
715
1178
|
error_description: error instanceof Error ? error.message : String(error)
|
|
716
1179
|
});
|