Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/studio-guest-login.md
Original file line number Diff line number Diff line change
@@ -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=<path>`, 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.
37 changes: 37 additions & 0 deletions apps/studio/src/lib/login-redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Where sign-in goes next (#388): `requireSession` sends a signed-out member to
* `/login?redirect=<the path they opened>`, 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;
}
64 changes: 64 additions & 0 deletions apps/studio/src/lib/route-guards.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> };
}

/**
* 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<boolean> {
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 });
}
39 changes: 12 additions & 27 deletions apps/studio/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<boolean> {
try {
return (await api.instance()).features.playground !== undefined;
} catch {
return false;
}
}

const rootRoute = createRootRouteWithContext<RouterContext>()({ component: () => <Outlet /> });
/**
* 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<string, unknown>): { redirect?: string } => ({
redirect: safeRedirect(search.redirect),
}),
beforeLoad: guestOnly,
component: LoginPage,
});
/**
Expand All @@ -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({
Expand Down
11 changes: 8 additions & 3 deletions apps/studio/src/routes/LoginPage.tsx
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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"
/>
<PasswordField
Expand Down
Loading