From d53e5c09273cbbb306adcb039695e4866a11c954 Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:22:28 +0300 Subject: [PATCH] fix(studio): guest-only /login and kept deep links (#388) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A signed-in member who opened /login saw the sign-in form again, and a signed-out member's deep link was lost after sign-in. - /login, /forgot-password and /reset-password check the session in beforeLoad (the cached one, so no extra request) and go on to the validated `redirect`, or to /sites. An RFC-0044 authorization request (?client_id=…&sig=…) stays; a playground goes to /sites. /invite is unchanged. - requireSession redirects to /login?redirect=. The login route keeps `redirect` only when it is a same-origin path (lib/login-redirect.ts: one linear pass, at most 2 kB, no `//`, `/\`, scheme, backslash or control character). LoginPage goes there after sign-in and sign-up; the OAuth `next` URL still wins. - The session guards move from router.tsx to lib/route-guards.ts. - The email field says autocomplete="username" in sign-in mode, so password managers pair it with the password; sign-up keeps `email` and `new-password`. Tests cover the redirects, the validation (including a 100k-character value) and that sign-out clears the cached session. Refs #388 (steps 1–2) Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- .changeset/studio-guest-login.md | 5 + apps/studio/src/lib/login-redirect.ts | 37 ++++ apps/studio/src/lib/route-guards.ts | 64 ++++++ apps/studio/src/router.tsx | 39 ++-- apps/studio/src/routes/LoginPage.tsx | 11 +- apps/studio/test/login-guest.test.tsx | 261 ++++++++++++++++++++++++ apps/studio/test/login-redirect.test.ts | 51 +++++ 7 files changed, 438 insertions(+), 30 deletions(-) create mode 100644 .changeset/studio-guest-login.md create mode 100644 apps/studio/src/lib/login-redirect.ts create mode 100644 apps/studio/src/lib/route-guards.ts create mode 100644 apps/studio/test/login-guest.test.tsx create mode 100644 apps/studio/test/login-redirect.test.ts diff --git a/.changeset/studio-guest-login.md b/.changeset/studio-guest-login.md new file mode 100644 index 00000000..f70253ab --- /dev/null +++ b/.changeset/studio-guest-login.md @@ -0,0 +1,5 @@ +--- +"@cloudhal/cli": patch +--- + +Studio's `/login`, `/forgot-password` and `/reset-password` no longer show their forms to a signed-in member: they go on to `/sites`, or to the page the member was opening (#388). An MCP client's authorization request (`/login?client_id=…&sig=…`) still shows the sign-in form. A signed-out member who opens a deep link now returns to it after signing in, through `/login?redirect=`, which accepts only paths on Studio's own origin. In sign-in mode the email field is marked `autocomplete="username"`, so password managers offer the saved account. diff --git a/apps/studio/src/lib/login-redirect.ts b/apps/studio/src/lib/login-redirect.ts new file mode 100644 index 00000000..ac78c2e7 --- /dev/null +++ b/apps/studio/src/lib/login-redirect.ts @@ -0,0 +1,37 @@ +/** + * Where sign-in goes next (#388): `requireSession` sends a signed-out member to + * `/login?redirect=`, and the login page goes back there afterwards. The + * value comes from the URL, so anyone can craft it: only a path on Studio's own origin is kept, + * never another site (an open redirect) or a script URL. + */ +export const MAX_REDIRECT_LENGTH = 2048; + +/** Any C0 control character, DEL, or a C1 control: browsers strip or reinterpret them in URLs. */ +function isControl(code: number): boolean { + return code < 0x20 || (code >= 0x7f && code <= 0x9f); +} + +/** + * `value` when it is a same-origin path (`/sites/a?x=1#y`), else `undefined`. Rejected: anything + * not starting with `/`, a protocol-relative start (`//`, `/\`), a scheme, a backslash or control + * character anywhere (the URL parser drops tabs and turns `\` into `/`, so `/\t/evil` would + * become `//evil`), and anything longer than 2 kB. One pass over the string, no patterns + * (AGENTS.md rule 13). + */ +export function safeRedirect(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + if (value.length === 0 || value.length > MAX_REDIRECT_LENGTH) return undefined; + if (value[0] !== "/" || value[1] === "/" || value[1] === "\\") return undefined; + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code === 0x5c || isControl(code)) return undefined; + } + // Belt and braces: whatever the browser makes of it must stay on this origin. + try { + const base = "https://studio.invalid"; + if (new URL(value, base).origin !== base) return undefined; + } catch { + return undefined; + } + return value; +} diff --git a/apps/studio/src/lib/route-guards.ts b/apps/studio/src/lib/route-guards.ts new file mode 100644 index 00000000..97de0e24 --- /dev/null +++ b/apps/studio/src/lib/route-guards.ts @@ -0,0 +1,64 @@ +import { redirect } from "@tanstack/react-router"; +import { api } from "./api.ts"; +import { authClient } from "./auth.ts"; +import { safeRedirect } from "./login-redirect.ts"; +import { cachedSession } from "./session-cache.ts"; + +/** What `beforeLoad` passes that the guards read: the address being opened. */ +interface GuardInput { + location?: { href: string; search: Record }; +} + +/** + * The signed-in session (kept between navigations, lib/session-cache.ts: asking each time held + * every screen back), and whether this deployment is a playground. RFC-0036 §5: a playground has + * no sign-in (its API refuses /api/auth with 403) and answers every call as its one fixed + * principal. A caller that shared another's request has no status of its own, so it asks too. + */ +async function sessionState(): Promise<{ session: unknown; playground: boolean }> { + const last: { status?: number } = {}; + const session = await cachedSession(async () => { + const r = await authClient.getSession(); + if (r.error) last.status = r.error.status; + return r.data; + }); + if (session) return { session, playground: false }; + return { session: null, playground: (last.status ?? 403) === 403 && (await isPlayground()) }; +} + +async function isPlayground(): Promise { + try { + return (await api.instance()).features.playground !== undefined; + } catch { + return false; + } +} + +/** + * `beforeLoad` of the signed-in screens. Signed out, it sends the member to the login page with + * the address they opened (`?redirect=`), where sign-in brings them back (#388). + */ +export async function requireSession(input: GuardInput = {}) { + const { session, playground } = await sessionState(); + if (session) return session; + if (playground) return null; + const back = input.location ? safeRedirect(input.location.href) : undefined; + throw redirect({ + to: "/login", + search: back && back !== "/" ? { redirect: back } : {}, + }); +} + +/** + * `beforeLoad` of the guest pages (`/login`, `/forgot-password`, `/reset-password`, #388): a + * signed-in member goes on to the `redirect` they came for, or to `/sites`; a playground, which + * has no sign-in, goes to `/sites`. An RFC-0044 authorization request (`?client_id=…&sig=…`) + * stays: the provider may ask a signed-in member to sign in again. + */ +export async function guestOnly(input: GuardInput = {}) { + const search = input.location?.search ?? {}; + if ("client_id" in search && "sig" in search) return; + const { session, playground } = await sessionState(); + if (session) throw redirect({ href: safeRedirect(search.redirect) ?? "/sites", replace: true }); + if (playground) throw redirect({ to: "/sites", replace: true }); +} diff --git a/apps/studio/src/router.tsx b/apps/studio/src/router.tsx index 6fa719f5..eb10ba36 100644 --- a/apps/studio/src/router.tsx +++ b/apps/studio/src/router.tsx @@ -10,11 +10,10 @@ import { import { RouteError, RoutePending } from "./components/RouteStates.tsx"; import { LOCALE_LIST, withMessages } from "./i18n/index.tsx"; import { type AnalyticsSearch, validateAnalyticsSearch } from "./lib/analytics-search.ts"; -import { api } from "./lib/api.ts"; -import { authClient } from "./lib/auth.ts"; import { isQueueTab, type QueueTab } from "./lib/comments-shell.ts"; import { listingSearch } from "./lib/listing-search.ts"; -import { cachedSession } from "./lib/session-cache.ts"; +import { safeRedirect } from "./lib/login-redirect.ts"; +import { guestOnly, requireSession } from "./lib/route-guards.ts"; import { AccountShell } from "./routes/AccountShell.tsx"; import { SiteShell } from "./routes/SiteShell.tsx"; @@ -179,34 +178,18 @@ export interface RouterContext { queryClient: QueryClient; } -async function requireSession() { - // Kept between navigations (lib/session-cache.ts): asking each time held every screen back. - const last: { status?: number } = {}; - const data = await cachedSession(async () => { - const r = await authClient.getSession(); - if (r.error) last.status = r.error.status; - return r.data; - }); - if (data) return data; - // RFC-0036 §5: a playground has no sign-in (its API refuses /api/auth with 403) and answers - // every call as its one fixed principal. - // (A caller that shared another's request has no status of its own: it asks too.) - if ((last.status ?? 403) === 403 && (await isPlayground())) return null; - throw redirect({ to: "/login" }); -} - -async function isPlayground(): Promise { - try { - return (await api.instance()).features.playground !== undefined; - } catch { - return false; - } -} - const rootRoute = createRootRouteWithContext()({ component: () => }); +/** + * Guest pages (#388): a signed-in member is sent on (`guestOnly`). `?redirect=` is where sign-in + * goes next, kept only when it is a path on this origin (`lib/login-redirect.ts`). + */ const loginRoute = createRoute({ getParentRoute: () => rootRoute, path: "/login", + validateSearch: (search: Record): { redirect?: string } => ({ + redirect: safeRedirect(search.redirect), + }), + beforeLoad: guestOnly, component: LoginPage, }); /** @@ -222,11 +205,13 @@ const inviteRoute = createRoute({ const forgotPasswordRoute = createRoute({ getParentRoute: () => rootRoute, path: "/forgot-password", + beforeLoad: guestOnly, component: ForgotPasswordPage, }); const resetPasswordRoute = createRoute({ getParentRoute: () => rootRoute, path: "/reset-password", + beforeLoad: guestOnly, component: ResetPasswordPage, }); const indexRoute = createRoute({ diff --git a/apps/studio/src/routes/LoginPage.tsx b/apps/studio/src/routes/LoginPage.tsx index 7eaf731d..2c49d8d9 100644 --- a/apps/studio/src/routes/LoginPage.tsx +++ b/apps/studio/src/routes/LoginPage.tsx @@ -1,12 +1,13 @@ import { AuthLayout, Banner, Button, Input, Link, Tabs, Text } from "@cloudhal/ui"; import { Key, SquaresFour } from "@phosphor-icons/react"; -import { useNavigate } from "@tanstack/react-router"; +import { useNavigate, useSearch } from "@tanstack/react-router"; import { type FormEvent, useEffect, useState } from "react"; import { ErrorBanner } from "../components/ErrorBanner.tsx"; import { LanguageSwitch } from "../components/LanguageSwitch.tsx"; import { PasswordField } from "../components/PasswordField.tsx"; import { useT } from "../i18n/index.tsx"; import { authClient } from "../lib/auth.ts"; +import { safeRedirect } from "../lib/login-redirect.ts"; const SETUP_KEY = "cloudhal.setupToken"; @@ -74,6 +75,8 @@ export function oauthRequest(): string | undefined { export function LoginPage() { const t = useT(); const navigate = useNavigate(); + // Where the member was going when `requireSession` sent them here (#388); same-origin paths only. + const back = safeRedirect((useSearch({ strict: false }) as { redirect?: unknown }).redirect); const [setupToken] = useState(takeSetupToken); const [authorization] = useState(oauthRequest); const [mode, setMode] = useState<"signin" | "signup">(setupToken ? "signup" : "signin"); @@ -116,7 +119,8 @@ export function LoginPage() { window.location.assign(next); return; } - await navigate({ to: "/sites" }); + if (back) await navigate({ href: back }); + else await navigate({ to: "/sites" }); } return ( @@ -174,7 +178,8 @@ export function LoginPage() { value={email} onValueChange={setEmail} required - autoComplete="email" + // Password managers pair the account with the password by `username` (#388). + autoComplete={mode === "signup" ? "email" : "username"} className="w-full" /> { + const stub: { impl?: typeof fetch } = {}; + const real = globalThis.fetch; + globalThis.fetch = ((...args: Parameters) => + (stub.impl ?? real)(...args)) as typeof fetch; + return stub; +}); + +afterEach(() => { + cleanup(); + forgetSession(); + fetchStub.impl = undefined; + window.history.replaceState(null, "", "/"); +}); + +const SESSION = { + session: { id: "s1", token: "t1", userId: "u1", expiresAt: "2999-01-01T00:00:00.000Z" }, + user: { id: "u1", name: "Ada", email: "ada@example.test" }, +}; + +/** Stubs `fetch` for the auth calls the guards and the login form make. */ +function server(opts: { signedIn: boolean; playground?: boolean }) { + const state = { signedIn: opts.signedIn }; + const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); + const fetch = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + const path = url.replace(/^https?:\/\/[^/]+/, "").split("?")[0]; + const method = ( + init?.method ?? (input instanceof Request ? input.method : "GET") + ).toUpperCase(); + if (path === "/api/auth/get-session") { + if (opts.playground) return json({ message: "forbidden" }, 403); + return json(state.signedIn ? SESSION : null); + } + if (path === "/api/auth/sign-out" && method === "POST") { + state.signedIn = false; + return json({ success: true }); + } + if (path === "/api/auth/sign-in/email" && method === "POST") { + state.signedIn = true; + return json({ redirect: false, token: "t1", user: SESSION.user }); + } + if (path === "/api/instance") { + const features = opts.playground + ? { ...INSTANCE.features, playground: { expiresAt: "2999-01-01T00:00:00.000Z" } } + : INSTANCE.features; + return json({ ...INSTANCE, features }); + } + return json({ error: "not_found", message: path }, 404); + }); + fetchStub.impl = fetch as unknown as typeof globalThis.fetch; + const sessionChecks = () => + fetch.mock.calls.filter(([u]) => String(u).includes("/api/auth/get-session")).length; + return { fetch, sessionChecks }; +} + +/** Runs a route's `beforeLoad` as the router would for `href`; the redirect it throws, if any. */ +async function beforeLoad(routeId: string, href: string) { + const router = createStudioRouter(undefined as never); + const route = router.routesById[routeId as keyof typeof router.routesById]; + const url = new URL(href, "http://studio.test"); + const location = router.parseLocation({ + pathname: url.pathname, + search: url.search, + hash: url.hash, + href, + state: {} as never, + }); + try { + await route.options.beforeLoad?.({ location, params: {}, search: location.search } as never); + return undefined; + } catch (thrown) { + return (thrown as { options?: Record }).options ?? thrown; + } +} + +describe("guest pages with a session (#388)", () => { + it("/login goes to /sites", async () => { + server({ signedIn: true }); + expect(await beforeLoad("/login", "/login")).toMatchObject({ href: "/sites", replace: true }); + }); + + it("/login?redirect=/sites/a goes to /sites/a", async () => { + server({ signedIn: true }); + expect(await beforeLoad("/login", "/login?redirect=%2Fsites%2Fa")).toMatchObject({ + href: "/sites/a", + }); + }); + + it("an unsafe redirect goes to /sites instead", async () => { + server({ signedIn: true }); + expect(await beforeLoad("/login", "/login?redirect=%2F%2Fevil.example")).toMatchObject({ + href: "/sites", + }); + }); + + it("an RFC-0044 authorization request stays, without asking for the session", async () => { + const { sessionChecks } = server({ signedIn: true }); + expect(await beforeLoad("/login", "/login?client_id=x&sig=y")).toBeUndefined(); + expect(sessionChecks()).toBe(0); + }); + + it("/forgot-password and /reset-password go on too; /invite does not check", async () => { + server({ signedIn: true }); + expect(await beforeLoad("/forgot-password", "/forgot-password")).toMatchObject({ + href: "/sites", + }); + expect(await beforeLoad("/reset-password", "/reset-password")).toMatchObject({ + href: "/sites", + }); + const router = createStudioRouter(undefined as never); + expect(router.routesById["/invite"].options.beforeLoad).toBeUndefined(); + }); + + it("a cached session costs no request", async () => { + const { sessionChecks } = server({ signedIn: true }); + await beforeLoad("/login", "/login"); + await beforeLoad("/login", "/login"); + expect(sessionChecks()).toBe(1); + }); +}); + +describe("guest pages without a session", () => { + it("/login shows the form", async () => { + server({ signedIn: false }); + expect(await beforeLoad("/login", "/login?redirect=%2Fsites%2Fa")).toBeUndefined(); + }); + + it("a playground, which has no sign-in, goes to /sites", async () => { + server({ signedIn: false, playground: true }); + expect(await beforeLoad("/login", "/login")).toMatchObject({ to: "/sites" }); + }); + + it("sign-out forgets the cached session, so /login then shows the form", async () => { + const { sessionChecks } = server({ signedIn: true }); + expect(await beforeLoad("/login", "/login")).toMatchObject({ href: "/sites" }); + await authClient.signOut(); + expect(await beforeLoad("/login", "/login")).toBeUndefined(); + expect(sessionChecks()).toBe(2); + }); +}); + +describe("a signed-out deep link", () => { + it("redirects to /login?redirect=", async () => { + server({ signedIn: false }); + const target = "/sites/a/collections/posts/e1?tab=x#top"; + expect(await beforeLoad("/sites/$siteId", target)).toMatchObject({ + to: "/login", + search: { redirect: target }, + }); + }); + + it("through the router: the URL keeps the target, and the login route validates it", async () => { + server({ signedIn: false }); + const router = createStudioRouter(undefined as never); + router.update({ + ...router.options, + history: createMemoryHistory({ initialEntries: ["/sites/a/pages"] }), + }); + await router.load(); + expect(router.state.location.pathname).toBe("/login"); + expect(safeRedirect(router.state.location.search.redirect)).toBe("/sites/a/pages"); + const validate = router.routesById["/login"].options.validateSearch as ( + s: Record, + ) => { redirect?: string }; + expect(validate({ redirect: "/sites/a" })).toEqual({ redirect: "/sites/a" }); + expect(validate({ redirect: "https://evil.example" }).redirect).toBeUndefined(); + }); +}); + +describe("LoginPage after sign-in", () => { + function renderLogin(href: string) { + const root = createRootRoute(); + const login = createRoute({ + getParentRoute: () => root, + path: "/login", + validateSearch: (s: Record) => ({ redirect: safeRedirect(s.redirect) }), + component: LoginPage, + }); + const site = createRoute({ + getParentRoute: () => root, + path: "/sites/$siteId", + component: () => site, + }); + const sites = createRoute({ + getParentRoute: () => root, + path: "/sites", + component: () => sites, + }); + const router = createRouter({ + routeTree: root.addChildren([login, site, sites]), + history: createMemoryHistory({ initialEntries: [href] }), + }); + render(wrap()); + return router; + } + + async function signIn() { + fireEvent.change(await screen.findByLabelText("Email"), { + target: { value: "ada@example.test" }, + }); + fireEvent.change(screen.getByLabelText("Password"), { target: { value: "correct horse" } }); + fireEvent.submit(screen.getByTestId("login-form")); + } + + it("goes to the validated redirect", async () => { + server({ signedIn: false }); + const router = renderLogin("/login?redirect=%2Fsites%2Fa"); + await signIn(); + expect(await screen.findByText("site")).toBeInTheDocument(); + expect(router.state.location.href).toBe("/sites/a"); + }); + + it("goes to /sites when the redirect is unsafe or missing", async () => { + server({ signedIn: false }); + const router = renderLogin("/login?redirect=%2F%2Fevil.example"); + await signIn(); + expect(await screen.findByText("sites")).toBeInTheDocument(); + expect(router.state.location.href).toBe("/sites"); + }); + + it("names the email field `username` for sign-in and `email` for a new account", async () => { + server({ signedIn: false }); + renderLogin("/login"); + expect((await screen.findByLabelText("Email")).getAttribute("autocomplete")).toBe("username"); + expect(screen.getByLabelText("Password").getAttribute("autocomplete")).toBe("current-password"); + fireEvent.click(screen.getByRole("tab", { name: "Create account" })); + await waitFor(() => + expect(screen.getByLabelText("Email").getAttribute("autocomplete")).toBe("email"), + ); + expect(screen.getByLabelText("Password").getAttribute("autocomplete")).toBe("new-password"); + }); +}); diff --git a/apps/studio/test/login-redirect.test.ts b/apps/studio/test/login-redirect.test.ts new file mode 100644 index 00000000..5323e3d9 --- /dev/null +++ b/apps/studio/test/login-redirect.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; +import { MAX_REDIRECT_LENGTH, safeRedirect } from "../src/lib/login-redirect.ts"; + +describe("safeRedirect (#388: where sign-in goes next, never off this origin)", () => { + it("keeps a path on this origin, with its query and fragment", () => { + for (const ok of ["/", "/sites", "/sites/a", "/sites/a/collections/posts/e1?tab=x#top"]) + expect(safeRedirect(ok), ok).toBe(ok); + }); + + it("refuses other sites, schemes and protocol-relative starts", () => { + for (const bad of [ + "//evil.example", + "/\\evil.example", + "https://evil.example", + "http:/evil.example", + "javascript:alert(1)", + "JavaScript:alert(1)", + "data:text/html,x", + "evil.example", + "sites/a", + " /sites", + "", + ]) + expect(safeRedirect(bad), bad).toBeUndefined(); + }); + + it("refuses backslashes and control characters anywhere (the URL parser rewrites them)", () => { + for (const bad of ["/a\\b", "/\t/evil.example", "/\n/evil.example", "/a\u0000", "/a\u007f"]) + expect(safeRedirect(bad), JSON.stringify(bad)).toBeUndefined(); + }); + + it("refuses what is not a string", () => { + for (const bad of [undefined, null, 1, ["/sites"], { href: "/sites" }]) + expect(safeRedirect(bad)).toBeUndefined(); + }); + + it("refuses more than 2 kB, and a 100k-character value at once (AGENTS.md rule 13)", () => { + const longest = `/${"a".repeat(MAX_REDIRECT_LENGTH - 1)}`; + expect(safeRedirect(longest)).toBe(longest); + expect(safeRedirect(`${longest}a`)).toBeUndefined(); + for (const huge of [ + `/${"a".repeat(100_000)}`, + `/${"/".repeat(100_000)}`, + "\\".repeat(100_000), + ]) { + const start = performance.now(); + expect(safeRedirect(huge)).toBeUndefined(); + expect(performance.now() - start).toBeLessThan(50); + } + }); +});