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/index.cjs
CHANGED
|
@@ -254,6 +254,16 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
254
254
|
get keyId() {
|
|
255
255
|
return this.signingKey.kid;
|
|
256
256
|
}
|
|
257
|
+
get accessTokenLifetime() {
|
|
258
|
+
return toSeconds(this.accessTokenExpiresIn);
|
|
259
|
+
}
|
|
260
|
+
async verify(token) {
|
|
261
|
+
const { payload } = await (0, import_jose.jwtVerify)(token, this.signingKey.publicKey, {
|
|
262
|
+
issuer: this.issuer,
|
|
263
|
+
algorithms: ["RS256"]
|
|
264
|
+
});
|
|
265
|
+
return payload;
|
|
266
|
+
}
|
|
257
267
|
jwks() {
|
|
258
268
|
return { keys: [{ ...this.signingKey.publicJwk }] };
|
|
259
269
|
}
|
|
@@ -261,9 +271,9 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
261
271
|
const now = this.clock();
|
|
262
272
|
const payload = {
|
|
263
273
|
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
264
|
-
aud: [...this.audience],
|
|
274
|
+
aud: [...options.audience ?? this.audience],
|
|
265
275
|
auth_time: options.authTime ?? now,
|
|
266
|
-
azp: this.clientId,
|
|
276
|
+
azp: options.clientId ?? this.clientId,
|
|
267
277
|
exp: now + toSeconds(options.expiresIn ?? this.accessTokenExpiresIn),
|
|
268
278
|
iat: now,
|
|
269
279
|
iss: this.issuer,
|
|
@@ -295,11 +305,12 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
295
305
|
const now = this.clock();
|
|
296
306
|
const authTime = options.authTime ?? now;
|
|
297
307
|
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
308
|
+
const clientId = options.clientId ?? this.clientId;
|
|
298
309
|
const payload = {
|
|
299
310
|
amr: [...options.authMethods ?? DEFAULT_AUTH_METHODS],
|
|
300
|
-
aud: [
|
|
311
|
+
aud: [clientId],
|
|
301
312
|
auth_time: authTime,
|
|
302
|
-
azp:
|
|
313
|
+
azp: clientId,
|
|
303
314
|
email: user.email,
|
|
304
315
|
email_verified: user.emailVerified,
|
|
305
316
|
exp: now + toSeconds(options.expiresIn ?? this.idTokenExpiresIn),
|
|
@@ -309,6 +320,7 @@ var KindeTestkit = class _KindeTestkit {
|
|
|
309
320
|
iss: this.issuer,
|
|
310
321
|
jti: (0, import_node_crypto2.randomUUID)(),
|
|
311
322
|
name: name || null,
|
|
323
|
+
nonce: options.nonce,
|
|
312
324
|
org_codes: organization ? [organization.code] : void 0,
|
|
313
325
|
picture: user.picture,
|
|
314
326
|
rat: authTime,
|
|
@@ -402,7 +414,7 @@ async function createSigningKey(prefix) {
|
|
|
402
414
|
const { privateKey, publicKey } = await (0, import_jose.generateKeyPair)("RS256");
|
|
403
415
|
const jwk = await (0, import_jose.exportJWK)(publicKey);
|
|
404
416
|
const kid = `${prefix}-${(await (0, import_jose.calculateJwkThumbprint)(jwk)).slice(0, 16)}`;
|
|
405
|
-
return { kid, privateKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
417
|
+
return { kid, privateKey, publicKey, publicJwk: { ...jwk, kid, alg: "RS256", use: "sig" } };
|
|
406
418
|
}
|
|
407
419
|
function tamperSignature(jwt) {
|
|
408
420
|
const [header, payload, signature] = jwt.split(".");
|
|
@@ -568,11 +580,445 @@ function isRecord(value) {
|
|
|
568
580
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
569
581
|
}
|
|
570
582
|
|
|
583
|
+
// src/oauth.ts
|
|
584
|
+
var import_node_crypto3 = require("crypto");
|
|
585
|
+
|
|
586
|
+
// src/login-page.ts
|
|
587
|
+
var STYLE = `
|
|
588
|
+
: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}
|
|
589
|
+
@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}}
|
|
590
|
+
*{box-sizing:border-box}
|
|
591
|
+
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}
|
|
592
|
+
main{width:100%;max-width:420px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:28px}
|
|
593
|
+
.brand{font:600 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.04em;color:var(--muted);text-transform:uppercase}
|
|
594
|
+
h1{font-size:22px;line-height:1.25;margin:10px 0 6px;font-weight:600}
|
|
595
|
+
p{margin:0;color:var(--muted)}
|
|
596
|
+
.note{margin-top:16px;padding:10px 12px;border-radius:8px;background:var(--warn-bg);color:var(--warn);font-size:13px}
|
|
597
|
+
form{margin:0}
|
|
598
|
+
label{display:block;font-size:13px;font-weight:500;margin:20px 0 6px}
|
|
599
|
+
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}
|
|
600
|
+
input[type=email]:focus{outline:2px solid var(--accent);outline-offset:1px}
|
|
601
|
+
.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}
|
|
602
|
+
h2{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);margin:26px 0 8px}
|
|
603
|
+
.list{display:grid;gap:8px}
|
|
604
|
+
.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}
|
|
605
|
+
.option:hover{border-color:var(--muted)}
|
|
606
|
+
.option strong{display:block;font-weight:500}
|
|
607
|
+
.option small{color:var(--muted);font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
608
|
+
.tag{flex:none;font:12px/1 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted)}
|
|
609
|
+
.error{margin-top:16px;padding:10px 12px;border-radius:8px;border:1px solid var(--line);font-size:14px}
|
|
610
|
+
`;
|
|
611
|
+
function escapeHtml(value) {
|
|
612
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
613
|
+
}
|
|
614
|
+
function layout(title, body) {
|
|
615
|
+
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>`;
|
|
616
|
+
}
|
|
617
|
+
function displayName(user) {
|
|
618
|
+
return [user.givenName, user.familyName].filter(Boolean).join(" ") || user.email || user.id;
|
|
619
|
+
}
|
|
620
|
+
function renderSignIn(options) {
|
|
621
|
+
const users = options.users.map(({ user, organizations }) => {
|
|
622
|
+
const value = escapeHtml(user.email ?? user.id);
|
|
623
|
+
const hasName = Boolean(user.givenName || user.familyName);
|
|
624
|
+
const detail = escapeHtml(hasName ? user.email ?? user.id : user.id);
|
|
625
|
+
const tag = organizations.length === 0 ? "no organization" : organizations.length === 1 ? escapeHtml(organizations[0].code) : `${organizations.length} organizations`;
|
|
626
|
+
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>`;
|
|
627
|
+
}).join("");
|
|
628
|
+
const orgNote = options.requiredOrganization ? `<p class="note">The app asked to sign in to <strong>${escapeHtml(options.requiredOrganization)}</strong>.</p>` : "";
|
|
629
|
+
return layout(
|
|
630
|
+
"Sign in",
|
|
631
|
+
`<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>`
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
function renderOrganizationPicker(options) {
|
|
635
|
+
const choices = options.organizations.map(
|
|
636
|
+
(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>`
|
|
637
|
+
).join("");
|
|
638
|
+
return layout(
|
|
639
|
+
"Choose an organization",
|
|
640
|
+
`<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>`
|
|
641
|
+
);
|
|
642
|
+
}
|
|
643
|
+
function renderMessage(title, message) {
|
|
644
|
+
return layout(title, `<h1>${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// src/oauth.ts
|
|
648
|
+
var CODE_LIFETIME_MS = 10 * 60 * 1e3;
|
|
649
|
+
var OAuthError = class extends Error {
|
|
650
|
+
constructor(status, error, description) {
|
|
651
|
+
super(description);
|
|
652
|
+
this.status = status;
|
|
653
|
+
this.error = error;
|
|
654
|
+
}
|
|
655
|
+
status;
|
|
656
|
+
error;
|
|
657
|
+
};
|
|
658
|
+
var AuthorizationServer = class {
|
|
659
|
+
constructor(testkit, seed) {
|
|
660
|
+
this.testkit = testkit;
|
|
661
|
+
this.seed = seed;
|
|
662
|
+
}
|
|
663
|
+
testkit;
|
|
664
|
+
seed;
|
|
665
|
+
codes = /* @__PURE__ */ new Map();
|
|
666
|
+
refreshTokens = /* @__PURE__ */ new Map();
|
|
667
|
+
signedUpUsers = /* @__PURE__ */ new Map();
|
|
668
|
+
async handle(req, res, url, readBody) {
|
|
669
|
+
const method = req.method ?? "GET";
|
|
670
|
+
switch (`${method} ${url.pathname}`) {
|
|
671
|
+
case "GET /oauth2/auth":
|
|
672
|
+
this.authorize(res, url.searchParams);
|
|
673
|
+
return true;
|
|
674
|
+
case "POST /oauth2/auth/login":
|
|
675
|
+
this.login(res, await readBody());
|
|
676
|
+
return true;
|
|
677
|
+
case "POST /oauth2/token":
|
|
678
|
+
await this.token(req, res, await readBody());
|
|
679
|
+
return true;
|
|
680
|
+
case "GET /oauth2/v2/user_profile":
|
|
681
|
+
await this.profile(req, res);
|
|
682
|
+
return true;
|
|
683
|
+
case "POST /oauth2/revoke":
|
|
684
|
+
this.revoke(res, await readBody());
|
|
685
|
+
return true;
|
|
686
|
+
case "GET /logout":
|
|
687
|
+
this.logout(res, url.searchParams);
|
|
688
|
+
return true;
|
|
689
|
+
default:
|
|
690
|
+
return false;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
authorize(res, params) {
|
|
694
|
+
let request;
|
|
695
|
+
try {
|
|
696
|
+
request = parseAuthorizeRequest(params);
|
|
697
|
+
} catch (error) {
|
|
698
|
+
return sendHtml(res, 400, renderMessage("Sign-in request rejected", error.message));
|
|
699
|
+
}
|
|
700
|
+
if (params.get("prompt") === "none") {
|
|
701
|
+
return redirectWithError(res, request, "login_required", "kinde-testkit has no signed-in browser session.");
|
|
702
|
+
}
|
|
703
|
+
sendHtml(
|
|
704
|
+
res,
|
|
705
|
+
200,
|
|
706
|
+
renderSignIn({
|
|
707
|
+
request: encodeRequest(request),
|
|
708
|
+
users: this.loginPageUsers(),
|
|
709
|
+
loginHint: request.loginHint ?? void 0,
|
|
710
|
+
requiredOrganization: request.orgCode ?? void 0
|
|
711
|
+
})
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
login(res, form) {
|
|
715
|
+
let request;
|
|
716
|
+
try {
|
|
717
|
+
request = decodeRequest(form.request ?? "");
|
|
718
|
+
} catch {
|
|
719
|
+
return sendHtml(res, 400, renderMessage("Sign-in request rejected", "The sign-in form is missing its request. Start again from the app."));
|
|
720
|
+
}
|
|
721
|
+
const encoded = encodeRequest(request);
|
|
722
|
+
const ref = (form.user || form.email || "").trim();
|
|
723
|
+
if (!ref) {
|
|
724
|
+
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." }));
|
|
725
|
+
}
|
|
726
|
+
const user = this.resolveUser(ref);
|
|
727
|
+
if (!user) {
|
|
728
|
+
return sendHtml(res, 400, renderSignIn({ request: encoded, users: this.loginPageUsers(), requiredOrganization: request.orgCode ?? void 0, error: `"${ref}" is not a valid email address.` }));
|
|
729
|
+
}
|
|
730
|
+
const memberships = this.seed.memberships.filter((m) => m.userId === user.id);
|
|
731
|
+
const wanted = request.orgCode ?? form.org ?? null;
|
|
732
|
+
let organizationCode = null;
|
|
733
|
+
if (wanted) {
|
|
734
|
+
if (!memberships.some((m) => m.organizationCode === wanted)) {
|
|
735
|
+
return sendHtml(
|
|
736
|
+
res,
|
|
737
|
+
403,
|
|
738
|
+
renderSignIn({
|
|
739
|
+
request: encoded,
|
|
740
|
+
users: this.loginPageUsers(),
|
|
741
|
+
requiredOrganization: request.orgCode ?? void 0,
|
|
742
|
+
error: `${user.email ?? user.id} is not a member of ${wanted}.`
|
|
743
|
+
})
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
organizationCode = wanted;
|
|
747
|
+
} else if (memberships.length === 1) {
|
|
748
|
+
organizationCode = memberships[0].organizationCode;
|
|
749
|
+
} else if (memberships.length > 1) {
|
|
750
|
+
return sendHtml(
|
|
751
|
+
res,
|
|
752
|
+
200,
|
|
753
|
+
renderOrganizationPicker({
|
|
754
|
+
request: encoded,
|
|
755
|
+
user,
|
|
756
|
+
organizations: memberships.map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
757
|
+
})
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
const membership = memberships.find((m) => m.organizationCode === organizationCode);
|
|
761
|
+
const scenario2 = {
|
|
762
|
+
kind: "authenticated",
|
|
763
|
+
user,
|
|
764
|
+
organization: organizationCode ? this.organization(organizationCode) : null,
|
|
765
|
+
roles: [...membership?.roles ?? []],
|
|
766
|
+
permissions: [...membership?.permissions ?? []],
|
|
767
|
+
claims: {}
|
|
768
|
+
};
|
|
769
|
+
const code = randomToken();
|
|
770
|
+
this.codes.set(code, {
|
|
771
|
+
clientId: request.clientId,
|
|
772
|
+
redirectUri: request.redirectUri,
|
|
773
|
+
scenario: scenario2,
|
|
774
|
+
scope: request.scope,
|
|
775
|
+
audience: request.audience,
|
|
776
|
+
nonce: request.nonce,
|
|
777
|
+
authTime: Math.floor(Date.now() / 1e3),
|
|
778
|
+
codeChallenge: request.codeChallenge,
|
|
779
|
+
codeChallengeMethod: request.codeChallengeMethod,
|
|
780
|
+
expiresAt: Date.now() + CODE_LIFETIME_MS
|
|
781
|
+
});
|
|
782
|
+
const target = new URL(request.redirectUri);
|
|
783
|
+
target.searchParams.set("code", code);
|
|
784
|
+
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
785
|
+
redirect(res, target.toString());
|
|
786
|
+
}
|
|
787
|
+
async token(req, res, form) {
|
|
788
|
+
try {
|
|
789
|
+
const clientId = clientIdFrom(req, form);
|
|
790
|
+
const grantType = form.grant_type;
|
|
791
|
+
let grant;
|
|
792
|
+
if (grantType === "authorization_code") {
|
|
793
|
+
grant = this.redeemCode(form, clientId);
|
|
794
|
+
} else if (grantType === "refresh_token") {
|
|
795
|
+
grant = this.redeemRefreshToken(form, clientId);
|
|
796
|
+
} else {
|
|
797
|
+
throw new OAuthError(400, "unsupported_grant_type", `kinde-testkit supports authorization_code and refresh_token, not "${grantType ?? ""}".`);
|
|
798
|
+
}
|
|
799
|
+
sendJson(res, 200, await this.issueTokens(grant));
|
|
800
|
+
} catch (error) {
|
|
801
|
+
if (error instanceof OAuthError) {
|
|
802
|
+
return sendJson(res, error.status, { error: error.error, error_description: error.message });
|
|
803
|
+
}
|
|
804
|
+
throw error;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
redeemCode(form, clientId) {
|
|
808
|
+
const code = form.code ?? "";
|
|
809
|
+
const pending = this.codes.get(code);
|
|
810
|
+
this.codes.delete(code);
|
|
811
|
+
if (!pending || pending.expiresAt < Date.now()) {
|
|
812
|
+
throw new OAuthError(400, "invalid_grant", "The authorization code is unknown, expired or already used.");
|
|
813
|
+
}
|
|
814
|
+
if (pending.clientId !== clientId) {
|
|
815
|
+
throw new OAuthError(400, "invalid_grant", "The authorization code was issued to a different client.");
|
|
816
|
+
}
|
|
817
|
+
if (form.redirect_uri !== pending.redirectUri) {
|
|
818
|
+
throw new OAuthError(400, "invalid_grant", "redirect_uri does not match the one used to start sign-in.");
|
|
819
|
+
}
|
|
820
|
+
if (pending.codeChallenge) {
|
|
821
|
+
const verifier = form.code_verifier ?? "";
|
|
822
|
+
const expected = pending.codeChallengeMethod === "plain" ? verifier : (0, import_node_crypto3.createHash)("sha256").update(verifier).digest("base64url");
|
|
823
|
+
if (!verifier || !safeEqual(expected, pending.codeChallenge)) {
|
|
824
|
+
throw new OAuthError(400, "invalid_grant", "code_verifier does not match the code_challenge.");
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
return pending;
|
|
828
|
+
}
|
|
829
|
+
redeemRefreshToken(form, clientId) {
|
|
830
|
+
const token = form.refresh_token ?? "";
|
|
831
|
+
const grant = this.refreshTokens.get(token);
|
|
832
|
+
this.refreshTokens.delete(token);
|
|
833
|
+
if (!grant) {
|
|
834
|
+
throw new OAuthError(400, "invalid_grant", "The refresh token is unknown, revoked or already used.");
|
|
835
|
+
}
|
|
836
|
+
if (grant.clientId !== clientId) {
|
|
837
|
+
throw new OAuthError(400, "invalid_grant", "The refresh token was issued to a different client.");
|
|
838
|
+
}
|
|
839
|
+
return grant;
|
|
840
|
+
}
|
|
841
|
+
async issueTokens(grant) {
|
|
842
|
+
const { scenario: scenario2 } = grant;
|
|
843
|
+
const body = {
|
|
844
|
+
access_token: await this.testkit.token({
|
|
845
|
+
subject: scenario2.user.id,
|
|
846
|
+
organizationCode: scenario2.organization?.code ?? null,
|
|
847
|
+
roles: scenario2.roles.length > 0 ? scenario2.roles : void 0,
|
|
848
|
+
permissions: scenario2.permissions.length > 0 ? scenario2.permissions : void 0,
|
|
849
|
+
scopes: grant.scope,
|
|
850
|
+
clientId: grant.clientId,
|
|
851
|
+
audience: grant.audience.length > 0 ? grant.audience : void 0,
|
|
852
|
+
authTime: grant.authTime
|
|
853
|
+
}),
|
|
854
|
+
expires_in: this.testkit.accessTokenLifetime,
|
|
855
|
+
scope: grant.scope.join(" "),
|
|
856
|
+
token_type: "bearer"
|
|
857
|
+
};
|
|
858
|
+
if (grant.scope.includes("openid")) {
|
|
859
|
+
body.id_token = await this.testkit.idTokenFor(scenario2, {
|
|
860
|
+
clientId: grant.clientId,
|
|
861
|
+
nonce: grant.nonce ?? void 0,
|
|
862
|
+
authTime: grant.authTime
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
if (grant.scope.includes("offline")) {
|
|
866
|
+
const refreshToken = randomToken();
|
|
867
|
+
this.refreshTokens.set(refreshToken, { ...grant, nonce: null });
|
|
868
|
+
body.refresh_token = refreshToken;
|
|
869
|
+
}
|
|
870
|
+
return body;
|
|
871
|
+
}
|
|
872
|
+
async profile(req, res) {
|
|
873
|
+
const header = req.headers.authorization ?? "";
|
|
874
|
+
if (!header.startsWith("Bearer ")) {
|
|
875
|
+
return sendJson(res, 401, { error: "invalid_token", error_description: "Send the access token as a Bearer token." });
|
|
876
|
+
}
|
|
877
|
+
let sub;
|
|
878
|
+
try {
|
|
879
|
+
sub = String((await this.testkit.verify(header.slice(7))).sub ?? "");
|
|
880
|
+
} catch {
|
|
881
|
+
return sendJson(res, 401, { error: "invalid_token", error_description: "The access token is not valid for this issuer." });
|
|
882
|
+
}
|
|
883
|
+
const user = this.seed.users.find((u) => u.id === sub) ?? this.signedUpUsers.get(sub);
|
|
884
|
+
if (!user) {
|
|
885
|
+
return sendJson(res, 404, { error: "not_found", error_description: `No user has the id ${sub}.` });
|
|
886
|
+
}
|
|
887
|
+
const name = [user.givenName, user.familyName].filter(Boolean).join(" ");
|
|
888
|
+
sendJson(res, 200, {
|
|
889
|
+
id: user.id,
|
|
890
|
+
sub: user.id,
|
|
891
|
+
provided_id: null,
|
|
892
|
+
name: name || null,
|
|
893
|
+
given_name: user.givenName,
|
|
894
|
+
family_name: user.familyName,
|
|
895
|
+
updated_at: Math.floor(Date.now() / 1e3),
|
|
896
|
+
email: user.email,
|
|
897
|
+
email_verified: user.emailVerified,
|
|
898
|
+
picture: user.picture,
|
|
899
|
+
preferred_username: null,
|
|
900
|
+
phone: null
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
revoke(res, form) {
|
|
904
|
+
if (form.token) this.refreshTokens.delete(form.token);
|
|
905
|
+
sendJson(res, 200, {});
|
|
906
|
+
}
|
|
907
|
+
logout(res, params) {
|
|
908
|
+
const target = params.get("redirect");
|
|
909
|
+
if (target && isHttpUrl(target)) return redirect(res, target);
|
|
910
|
+
sendHtml(res, 200, renderMessage("Signed out", "You are signed out of kinde-testkit. You can close this tab."));
|
|
911
|
+
}
|
|
912
|
+
resolveUser(ref) {
|
|
913
|
+
const seeded = findUser(this.seed.users, ref);
|
|
914
|
+
if (seeded) return seeded;
|
|
915
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ref)) return null;
|
|
916
|
+
const user = createKindeUser({ email: ref.toLowerCase() });
|
|
917
|
+
this.signedUpUsers.set(user.id, user);
|
|
918
|
+
return user;
|
|
919
|
+
}
|
|
920
|
+
organization(code) {
|
|
921
|
+
return this.seed.organizations.find((org) => org.code === code) ?? null;
|
|
922
|
+
}
|
|
923
|
+
loginPageUsers() {
|
|
924
|
+
return this.seed.users.map((user) => ({
|
|
925
|
+
user,
|
|
926
|
+
organizations: this.seed.memberships.filter((m) => m.userId === user.id).map((m) => this.organization(m.organizationCode)).filter((org) => org !== null)
|
|
927
|
+
}));
|
|
928
|
+
}
|
|
929
|
+
};
|
|
930
|
+
function parseAuthorizeRequest(params) {
|
|
931
|
+
const clientId = params.get("client_id");
|
|
932
|
+
const redirectUri = params.get("redirect_uri");
|
|
933
|
+
if (!clientId) throw new Error("client_id is missing.");
|
|
934
|
+
if (!redirectUri || !isHttpUrl(redirectUri)) {
|
|
935
|
+
throw new Error("redirect_uri must be an absolute http or https URL.");
|
|
936
|
+
}
|
|
937
|
+
if (params.get("response_type") !== "code") {
|
|
938
|
+
throw new Error('response_type must be "code".');
|
|
939
|
+
}
|
|
940
|
+
const method = params.get("code_challenge_method");
|
|
941
|
+
const challenge = params.get("code_challenge");
|
|
942
|
+
if (challenge && method && method !== "S256" && method !== "plain") {
|
|
943
|
+
throw new Error('code_challenge_method must be "S256" or "plain".');
|
|
944
|
+
}
|
|
945
|
+
return {
|
|
946
|
+
clientId,
|
|
947
|
+
redirectUri,
|
|
948
|
+
state: params.get("state"),
|
|
949
|
+
scope: (params.get("scope") ?? DEFAULT_SCOPES.join(" ")).split(/\s+/).filter(Boolean),
|
|
950
|
+
nonce: params.get("nonce"),
|
|
951
|
+
audience: params.getAll("audience").flatMap((a) => a.split(/\s+/)).filter(Boolean),
|
|
952
|
+
orgCode: params.get("org_code"),
|
|
953
|
+
loginHint: params.get("login_hint"),
|
|
954
|
+
codeChallenge: challenge,
|
|
955
|
+
codeChallengeMethod: challenge ? method ?? "plain" : null
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
function encodeRequest(request) {
|
|
959
|
+
return Buffer.from(JSON.stringify(request)).toString("base64url");
|
|
960
|
+
}
|
|
961
|
+
function decodeRequest(value) {
|
|
962
|
+
const request = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
963
|
+
if (!request.clientId || !request.redirectUri || !isHttpUrl(request.redirectUri)) {
|
|
964
|
+
throw new Error("invalid request");
|
|
965
|
+
}
|
|
966
|
+
return request;
|
|
967
|
+
}
|
|
968
|
+
function clientIdFrom(req, form) {
|
|
969
|
+
const header = req.headers.authorization ?? "";
|
|
970
|
+
if (header.startsWith("Basic ")) {
|
|
971
|
+
const decoded = Buffer.from(header.slice(6), "base64").toString("utf8");
|
|
972
|
+
const id = decodeURIComponent(decoded.split(":")[0] ?? "");
|
|
973
|
+
if (id) return id;
|
|
974
|
+
}
|
|
975
|
+
if (form.client_id) return form.client_id;
|
|
976
|
+
throw new OAuthError(401, "invalid_client", "Send client_id in the body or with HTTP Basic authentication.");
|
|
977
|
+
}
|
|
978
|
+
function redirectWithError(res, request, error, description) {
|
|
979
|
+
const target = new URL(request.redirectUri);
|
|
980
|
+
target.searchParams.set("error", error);
|
|
981
|
+
target.searchParams.set("error_description", description);
|
|
982
|
+
if (request.state !== null) target.searchParams.set("state", request.state);
|
|
983
|
+
redirect(res, target.toString());
|
|
984
|
+
}
|
|
985
|
+
function isHttpUrl(value) {
|
|
986
|
+
try {
|
|
987
|
+
const { protocol } = new URL(value);
|
|
988
|
+
return protocol === "http:" || protocol === "https:";
|
|
989
|
+
} catch {
|
|
990
|
+
return false;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
function randomToken() {
|
|
994
|
+
return (0, import_node_crypto3.randomBytes)(32).toString("base64url");
|
|
995
|
+
}
|
|
996
|
+
function safeEqual(a, b) {
|
|
997
|
+
const left = Buffer.from(a);
|
|
998
|
+
const right = Buffer.from(b);
|
|
999
|
+
return left.length === right.length && (0, import_node_crypto3.timingSafeEqual)(left, right);
|
|
1000
|
+
}
|
|
1001
|
+
function redirect(res, location) {
|
|
1002
|
+
res.writeHead(303, { location, "cache-control": "no-store" });
|
|
1003
|
+
res.end();
|
|
1004
|
+
}
|
|
1005
|
+
function sendHtml(res, status, html) {
|
|
1006
|
+
res.writeHead(status, {
|
|
1007
|
+
"content-type": "text/html; charset=utf-8",
|
|
1008
|
+
"cache-control": "no-store",
|
|
1009
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http: https:; base-uri 'none'; frame-ancestors 'none'"
|
|
1010
|
+
});
|
|
1011
|
+
res.end(html);
|
|
1012
|
+
}
|
|
1013
|
+
function sendJson(res, status, body) {
|
|
1014
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
1015
|
+
res.end(JSON.stringify(body));
|
|
1016
|
+
}
|
|
1017
|
+
|
|
571
1018
|
// src/server.ts
|
|
572
1019
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
573
1020
|
var MAX_BODY_BYTES = 64 * 1024;
|
|
574
1021
|
var JWKS_PATHS = /* @__PURE__ */ new Set(["/.well-known/jwks", "/.well-known/jwks.json"]);
|
|
575
|
-
var NOT_IMPLEMENTED = /* @__PURE__ */ new Set(["/oauth2/auth", "/oauth2/token", "/oauth2/v2/user_profile", "/logout"]);
|
|
576
1022
|
async function startKindeTestkit(options = {}) {
|
|
577
1023
|
const host = options.host ?? "127.0.0.1";
|
|
578
1024
|
if (!LOOPBACK_HOSTS.has(host) && !options.allowPublic) {
|
|
@@ -583,9 +1029,11 @@ async function startKindeTestkit(options = {}) {
|
|
|
583
1029
|
}
|
|
584
1030
|
const seed = resolveSeed(options.seed ?? {});
|
|
585
1031
|
let ready;
|
|
586
|
-
const testkitReady = new Promise(
|
|
1032
|
+
const testkitReady = new Promise(
|
|
1033
|
+
(resolve) => ready = resolve
|
|
1034
|
+
);
|
|
587
1035
|
const server = (0, import_node_http.createServer)((req, res) => {
|
|
588
|
-
testkitReady.then((testkit2) => handle(req, res, testkit2, seed)).catch((error) => sendError(res, error));
|
|
1036
|
+
testkitReady.then(({ testkit: testkit2, auth }) => handle(req, res, testkit2, auth, seed)).catch((error) => sendError(res, error));
|
|
589
1037
|
});
|
|
590
1038
|
await new Promise((resolve, reject) => {
|
|
591
1039
|
server.once("error", reject);
|
|
@@ -599,7 +1047,7 @@ async function startKindeTestkit(options = {}) {
|
|
|
599
1047
|
audience: options.audience ?? options.seed?.audience,
|
|
600
1048
|
clientId: options.clientId ?? options.seed?.clientId
|
|
601
1049
|
});
|
|
602
|
-
ready(testkit);
|
|
1050
|
+
ready({ testkit, auth: new AuthorizationServer(testkit, seed) });
|
|
603
1051
|
return {
|
|
604
1052
|
url,
|
|
605
1053
|
issuer: testkit.issuer,
|
|
@@ -613,37 +1061,33 @@ async function startKindeTestkit(options = {}) {
|
|
|
613
1061
|
})
|
|
614
1062
|
};
|
|
615
1063
|
}
|
|
616
|
-
async function handle(req, res, testkit, seed) {
|
|
617
|
-
const
|
|
1064
|
+
async function handle(req, res, testkit, auth, seed) {
|
|
1065
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1066
|
+
const { pathname } = url;
|
|
618
1067
|
const method = req.method ?? "GET";
|
|
1068
|
+
if (await auth.handle(req, res, url, () => readForm(req))) return;
|
|
619
1069
|
if (method === "GET" && pathname === "/.well-known/openid-configuration") {
|
|
620
|
-
return
|
|
1070
|
+
return sendJson2(res, 200, discovery(testkit));
|
|
621
1071
|
}
|
|
622
1072
|
if (method === "GET" && JWKS_PATHS.has(pathname)) {
|
|
623
|
-
return
|
|
1073
|
+
return sendJson2(res, 200, testkit.jwks());
|
|
624
1074
|
}
|
|
625
1075
|
if (method === "GET" && pathname === "/testkit/health") {
|
|
626
|
-
return
|
|
1076
|
+
return sendJson2(res, 200, { ok: true, issuer: testkit.issuer, kid: testkit.keyId });
|
|
627
1077
|
}
|
|
628
|
-
if (method === "GET" && pathname === "/testkit/users") return
|
|
1078
|
+
if (method === "GET" && pathname === "/testkit/users") return sendJson2(res, 200, seed.users);
|
|
629
1079
|
if (method === "GET" && pathname === "/testkit/organizations") {
|
|
630
|
-
return
|
|
1080
|
+
return sendJson2(res, 200, seed.organizations);
|
|
631
1081
|
}
|
|
632
1082
|
if (method === "GET" && pathname === "/testkit/memberships") {
|
|
633
|
-
return
|
|
1083
|
+
return sendJson2(res, 200, seed.memberships);
|
|
634
1084
|
}
|
|
635
1085
|
if (method === "POST" && pathname === "/testkit/token") {
|
|
636
1086
|
const body = await readJson(req);
|
|
637
1087
|
const accessToken = await issueToken(testkit, seed, body);
|
|
638
|
-
return
|
|
639
|
-
}
|
|
640
|
-
if (NOT_IMPLEMENTED.has(pathname)) {
|
|
641
|
-
return sendJson(res, 501, {
|
|
642
|
-
error: "not_implemented",
|
|
643
|
-
error_description: `${pathname} is not part of this kinde-testkit release. Use POST /testkit/token to mint tokens.`
|
|
644
|
-
});
|
|
1088
|
+
return sendJson2(res, 200, { access_token: accessToken, token_type: "Bearer" });
|
|
645
1089
|
}
|
|
646
|
-
return
|
|
1090
|
+
return sendJson2(res, 404, { error: "not_found", error_description: `${method} ${pathname} does not exist.` });
|
|
647
1091
|
}
|
|
648
1092
|
function discovery(testkit) {
|
|
649
1093
|
const base = testkit.issuer;
|
|
@@ -653,8 +1097,11 @@ function discovery(testkit) {
|
|
|
653
1097
|
token_endpoint: `${base}/oauth2/token`,
|
|
654
1098
|
userinfo_endpoint: `${base}/oauth2/v2/user_profile`,
|
|
655
1099
|
end_session_endpoint: `${base}/logout`,
|
|
1100
|
+
revocation_endpoint: `${base}/oauth2/revoke`,
|
|
656
1101
|
jwks_uri: `${base}/.well-known/jwks`,
|
|
657
1102
|
response_types_supported: ["code"],
|
|
1103
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
1104
|
+
code_challenge_methods_supported: ["S256", "plain"],
|
|
658
1105
|
subject_types_supported: ["public"],
|
|
659
1106
|
id_token_signing_alg_values_supported: ["RS256"],
|
|
660
1107
|
scopes_supported: ["openid", "profile", "email", "offline"],
|
|
@@ -716,7 +1163,28 @@ function optionalStrings(input, field) {
|
|
|
716
1163
|
}
|
|
717
1164
|
return value;
|
|
718
1165
|
}
|
|
1166
|
+
async function readForm(req) {
|
|
1167
|
+
const text = await readText(req);
|
|
1168
|
+
if ((req.headers["content-type"] ?? "").includes("application/json")) {
|
|
1169
|
+
try {
|
|
1170
|
+
const parsed = JSON.parse(text || "{}");
|
|
1171
|
+
return Object.fromEntries(Object.entries(parsed).map(([key, value]) => [key, String(value)]));
|
|
1172
|
+
} catch {
|
|
1173
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
return Object.fromEntries(new URLSearchParams(text));
|
|
1177
|
+
}
|
|
719
1178
|
async function readJson(req) {
|
|
1179
|
+
const text = await readText(req);
|
|
1180
|
+
if (text.length === 0) return {};
|
|
1181
|
+
try {
|
|
1182
|
+
return JSON.parse(text);
|
|
1183
|
+
} catch {
|
|
1184
|
+
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
async function readText(req) {
|
|
720
1188
|
const chunks = [];
|
|
721
1189
|
let size = 0;
|
|
722
1190
|
for await (const chunk of req) {
|
|
@@ -726,15 +1194,9 @@ async function readJson(req) {
|
|
|
726
1194
|
}
|
|
727
1195
|
chunks.push(chunk);
|
|
728
1196
|
}
|
|
729
|
-
|
|
730
|
-
if (text.length === 0) return {};
|
|
731
|
-
try {
|
|
732
|
-
return JSON.parse(text);
|
|
733
|
-
} catch {
|
|
734
|
-
throw new TestkitError("INVALID_REQUEST", "The request body is not valid JSON.");
|
|
735
|
-
}
|
|
1197
|
+
return Buffer.concat(chunks).toString("utf8").trim();
|
|
736
1198
|
}
|
|
737
|
-
function
|
|
1199
|
+
function sendJson2(res, status, body) {
|
|
738
1200
|
res.writeHead(status, {
|
|
739
1201
|
"content-type": "application/json; charset=utf-8",
|
|
740
1202
|
"cache-control": "no-store"
|
|
@@ -747,10 +1209,10 @@ function sendError(res, error) {
|
|
|
747
1209
|
return;
|
|
748
1210
|
}
|
|
749
1211
|
if (error instanceof TestkitError) {
|
|
750
|
-
|
|
1212
|
+
sendJson2(res, 400, { error: error.code, error_description: error.message, details: error.details });
|
|
751
1213
|
return;
|
|
752
1214
|
}
|
|
753
|
-
|
|
1215
|
+
sendJson2(res, 500, {
|
|
754
1216
|
error: "server_error",
|
|
755
1217
|
error_description: error instanceof Error ? error.message : String(error)
|
|
756
1218
|
});
|