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