Skip to main content

agentmux_srv/server/
local_session_routes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The browser sign-in of a headless srv that serves its own UI (`--frontend-dir`) on loopback:
5//! the `/auth/*` routes, the check that admits a browser's session in [`auth_middleware`], and the
6//! headers of the served UI. The sessions themselves are in [`super::local_session`].
7//!
8//! Every answer to a failed sign-in route is the same 403 `not accepted`, after the same short wait,
9//! whatever was wrong; the reason goes to the log only, never the secret.
10//! The routes are registered here, not in `routes.rs`: they authenticate themselves (a container
11//! token never reaches them: its listener refuses a path with no audience).
12
13use std::sync::OnceLock;
14use std::time::{Duration, Instant};
15
16use axum::body::Bytes;
17use axum::extract::{ConnectInfo, DefaultBodyLimit};
18use axum::http::{HeaderMap, HeaderValue};
19use serde::Deserialize;
20
21use super::local_proof::{self, Admitted, Channels};
22use super::local_session::{CodeState, Collected, ConfirmHow, RouteClass, SessionId, SessionStore, LOGGED_FAILURES};
23use super::*;
24
25/// The cookie's name is this, then the instance id.
26const COOKIE_PREFIX: &str = "amx-s-";
27/// The per-tab token on a fetch.
28pub(crate) const TOKEN_HEADER: &str = "x-am-session";
29/// The protocol srv selects on `/ws`; the other protocol the page offers is the token.
30pub(crate) const WS_PROTOCOL: &str = "amx-session";
31/// A refused sign-in waits this long before it answers, in an async sleep.
32const FAILURE_DELAY: Duration = Duration::from_millis(250);
33/// At most this many refusals wait at once; beyond it a refusal answers at once.
34const MAX_DELAYED: usize = 64;
35/// How long a waiting page's request is held before it asks again.
36const WAIT_HOLD: Duration = Duration::from_secs(20);
37/// Routes that take the cookie alone: GETs that change nothing and that an element loads by URL.
38/// The UI fetches every file with its headers, so none needs it; each entry added here is a
39/// reviewed decision, and the test in `tests/local_session_route_tests.rs` holds it to a GET route.
40pub(crate) const COOKIE_ONLY_GET: &[&str] = &[];
41
42/// What the running server accepts: set once the web listener is bound.
43struct Shape {
44    cookie_name: String,
45    /// Exactly the origins a page may have: `http://127.0.0.1:<port>`, and the declared one.
46    origins: Vec<String>,
47}
48
49impl Shape {
50    fn new(port: u16, instance_id: &str, declared: Option<&str>) -> Shape {
51        let id: String = instance_id.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
52        let mut origins = vec![format!("http://127.0.0.1:{port}")];
53        origins.extend(declared.map(str::to_string).filter(|o| *o != origins[0]));
54        Shape { cookie_name: format!("{COOKIE_PREFIX}{id}"), origins }
55    }
56
57    fn host_ok(&self, host: &str) -> bool {
58        self.origins.iter().any(|o| o.strip_prefix("http://") == Some(host))
59    }
60
61    /// The address srv is bound to, as `host:port`: what its proof to `open` covers.
62    fn bound(&self) -> &str {
63        self.origins[0].strip_prefix("http://").unwrap_or(&self.origins[0])
64    }
65
66    /// The other origin it accepts, or empty.
67    fn declared(&self) -> &str {
68        self.origins.get(1).map_or("", String::as_str)
69    }
70}
71
72static SHAPE: OnceLock<Shape> = OnceLock::new();
73static STORE: OnceLock<SessionStore> = OnceLock::new();
74static CHANNELS: OnceLock<Channels> = OnceLock::new();
75/// What ends the server: the token the signal handlers cancel. `agentmux stop` on Windows, which has no signal to
76/// send, asks for it through `/auth/shutdown`.
77static SHUTDOWN: std::sync::Mutex<Option<tokio_util::sync::CancellationToken>> = std::sync::Mutex::new(None);
78
79fn store() -> &'static SessionStore {
80    STORE.get_or_init(SessionStore::default)
81}
82
83/// Whether something here can vouch for a browser's connection as the person's: this srv serves its own
84/// sign-in, or a browser has signed in.
85pub(crate) fn sign_in_exists() -> bool {
86    crate::headless::local_sign_in() || store().session_count(std::time::Instant::now()) > 0
87}
88
89fn channels() -> &'static Channels {
90    CHANNELS.get_or_init(Channels::default)
91}
92
93/// Turn the sign-in on, once the web listener has its port. Only for a headless srv that serves a UI.
94pub(crate) fn enable(port: u16, instance_id: &str) {
95    if crate::headless::local_sign_in() {
96        let _ = SHAPE.set(Shape::new(port, instance_id, crate::headless::public_origin()));
97        crate::headless::publish_port(port);
98        if let Some((path, binding)) = crate::headless::session_file() {
99            store().keep_in(path, binding, Instant::now(), agentmux_common::time::now_secs_u64());
100        }
101    }
102}
103
104/// Give the shutdown route the token that ends the server.
105pub(crate) fn set_shutdown(token: tokio_util::sync::CancellationToken) {
106    *SHUTDOWN.lock().unwrap_or_else(|e| e.into_inner()) = Some(token);
107}
108
109pub(crate) fn enabled() -> bool {
110    SHAPE.get().is_some()
111}
112
113/// The `/auth/*` routes.
114pub(crate) fn routes() -> Router<AppState> {
115    Router::new()
116        .route("/auth/hello", post(handle_hello))
117        .route("/auth/code", post(handle_code))
118        .route("/auth/pending", post(handle_pending))
119        .route("/auth/confirm", post(handle_confirm))
120        .route("/auth/logout", post(handle_logout))
121        .route("/auth/sessions", post(handle_sessions))
122        .route("/auth/shutdown", post(handle_shutdown))
123        .route("/auth/enter", get(handle_page).post(handle_enter))
124        .route("/auth/enter.js", get(handle_script))
125        .route("/auth/enter.css", get(handle_style))
126        .route("/auth/wait", post(handle_wait))
127        .route("/auth/signout", post(handle_signout))
128        .route("/auth/signout-all", post(handle_signout_all))
129        .layer(DefaultBodyLimit::max(1024))
130}
131
132// ---- Who may ask ----
133
134/// Why a request was refused. For the log; the answer never says.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136enum Reason {
137    Code,
138    Host,
139    Origin,
140    FetchSite,
141    Proof,
142    Session,
143}
144
145impl Reason {
146    fn name(self) -> &'static str {
147        match self {
148            Reason::Code => "code",
149            Reason::Host => "host",
150            Reason::Origin => "origin",
151            Reason::FetchSite => "fetch-site",
152            Reason::Proof => "proof",
153            Reason::Session => "session",
154        }
155    }
156}
157
158#[derive(Clone, Copy, PartialEq, Eq)]
159enum Kind {
160    /// `agentmux-srv open`: no browser headers at all.
161    Client,
162    /// The sign-in page's own requests: same-origin.
163    Browser,
164    /// A page load or a session's request: only Host and Origin are held to.
165    Any,
166}
167
168fn hval<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
169    headers.get(name).and_then(|v| v.to_str().ok())
170}
171
172/// `Host` is exactly an allowed one, `Origin` (where sent) is exactly an allowed origin, and
173/// `Sec-Fetch-Site` suits the kind. A missing or unreadable header counts as wrong.
174fn check_shape(shape: &Shape, headers: &HeaderMap, kind: Kind) -> Result<(), Reason> {
175    if !hval(headers, "host").is_some_and(|h| shape.host_ok(h)) {
176        return Err(Reason::Host);
177    }
178    if let Some(origin) = headers.get(header::ORIGIN) {
179        if !origin.to_str().is_ok_and(|o| shape.origins.iter().any(|x| x == o)) {
180            return Err(Reason::Origin);
181        }
182    }
183    let site = headers.get("sec-fetch-site");
184    let site_ok = match kind {
185        Kind::Client => site.is_none(),
186        Kind::Browser => site.is_some_and(|s| s == "same-origin"),
187        Kind::Any => true,
188    };
189    if site_ok { Ok(()) } else { Err(Reason::FetchSite) }
190}
191
192/// The same 403 for every refusal, in the same time: the wait is the same for every reason.
193async fn refuse(route: &'static str, reason: Reason) -> Response {
194    static DELAYED: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(MAX_DELAYED);
195    let recent = store().note_failure(Instant::now());
196    match recent {
197        n if n <= LOGGED_FAILURES => tracing::warn!(route, reason = reason.name(), failures_last_minute = n, "local sign-in refused"),
198        n if n == LOGGED_FAILURES + 1 => tracing::warn!(failures_last_minute = n, "local sign-in refused again and again: more this minute are counted, not logged"),
199        _ => {}
200    }
201    if let Ok(_slot) = DELAYED.try_acquire() {
202        tokio::time::sleep(FAILURE_DELAY).await;
203    }
204    refusal()
205}
206
207fn refusal() -> Response {
208    let mut r = (StatusCode::FORBIDDEN, "not accepted").into_response();
209    r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
210    r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
211    r
212}
213
214fn no_store(mut r: Response) -> Response {
215    r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
216    r
217}
218
219/// `open` and the other commands: the shape of a non-browser caller, and a request that proves the
220/// caller holds the key on a channel it began with [`handle_hello`]. The key itself is never sent,
221/// and is not accepted on these routes.
222async fn channel_gate(headers: &HeaderMap, route: &'static str, body: &[u8]) -> Result<Admitted, Response> {
223    let Some(shape) = SHAPE.get() else { return Err(refusal()) };
224    if let Err(reason) = check_shape(shape, headers, Kind::Client) {
225        return Err(refuse(route, reason).await);
226    }
227    let seq = hval(headers, local_proof::SEQ_HEADER).and_then(|s| s.parse::<u64>().ok());
228    let admitted = match (hval(headers, local_proof::CHANNEL_HEADER), seq, hval(headers, local_proof::PROOF_HEADER)) {
229        (Some(channel), Some(seq), Some(proof)) => channels().admit(channel, seq, "POST", route, body, proof, Instant::now()),
230        _ => None,
231    };
232    match admitted {
233        Some(a) => Ok(a),
234        None => Err(refuse(route, Reason::Proof).await),
235    }
236}
237
238/// A 200 answer that carries the proof of the channel for the request it answers.
239fn proved(admitted: &Admitted, value: serde_json::Value) -> Response {
240    let body = serde_json::to_vec(&value).unwrap_or_default();
241    let proof = local_proof::response_proof(&admitted.key, admitted.seq, 200, &body);
242    let mut r = (StatusCode::OK, body).into_response();
243    r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
244    if let Ok(v) = HeaderValue::from_str(&proof) {
245        r.headers_mut().insert(local_proof::PROOF_HEADER, v);
246    }
247    no_store(r)
248}
249
250#[derive(Deserialize)]
251struct HelloBody {
252    nonce: String,
253}
254
255#[derive(Deserialize)]
256struct CodeBody {
257    code: String,
258}
259
260#[derive(Deserialize)]
261struct ConfirmBody {
262    code: String,
263    accept: bool,
264}
265
266#[derive(Deserialize)]
267struct HandleBody {
268    handle: String,
269}
270
271// ---- The commands' routes (a proof of the key) ----
272
273/// `POST /auth/hello {nonce}`: srv proves to `open` that it holds the key and which address it is
274/// bound to, before `open` sends anything else. It asks for no secret, so anyone may call it; what it
275/// returns proves only what srv holds, and is made for this caller's nonce alone.
276async fn handle_hello(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
277    let Some(shape) = SHAPE.get() else { return refusal() };
278    if let Err(reason) = check_shape(shape, &headers, Kind::Client) {
279        return refuse("/auth/hello", reason).await;
280    }
281    let Ok(HelloBody { nonce }) = serde_json::from_slice(&body) else { return refuse("/auth/hello", Reason::Code).await };
282    let Some(hello) = channels().hello(state.auth_key.as_bytes(), &nonce, shape.bound(), shape.declared(), Instant::now()) else {
283        return refuse("/auth/hello", Reason::Code).await;
284    };
285    no_store(Json(json!({ "channel": hello.channel, "nonce": hello.nonce, "declared": shape.declared(), "proof": hello.proof })).into_response())
286}
287
288/// `POST /auth/code`: a new one-time code.
289async fn handle_code(headers: HeaderMap, body: Bytes) -> Response {
290    let admitted = match channel_gate(&headers, "/auth/code", &body).await {
291        Ok(a) => a,
292        Err(r) => return r,
293    };
294    proved(&admitted, json!({ "code": store().mint_code(Instant::now()) }))
295}
296
297/// `POST /auth/pending {code}`: what became of the code `open` minted.
298async fn handle_pending(headers: HeaderMap, body: Bytes) -> Response {
299    let admitted = match channel_gate(&headers, "/auth/pending", &body).await {
300        Ok(a) => a,
301        Err(r) => return r,
302    };
303    let Ok(CodeBody { code }) = serde_json::from_slice(&body) else { return refuse("/auth/pending", Reason::Code).await };
304    let state = match store().code_state(&code, Instant::now()) {
305        CodeState::Unused => json!({ "state": "unused" }),
306        CodeState::Entered { phrase } => json!({ "state": "entered", "phrase": phrase }),
307        CodeState::Gone => json!({ "state": "gone" }),
308    };
309    proved(&admitted, state)
310}
311
312/// `POST /auth/confirm {code, accept}`: the person's answer for the session that code made. An accept is taken only from a
313/// process found outside every agent's process tree; one from an agent's tree, from a process that cannot be found, or through
314/// a proxy is not taken (the answer says what works). Every accept, taken or not, is recorded with how it arrived
315/// ([`super::confirm_peer`]).
316async fn handle_confirm(
317    State(state): State<AppState>,
318    conn: Option<ConnectInfo<super::confirm_peer::Conn>>,
319    headers: HeaderMap,
320    body: Bytes,
321) -> Response {
322    let admitted = match channel_gate(&headers, "/auth/confirm", &body).await {
323        Ok(a) => a,
324        Err(r) => return r,
325    };
326    let Ok(ConfirmBody { code, accept }) = serde_json::from_slice(&body) else { return refuse("/auth/confirm", Reason::Code).await };
327    if accept {
328        let how = match conn {
329            Some(ConnectInfo(conn)) => super::confirm_peer::classify(&state, conn, super::confirm_peer::is_forwarded(&headers)).await,
330            None => ConfirmHow::Unknown,
331        };
332        let found = store().note_confirm(&code, how.clone(), Instant::now());
333        if !how.is_taken() {
334            tracing::warn!(found, how = %how.label(), "local sign-in confirm not taken");
335            return proved(&admitted, json!({ "found": false, "refused": super::confirm_peer::refusal_text(&how) }));
336        }
337    }
338    let found = store().decide(&code, accept, Instant::now());
339    tracing::info!(accepted = accept && found, found, "local sign-in answered");
340    proved(&admitted, json!({ "found": found }))
341}
342
343/// `POST /auth/logout`: end every browser session.
344async fn handle_logout(headers: HeaderMap, body: Bytes) -> Response {
345    let admitted = match channel_gate(&headers, "/auth/logout", &body).await {
346        Ok(a) => a,
347        Err(r) => return r,
348    };
349    let revoked = store().revoke_all();
350    tracing::info!(revoked, "local sign-in sessions revoked");
351    proved(&admitted, json!({ "revoked": revoked }))
352}
353
354/// `POST /auth/sessions`: how many browsers are signed in now, and how each recent confirm arrived (when, the session's check
355/// phrase, how). Nothing that names or reaches a session.
356async fn handle_sessions(headers: HeaderMap, body: Bytes) -> Response {
357    let admitted = match channel_gate(&headers, "/auth/sessions", &body).await {
358        Ok(a) => a,
359        Err(r) => return r,
360    };
361    let confirms: Vec<_> = store()
362        .confirms()
363        .iter()
364        .map(|c| json!({ "at_unix_ms": c.at_unix_ms, "session": c.session, "how": c.how.label() }))
365        .collect();
366    proved(&admitted, json!({ "sessions": store().session_count(Instant::now()), "confirms": confirms }))
367}
368
369/// `POST /auth/shutdown`: end the server, as a termination signal does. The answer is sent first; the server leaves a
370/// moment later, by the same path as the signal (every request in flight and every agent is closed as it is then).
371async fn handle_shutdown(headers: HeaderMap, body: Bytes) -> Response {
372    let admitted = match channel_gate(&headers, "/auth/shutdown", &body).await {
373        Ok(a) => a,
374        Err(r) => return r,
375    };
376    let token = SHUTDOWN.lock().unwrap_or_else(|e| e.into_inner()).clone();
377    let known = token.is_some();
378    if let Some(token) = token {
379        tracing::info!("shutdown asked for by `agentmux stop`");
380        tokio::spawn(async move {
381            tokio::time::sleep(Duration::from_millis(300)).await;
382            token.cancel();
383        });
384    }
385    proved(&admitted, json!({ "stopping": known }))
386}
387
388// ---- The browser's routes (the code) ----
389
390/// `GET /auth/enter`: the page. It holds no secret; the code is in the fragment, which is never sent.
391async fn handle_page(headers: HeaderMap) -> Response {
392    let Some(shape) = SHAPE.get() else { return refusal() };
393    if let Err(reason) = check_shape(shape, &headers, Kind::Any) {
394        return refuse("/auth/enter", reason).await;
395    }
396    with_ui_headers(shape, no_store(([(header::CONTENT_TYPE, "text/html; charset=utf-8")], ENTER_HTML).into_response()))
397}
398
399async fn handle_script() -> Response {
400    let Some(shape) = SHAPE.get() else { return refusal() };
401    with_ui_headers(shape, no_store(([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], ENTER_JS).into_response()))
402}
403
404async fn handle_style() -> Response {
405    let Some(shape) = SHAPE.get() else { return refusal() };
406    with_ui_headers(shape, no_store(([(header::CONTENT_TYPE, "text/css; charset=utf-8")], ENTER_CSS).into_response()))
407}
408
409/// `POST /auth/enter {code}`: spends the code and makes a pending session; the answer is the
410/// handle to wait on and the check phrase to show. The session has no access yet.
411async fn handle_enter(headers: HeaderMap, body: Bytes) -> Response {
412    let Some(shape) = SHAPE.get() else { return refusal() };
413    if let Err(reason) = check_shape(shape, &headers, Kind::Browser) {
414        return refuse("/auth/enter", reason).await;
415    }
416    let entered = serde_json::from_slice::<CodeBody>(&body).ok().and_then(|b| store().enter(&b.code, Instant::now()));
417    match entered {
418        Some(e) => no_store(Json(json!({ "handle": e.handle, "phrase": e.phrase })).into_response()),
419        None => refuse("/auth/enter", Reason::Code).await,
420    }
421}
422
423/// `POST /auth/wait {handle}`: held until the person answers in the terminal. A confirmed session
424/// is handed over once, here: the cookie in `Set-Cookie` and the token in the body.
425async fn handle_wait(headers: HeaderMap, body: Bytes) -> Response {
426    let Some(shape) = SHAPE.get() else { return refusal() };
427    if let Err(reason) = check_shape(shape, &headers, Kind::Browser) {
428        return refuse("/auth/wait", reason).await;
429    }
430    let Ok(HandleBody { handle }) = serde_json::from_slice(&body) else { return refuse("/auth/wait", Reason::Code).await };
431    let until = Instant::now() + WAIT_HOLD;
432    loop {
433        match store().collect(&handle, Instant::now()) {
434            Collected::Granted(grant) => {
435                let cookie = format!("{}={}; HttpOnly; SameSite=Strict; Path=/", shape.cookie_name, grant.cookie);
436                let mut r = no_store(Json(json!({ "token": grant.token })).into_response());
437                if let Ok(v) = HeaderValue::from_str(&cookie) {
438                    r.headers_mut().insert(header::SET_COOKIE, v);
439                }
440                return r;
441            }
442            Collected::Refused => return refuse("/auth/wait", Reason::Code).await,
443            Collected::Waiting if Instant::now() >= until => return no_store((StatusCode::ACCEPTED, Json(json!({ "waiting": true }))).into_response()),
444            Collected::Waiting => tokio::time::sleep(Duration::from_millis(200)).await,
445        }
446    }
447}
448
449/// `POST /auth/signout`: end this browser's session, and no other. It takes the session pair like any
450/// route of the UI, from a same-origin fetch of the page; srv also tells the browser to drop the cookie.
451async fn handle_signout(req: Request<Body>) -> Response {
452    let Some(shape) = SHAPE.get() else { return refusal() };
453    if let Err(reason) = check_shape(shape, req.headers(), Kind::Browser) {
454        return refuse("/auth/signout", reason).await;
455    }
456    let Some(session) = admit_session(&req) else { return refuse("/auth/signout", Reason::Session).await };
457    let ended = store().revoke(session, Instant::now());
458    tracing::info!(ended, "local sign-in session signed out");
459    let mut r = no_store(Json(json!({ "signedOut": ended })).into_response());
460    let cleared = format!("{}=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/", shape.cookie_name);
461    if let Ok(v) = HeaderValue::from_str(&cleared) {
462        r.headers_mut().insert(header::SET_COOKIE, v);
463    }
464    r
465}
466
467/// `POST /auth/signout-all`: end every browser session, this one included, and clear the file that keeps them across a restart. It
468/// takes the session pair like any route of the UI, so a signed-in person can end every sign-in without a shell on the machine.
469async fn handle_signout_all(req: Request<Body>) -> Response {
470    let Some(shape) = SHAPE.get() else { return refusal() };
471    if let Err(reason) = check_shape(shape, req.headers(), Kind::Browser) {
472        return refuse("/auth/signout-all", reason).await;
473    }
474    if admit_session(&req).is_none() {
475        return refuse("/auth/signout-all", Reason::Session).await;
476    }
477    let ended = store().revoke_all();
478    tracing::info!(ended, "every local sign-in session signed out from a browser");
479    let mut r = no_store(Json(json!({ "signedOut": ended })).into_response());
480    let cleared = format!("{}=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/", shape.cookie_name);
481    if let Ok(v) = HeaderValue::from_str(&cleared) {
482        r.headers_mut().insert(header::SET_COOKIE, v);
483    }
484    r
485}
486
487// ---- A browser's session on any other route ----
488
489/// How a route takes a session. Every route needs the cookie and the token, except the GETs named
490/// in [`COOKIE_ONLY_GET`].
491pub(crate) fn route_class(method: &Method, path: &str) -> RouteClass {
492    use crate::backend::route_audience::Match;
493    let listed = *method == Method::GET && COOKIE_ONLY_GET.iter().any(|pattern| Match::Route(*pattern).matches(path));
494    if listed { RouteClass::CookieOnly } else { RouteClass::Both }
495}
496
497fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
498    hval(headers, "cookie")?.split(';').filter_map(|c| c.trim().split_once('=')).find(|(n, _)| *n == name).map(|(_, v)| v)
499}
500
501/// The routes a browser opens as a WebSocket, which can carry no header: the token travels as a protocol.
502fn is_websocket_route(path: &str) -> bool {
503    path == "/ws" || path == super::streamed_browser::ROUTE
504}
505
506/// The token a request carries: `X-AM-Session`, or on a WebSocket route the protocol offered beside [`WS_PROTOCOL`].
507fn session_token<'a>(headers: &'a HeaderMap, path: &str) -> Option<&'a str> {
508    if let Some(t) = hval(headers, TOKEN_HEADER) {
509        return Some(t);
510    }
511    if !is_websocket_route(path) {
512        return None;
513    }
514    hval(headers, "sec-websocket-protocol")?.split(',').map(str::trim).find(|p| !p.is_empty() && *p != WS_PROTOCOL)
515}
516
517/// Does this request come from a live browser session? `Host` and `Origin` exact, and the cookie
518/// and token (or the cookie alone where listed, with `Sec-Fetch-Site: same-origin`).
519pub(crate) fn admit_session(req: &Request<Body>) -> Option<SessionId> {
520    let shape = SHAPE.get()?;
521    let headers = req.headers();
522    check_shape(shape, headers, Kind::Any).ok()?;
523    let class = route_class(req.method(), req.uri().path());
524    if class == RouteClass::CookieOnly && hval(headers, "sec-fetch-site") != Some("same-origin") {
525        return None;
526    }
527    let cookie = cookie_value(headers, &shape.cookie_name)?;
528    let token = session_token(headers, req.uri().path());
529    store().admit(Some(cookie), token, class, Instant::now()).then(|| SessionId::of_cookie(cookie))
530}
531
532/// Completes when the browser session behind a WebSocket ends; never for a connection that came
533/// with the key.
534pub(crate) async fn session_ended(session: Option<SessionId>) {
535    match session {
536        Some(id) => store().ended(id).await,
537        None => std::future::pending().await,
538    }
539}
540
541// ---- The served UI ----
542
543/// The policy of the served UI and the sign-in page. `'unsafe-inline'` for styles only: the
544/// terminal and layout set inline styles.
545/// `'wasm-unsafe-eval'` lets the code highlighter's WebAssembly engine (Oniguruma, in shiki) compile and
546/// nothing else: scripts still come from this origin only, and `eval` of text stays refused. `base-uri
547/// 'self'` lets a library resolve a relative address against a base on this origin (the drag-preview
548/// picture does, for the fonts) and no other.
549fn content_security_policy(shape: &Shape) -> String {
550    let ws: Vec<String> = shape.origins.iter().map(|o| o.replacen("http://", "ws://", 1)).collect();
551    format!(
552        "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; \
553         font-src 'self' data:; connect-src 'self' {}; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; \
554         form-action 'self'; frame-ancestors 'none'",
555        ws.join(" ")
556    )
557}
558
559fn with_ui_headers(shape: &Shape, mut r: Response) -> Response {
560    let h = r.headers_mut();
561    if let Ok(v) = HeaderValue::from_str(&content_security_policy(shape)) {
562        h.insert(header::CONTENT_SECURITY_POLICY, v);
563    }
564    h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
565    h.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
566    h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
567    r
568}
569
570/// Is the UI's file asked for on an address this server serves? The files hold no secret, but a name that is not the
571/// server's own (a DNS-rebinding page, a stray alias) gets nothing from it: the same rule as the sign-in and API routes.
572fn ui_host_ok(shape: &Shape, headers: &HeaderMap) -> bool {
573    hval(headers, "host").is_some_and(|h| shape.host_ok(h))
574}
575
576/// Middleware for the served UI's files.
577pub(crate) async fn ui_headers(req: Request<Body>, next: Next) -> Response {
578    if let Some(shape) = SHAPE.get() {
579        if !ui_host_ok(shape, req.headers()) {
580            return refusal();
581        }
582    }
583    let response = next.run(req).await;
584    match SHAPE.get() {
585        Some(shape) => with_ui_headers(shape, response),
586        None => response,
587    }
588}
589
590const ENTER_HTML: &str = r#"<!doctype html>
591<html lang="en">
592<head>
593<meta charset="utf-8">
594<meta name="viewport" content="width=device-width, initial-scale=1">
595<meta name="referrer" content="no-referrer">
596<title>Open AgentMux</title>
597<link rel="stylesheet" href="/auth/enter.css">
598</head>
599<body>
600<main>
601<h1>AgentMux</h1>
602<p id="msg">Opening&hellip;</p>
603<p id="phrase" hidden></p>
604<p id="hint" hidden>Compare this with the terminal where you ran <code>agentmux open</code>. Answer <code>y</code> there only if the two match: that keeps another user of this computer from opening your AgentMux.</p>
605<form id="paste" hidden><label>Code from the terminal <input id="code" autocomplete="off" autocapitalize="off" spellcheck="false"></label> <button type="submit">Open</button></form>
606</main>
607<script src="/auth/enter.js"></script>
608</body>
609</html>
610"#;
611
612const ENTER_CSS: &str = "body{font-family:system-ui,sans-serif;background:#111;color:#eee;display:flex;justify-content:center;padding-top:15vh}\
613main{max-width:34rem;padding:0 1rem;text-align:center}\
614#phrase{font-family:ui-monospace,monospace;font-size:3rem;letter-spacing:.05em;margin:1.5rem 0}\
615#hint{color:#bbb}code{background:#222;padding:.1rem .3rem;border-radius:.2rem}\
616#paste{margin-top:1rem}#code{font-family:ui-monospace,monospace;background:#222;color:#eee;border:1px solid #444;border-radius:.2rem;padding:.3rem;width:20rem;max-width:100%}\n";
617
618/// The code is in the fragment. The history entry loses it before anything is sent; the page then
619/// waits for the person's answer in the terminal and keeps the token in `sessionStorage` only. A page
620/// opened with no code (a visitor with no session, or a browser that was disconnected) says how to
621/// open AgentMux and is no refusal: it is the same words for everyone and tells nothing about the server.
622const ENTER_JS: &str = r#"(() => {
623  const msg = document.getElementById("msg");
624  const phrase = document.getElementById("phrase");
625  const hint = document.getElementById("hint");
626  const paste = document.getElementById("paste");
627  const field = document.getElementById("code");
628  // Each attempt to open is a run; a new code in the fragment (a hash-only navigation in this tab) starts a new one and ends the last.
629  let run = 0;
630  const begin = async () => {
631    const mine = ++run;
632    const current = () => mine === run;
633    const fail = () => {
634      if (!current()) return;
635      msg.textContent = "not accepted";
636      phrase.hidden = true;
637      // The same words for everyone, whatever went wrong: how to try again.
638      hint.textContent = "Run agentmux open in the terminal again for a new link.";
639      hint.hidden = false;
640    };
641    msg.textContent = "Opening...";
642    phrase.hidden = true;
643    hint.hidden = true;
644    paste.hidden = true;
645    const code = location.hash.slice(1);
646    history.replaceState(null, "", location.pathname);
647    if (!code) {
648      // Nobody tried to open it: a visitor with no session, or a browser that has just been disconnected.
649      msg.textContent = "This browser is not open to AgentMux.";
650      hint.textContent = "To open AgentMux here, run agentmux open (or agentmux-srv open) in a terminal on the machine where AgentMux runs, as the user that started it, and paste the code it prints below if its link will not copy.";
651      hint.hidden = false;
652      paste.hidden = false;
653      return;
654    }
655    const post = (path, body) =>
656      fetch(path, {
657        method: "POST",
658        headers: { "content-type": "application/json" },
659        body: JSON.stringify(body),
660        cache: "no-store",
661        credentials: "same-origin",
662      });
663    let entered;
664    try {
665      const r = await post("/auth/enter", { code });
666      if (!current()) return;
667      if (!r.ok) return fail();
668      entered = await r.json();
669    } catch {
670      return fail();
671    }
672    if (!current()) return;
673    msg.textContent = "Waiting for you to confirm in the terminal.";
674    phrase.textContent = entered.phrase;
675    phrase.hidden = false;
676    hint.textContent = "Compare this with the terminal where you ran agentmux open. Answer y there only if the two match: that keeps another user of this computer from opening your AgentMux.";
677    hint.hidden = false;
678    for (;;) {
679      let w;
680      try {
681        w = await post("/auth/wait", { handle: entered.handle });
682      } catch {
683        return fail();
684      }
685      if (!current()) return;
686      if (w.status === 202) continue;
687      if (!w.ok) return fail();
688      const { token } = await w.json();
689      if (!current()) return;
690      sessionStorage.setItem("amx-session", token);
691      location.replace("/");
692      return;
693    }
694  };
695  paste.addEventListener("submit", (e) => {
696    e.preventDefault();
697    const typed = field.value.trim();
698    field.value = "";
699    if (typed) location.hash = typed;
700  });
701  window.addEventListener("hashchange", begin);
702  begin();
703})();
704"#;
705
706#[cfg(test)]
707#[path = "tests/local_session_route_tests.rs"]
708mod tests;