diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 63998074..3c7a6670 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -281,6 +281,9 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.get("/auth/providers", sign_in::providers); route.post("/auth/logout", sign_in::logout); setup::routes(route); + // `/` is a route of its own: the static files would otherwise answer it with public/index.html before any route + // runs, so a signed-out visitor got the page instead of the site + route.get("/", crate::http::app_shell::app_shell); // Anything else on the web group is a page of the React app route.fallback(crate::http::app_shell::app_shell); } diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 135ff20d..dc84328e 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -60,10 +60,47 @@ fn safe_return(to: &str) -> Option { && !to.starts_with("//") && !to.contains('\\') && to.len() <= 4000 - && !to.chars().any(char::is_control)) + && !to.chars().any(char::is_control) + && is_page(to)) .then(|| to.to_string()) } +/// Whether a path is a page a person lands on, not an endpoint that answers JSON or does something: the API, the +/// sign-in routes themselves, the OAuth server's token endpoints and the MCP server. The consent page +/// (`/oauth/authorize`) is a page. (3 Dec 2026: the app's signed-out `GET /api/ui/me` was remembered as the page to +/// return to, and signing in landed on its JSON.) +fn is_page(to: &str) -> bool { + // Judged as the router reads it: `/%61pi/ui/me` and `//api` are the API too + let path = crate::http::hosts::normalized(to.split(['?', '#']).next().unwrap_or_default()); + let under = |prefix: &str| path == prefix || path.starts_with(&format!("{prefix}/")); + !(under("/api") + || under("/auth") + || under("/mcp") + || under("/webhooks") + || under("/internal") + || (under("/oauth") && !under("/oauth/authorize")) + || path.starts_with("/.well-known")) +} + +/// The page Laravel's `Authenticate` remembered (`url.intended`, the full URL of the page that sent a guest to sign +/// in) as a path on this app, if it's one a person should land on. +fn intended_page(url: &str, hosts: &crate::http::hosts::HostUrls) -> Option { + let parsed = url::Url::parse(url).ok()?; + // Configured hosts: only the app's own pages. Without them one origin serves everything, and the URL is the + // request's own. + if let Some(app) = hosts.app.as_deref().map(str::trim).filter(|a| !a.is_empty()) { + let app = url::Url::parse(app).ok()?; + if parsed.host_str() != app.host_str() { + return None; + } + } + let mut path = parsed.path().to_string(); + if let Some(query) = parsed.query() { + path = format!("{path}?{query}"); + } + safe_return(&path) +} + /// `GET /login`: where a page that needs a signed-in person (an MCP client's consent page) sends someone who isn't, /// and where they come back from afterwards (sign-in returns to the page they were sent from). One line per forge. #[laravel::auth::page(login)] @@ -161,7 +198,12 @@ pub async fn callback( Some(to) => Redirect::to(to), // Laravel's `Authenticate` keeps the page it sent them from under this key (`Redirect::intended`, which // needs a route for its fallback) - None => Redirect::to(session.pull::("url.intended").unwrap_or_else(|| "/".to_string())), + None => Redirect::to( + session + .pull::("url.intended") + .and_then(|url| intended_page(&url, &hosts)) + .unwrap_or_else(|| "/".to_string()), + ), }; Ok(laravel::http::Response::new(back).with_cookie(signed_in_hint(&hosts, true))) } diff --git a/app/src/http/app_shell.rs b/app/src/http/app_shell.rs index 423aec88..0950eacc 100644 --- a/app/src/http/app_shell.rs +++ b/app/src/http/app_shell.rs @@ -23,6 +23,7 @@ pub async fn app_shell( uri: Uri, headers: axum::http::HeaderMap, hosts: laravel::config::Section, + auth: laravel::auth::Auth, ) -> laravel::Result { let path = uri.path(); if !(method == Method::GET || method == Method::HEAD) || names_a_file(path) || path.starts_with("/api/") { @@ -34,6 +35,13 @@ pub async fn app_shell( if configured && hosts.classify(&host.to_ascii_lowercase()) != Some(Host::App) { return Err(laravel::abort(404)); } + // `/` on the app is the list of your organizations. Signed out, it's the site: the landing page never shows on + // the app. This reads the session, not whether its cookie is there: signing out leaves a new, signed-out session + // (3 Dec 2026, "Sign out" landed on the landing page at app.visualci.com). + if configured && path == "/" && auth.user().await?.is_none() { + let site = laravel::http::Redirect::to(format!("{}/", hosts.site())).status(307); + return Ok(laravel::http::Response::new(site).with_header("cache-control", "no-store")); + } // The page the security policy was built from at boot; read now only when there was none then (a dev server) let html = match super::security::index_html() { Some(html) => html.to_string(), diff --git a/app/src/http/hosts.rs b/app/src/http/hosts.rs index 2970b60c..d3605a72 100644 --- a/app/src/http/hosts.rs +++ b/app/src/http/hosts.rs @@ -6,8 +6,8 @@ //! - the MCP server (`mcp.visualci.com`): `/mcp` and the OAuth endpoints MCP clients call. //! //! The site (`visualci.com`) is a static Cloudflare Worker; a request for it that reaches the server anyway gets a 404, -//! and so does any path a host doesn't serve. The one redirect is the app's `/` for a visitor without a session, which -//! goes to the landing page. `/up` answers on every host. +//! and so does any path a host doesn't serve. The app's `/` sends a signed-out visitor to the site (`app_shell`, which +//! reads the session). `/up` answers on every host. //! //! In production, a request for any other host (a pod's own address for probes, the cluster-internal address the //! renderers use) reaches only `/up` and the renderers' `/internal` paths. Elsewhere (a dev server) it gets every path, @@ -60,7 +60,7 @@ impl HostUrls { .map(|(host, _)| host) } - fn site(&self) -> &str { + pub fn site(&self) -> &str { self.site.as_deref().unwrap_or("").trim_end_matches('/') } } @@ -195,12 +195,6 @@ pub async fn route_by_host(hosts: Section, request: Request, next: Nex } return next.run(request).await; }; - // `/` on the app is the list of your organizations; without a session, the landing page. The session cookie is - // the framework's own (`SESSION_COOKIE`, else its default), so this can't drift from the cookie sign-in sets. - if here == Host::App && path == "/" && request.cookie(&laravel::config().session.cookie).is_none() { - return Response::new(laravel::http::Redirect::to(format!("{}/", hosts.site())).status(307)) - .with_header("cache-control", "no-store"); - } if !serves(here, &path) { return not_found(&hosts); } diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs index d516b9c9..18ae82cf 100644 --- a/app/tests/sign_in.rs +++ b/app/tests/sign_in.rs @@ -90,6 +90,9 @@ async fn an_unsafe_return_address_is_ignored(app: Application) -> laravel::Resul let long = format!("/{}", "a".repeat(4000)); for to in ["//evil.example/x", "/%09/evil.example", "/%0a/evil.example", "/%0d/evil.example", "/%5C/evil.example", &long] + .into_iter() + // Not pages: JSON endpoints, the sign-in itself, the OAuth server's token endpoint and the MCP server + .chain(["/api/ui/me", "/%2561pi/ui/me", "/auth/github", "/oauth/token", "/mcp", "/webhooks/github"]) { let start = app.get(format!("/auth/github?return_to={to}")).await; app.get("/auth/github/callback").with_cookies_from(&start).await.assert_redirect_to("/"); @@ -350,3 +353,54 @@ async fn signing_in_from_the_site_lands_in_the_app(app: Application) -> laravel: app.get("/").header("host", host).await.assert_redirect_to("https://visualci.test/"); Ok(()) } + +/// Signing out on the app lands on the site: the app's `/` reads the session, and signing out leaves a new, signed-out +/// one behind, so the cookie being there means nothing (3 Dec 2026: "Sign out" showed the landing page at +/// app.visualci.com). +#[laravel::test(app = four_hosts)] +async fn signing_out_lands_on_the_site(app: Application) -> laravel::Result<()> { + let _github = github(); + let _social = social::fake().with(Provider::GITHUB, ada()); + let host = "app.visualci.test"; + + let done = app.get("/auth/github/callback").header("host", host).await; + app.get("/").header("host", host).with_cookies_from(&done).await.assert_ok(); + let out = app + .post("/auth/logout") + .header("host", host) + .header("sec-fetch-site", "same-origin") + .with_cookies_from(&done) + .await; + out.assert_ok(); + // The browser keeps the session cookie the sign-out answered with + let front = app.get("/").header("host", host).with_cookies_from(&done).with_cookies_from(&out).await; + front.assert_status(307); + front.assert_redirect_to("https://visualci.test/"); + app.get("/auth/session") + .header("host", host) + .with_cookies_from(&done) + .with_cookies_from(&out) + .await + .assert_json_path("signed_in", false); + Ok(()) +} + +/// A signed-out request the app's page made to its API never becomes the page sign-in returns to: signing in from the +/// site lands on the app's `/` (3 Dec 2026: the page's `GET /api/ui/me`, sent without asking for JSON, was redirected +/// to sign in and remembered, and signing in from the site then landed on its JSON). +#[laravel::test(app = four_hosts)] +async fn signing_in_never_returns_to_an_api_path(app: Application) -> laravel::Result<()> { + let _github = github(); + let _social = social::fake().with(Provider::GITHUB, ada()); + let host = "app.visualci.test"; + + // As the page's client asked before it sent Accept: a browser-looking request, which Laravel redirects to sign in + let me = app.get("/api/ui/me").header("host", host).header("accept", "text/html").await; + let start = app.get("/auth/github").header("host", host).with_cookies_from(&me).await; + start.assert_redirect(); + let done = + app.get("/auth/github/callback").header("host", host).with_cookies_from(&me).with_cookies_from(&start).await; + done.assert_redirect_to("/"); + app.get("/").header("host", host).with_cookies_from(&done).await.assert_ok(); + Ok(()) +} diff --git a/server/frontend/src/__tests__/home.test.tsx b/server/frontend/src/__tests__/home.test.tsx new file mode 100644 index 00000000..d02467e4 --- /dev/null +++ b/server/frontend/src/__tests__/home.test.tsx @@ -0,0 +1,39 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render } from '@testing-library/react' + +// `/` signed out: the landing page on the site's host or a single-origin server, never on the app's own host, which +// goes to the site instead (3 Dec 2026: "Sign out" showed the landing page at app.visualci.com). +const hosts = vi.hoisted(() => ({ app: false, left: [] as string[] })) +vi.mock('../lib/hosts', () => ({ + onAppHost: () => hosts.app, + siteUrl: (path = '/') => `https://visualci.com${path}`, + leaveFor: (url: string) => hosts.left.push(url), +})) +vi.mock('@tanstack/react-router', () => ({ + Navigate: () => null, + getRouteApi: () => ({ useSearch: () => ({}) }), +})) +vi.mock('../api/hooks', () => ({ useMe: () => ({ isPending: false, data: null }) })) +vi.mock('../pages/Landing', () => ({ Landing: () =>
})) +vi.mock('../components/AppShell', () => ({ AppShell: () => null })) +vi.mock('../pages/OrgsPage', () => ({ OrgsPage: () => null })) + +const { Home } = await import('../pages/Home') + +describe('the front page, signed out', () => { + afterEach(cleanup) + it('is the landing page off the app host', () => { + hosts.app = false + hosts.left = [] + const { queryByTestId } = render() + expect(queryByTestId('landing')).not.toBeNull() + expect(hosts.left).toEqual([]) + }) + it('never renders the landing page on the app host, and goes to the site', () => { + hosts.app = true + hosts.left = [] + const { queryByTestId } = render() + expect(queryByTestId('landing')).toBeNull() + expect(hosts.left).toEqual(['https://visualci.com/']) + }) +}) diff --git a/server/frontend/src/api/hooks.ts b/server/frontend/src/api/hooks.ts index 423be142..409ae448 100644 --- a/server/frontend/src/api/hooks.ts +++ b/server/frontend/src/api/hooks.ts @@ -1,4 +1,5 @@ import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { siteUrl } from '../lib/hosts' import { ApiError, del, get, patch, post, request } from './client' import type { EmailPreview, @@ -137,12 +138,12 @@ export function useLogout() { const qc = useQueryClient() return useMutation({ mutationFn: () => post('/auth/logout'), - // A full navigation to the sign-in page: clearing the cache alone left the page on screen until a refresh, since - // the mounted queries kept their old data. + // A full navigation to the site (clearing the cache alone left the page on screen until a refresh, since the + // mounted queries kept their old data). On visualci.com that's visualci.com itself, never the app's `/`. onSuccess: () => { qc.setQueryData(keys.me, null) qc.clear() - window.location.assign('/') + window.location.assign(siteUrl('/')) }, }) } diff --git a/server/frontend/src/lib/hosts.ts b/server/frontend/src/lib/hosts.ts index 0415f8c8..1c5abc27 100644 --- a/server/frontend/src/lib/hosts.ts +++ b/server/frontend/src/lib/hosts.ts @@ -14,3 +14,9 @@ export const siteUrl = (path = '/') => `${base('')}${path}` export const appUrl = (path = '/') => `${base('app')}${path}` export const apiUrl = () => base('api') export const mcpUrl = () => `${base('mcp')}/mcp` + +/** Whether this page is the app on its own host (app.visualci.com), where the landing page never shows. */ +export const onAppHost = () => typeof window !== 'undefined' && window.location.hostname === `app.${DOMAIN}` + +/** Leave for another page, replacing this one in the history (a function of its own so tests can see it). */ +export const leaveFor = (url: string) => window.location.replace(url) diff --git a/server/frontend/src/pages/Home.tsx b/server/frontend/src/pages/Home.tsx index e918c484..e2ed7d51 100644 --- a/server/frontend/src/pages/Home.tsx +++ b/server/frontend/src/pages/Home.tsx @@ -1,20 +1,30 @@ import { Navigate, getRouteApi } from '@tanstack/react-router' +import { useEffect } from 'react' import { useMe } from '../api/hooks' import { AppShell } from '../components/AppShell' import { Spinner } from '../components/ui' +import { leaveFor, onAppHost, siteUrl } from '../lib/hosts' import { Landing } from './Landing' import { OrgsPage } from './OrgsPage' const route = getRouteApi('/') /** - * `/` is the landing page when signed out. Signed in with one organization, it goes straight to that organization - * (where setup starts), replacing this entry so Back doesn't bounce; with several, or `?all=1`, it lists them. + * `/` is the landing page when signed out, on the site's host or a single-origin server (never on the app's own host). + * Signed in with one organization, it goes straight to that organization (where setup starts), replacing this entry so + * Back doesn't bounce; with several, or `?all=1`, it lists them. */ export function Home() { const me = useMe() const { all } = route.useSearch() - if (me.isPending) { + // Signed out on the app's own host: the site. The landing page shows only on the site (and on a single-origin dev + // server or self-hosted install); the server sends a signed-out `/` there too, so this is only for a session that + // ended while the page was open. + const leave = !me.isPending && !me.data && onAppHost() + useEffect(() => { + if (leave) leaveFor(siteUrl('/')) + }, [leave]) + if (me.isPending || leave) { return (