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
3 changes: 3 additions & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
46 changes: 44 additions & 2 deletions app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,47 @@ fn safe_return(to: &str) -> Option<String> {
&& !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<String> {
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)]
Expand Down Expand Up @@ -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::<String>("url.intended").unwrap_or_else(|| "/".to_string())),
None => Redirect::to(
session
.pull::<String>("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)))
}
Expand Down
8 changes: 8 additions & 0 deletions app/src/http/app_shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub async fn app_shell(
uri: Uri,
headers: axum::http::HeaderMap,
hosts: laravel::config::Section<HostUrls>,
auth: laravel::auth::Auth<crate::models::User>,
) -> laravel::Result<laravel::http::Response> {
let path = uri.path();
if !(method == Method::GET || method == Method::HEAD) || names_a_file(path) || path.starts_with("/api/") {
Expand All @@ -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(),
Expand Down
12 changes: 3 additions & 9 deletions app/src/http/hosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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('/')
}
}
Expand Down Expand Up @@ -195,12 +195,6 @@ pub async fn route_by_host(hosts: Section<HostUrls>, 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);
}
Expand Down
54 changes: 54 additions & 0 deletions app/tests/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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("/");
Expand Down Expand Up @@ -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(())
}
39 changes: 39 additions & 0 deletions server/frontend/src/__tests__/home.test.tsx
Original file line number Diff line number Diff line change
@@ -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: () => <main data-testid="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(<Home />)
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(<Home />)
expect(queryByTestId('landing')).toBeNull()
expect(hosts.left).toEqual(['https://visualci.com/'])
})
})
7 changes: 4 additions & 3 deletions server/frontend/src/api/hooks.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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('/'))
},
})
}
Expand Down
6 changes: 6 additions & 0 deletions server/frontend/src/lib/hosts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
16 changes: 13 additions & 3 deletions server/frontend/src/pages/Home.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="splash">
<Spinner />
Expand Down
Loading