~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
1113 lines · 40.7 KB Raw History
//! The workspace, mounted with sign-in on: `GET /workspace`, its page (one
//! HTML file, `web/dist/workspace.html`, embedded as `WORKSPACE_HTML`),
//! where `GET /` sends a browser (`home`, without the web app), signed out
//! its landing page; its icon, `GET /favicon.svg` (`FAVICON_SVG`, served
//! with sign-in off too, by `crate::router`); `GET /workspace/atmo/{file}`,
//! the apps' logos its sign-in dialog runs past (`ATMO`); `GET
//! /workspace/hero/{file}`, the landing's picture of the workspace (`HERO`);
//! and its sign-ins, each a
//! POST from the page alone (`X-HUD: 1` and the server's own `Origin`),
//! its input JSON, answered as JSON (`{error: "InvalidRequest", message}`
//! when refused, the message for a person): `POST /workspace/signin`, an
//! account named by `handle` (or DID) sent on to its server, or with
//! `create`, "Create one", to the sign-up PDS's, `{url}` the page goes to,
//! coming back at `/oauth/callback` with a web session;
//! `POST /workspace/switch`, to another account (`did`) the browser is
//! signed in to; and `POST /workspace/signout`, the session's end, going
//! on as the account used last before it, if any. The page calls the
//! workspace's methods (`crate::xrpc`) as the web session the
//! `hud_session` cookie names. Its CSP lets it run its own inline script
//! and styles, reach only the server, and load images and audio from the
//! server and the origins the bundled views trust, and images from the
//! image CDN.
//!
//! A browser holds up to four web sessions besides the one in use, their
//! cookies in `hud_accounts` (`~` between, the one used last first), so it
//! switches between accounts without signing in again. Signing in keeps
//! the session it was in among them; one more than four ends the one used
//! least lately, and a session of the account signed in to ends. Only
//! sessions still live count; HUD keeps each cookie as its SHA-256 alone,
//! and never logs one.

use crate::oauth::see_other;
use crate::{FAVICON_SVG, WORKSPACE_HTML};
use axum::Router;
use axum::body::Bytes;
use axum::extract::State;
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use hud_core::Hud;
use hud_core::oauth::{Account, COOKIE, WEB_LIFE};
use serde_json::{Value as Json, json};
use std::sync::Arc;

/// The cookie holding a browser's other web sessions' cookies, `~`
/// between, the one used last first.
const OTHERS: &str = "hud_accounts";
/// How many web sessions a browser keeps besides the one in use.
const MOST: usize = 4;
/// The most of a sign-in's or a switch's input read.
const MAX_BODY: usize = 4 * 1024;

/// The workspace's routes, over the server's state.
pub fn routes() -> Router<Arc<Hud>> {
    Router::new()
        .route("/workspace", get(app))
        .route("/workspace/atmo/{file}", get(atmo))
        .route("/workspace/hero/{file}", get(hero))
        .route("/workspace/signin", post(sign_in))
        .route("/workspace/switch", post(switch))
        .route("/workspace/signout", post(sign_out))
}

/// The page's Content-Security-Policy: its own inline script and styles;
/// the server alone to talk to, and a `Map`'s tiles (`MAP_TILES`) alone to
/// fetch besides; images, audio and video from the server and
/// the origins the bundled views trust (Bluesky's video service and CDN
/// among them, for posts' videos' HLS), and images from Bluesky's CDN, for
/// the AppView's avatars, and the image CDN (`image_cdn`, an origin), for
/// public records' images.
pub(crate) fn csp(public_origin: &str, image_cdn: Option<&str>) -> String {
    let trusted: Vec<String> = hud_core::view::csp_origins(public_origin)
        .into_iter()
        .filter(|o| o != public_origin)
        .collect();
    let mut img = vec!["https://cdn.bsky.app".to_string()];
    for o in image_cdn
        .map(str::to_string)
        .into_iter()
        .chain(trusted.iter().cloned())
    {
        if !img.contains(&o) {
            img.push(o);
        }
    }
    let list = |extra: &[String]| {
        std::iter::once("'self'")
            .chain(extra.iter().map(String::as_str))
            .collect::<Vec<_>>()
            .join(" ")
    };
    format!(
        "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src {}; media-src {}; connect-src 'self' {}; frame-ancestors 'none'; base-uri 'none'; form-action 'self' https:",
        list(&img),
        list(&trusted),
        hud_core::catalog::MAP_TILES
    )
}

/// The `Set-Cookie` giving the browser the cookie `name` holding `value`,
/// as long as a web session lasts; an empty one takes it away.
fn set_cookie(name: &str, value: &str) -> HeaderValue {
    let age = if value.is_empty() { 0 } else { WEB_LIFE };
    HeaderValue::from_str(&format!(
        "{name}={value}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age={age}"
    ))
    .expect("a cookie HUD made is a header's text")
}

/// The value of the cookie `name` a request carries, if any.
fn cookie_named<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers
        .get_all(header::COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .flat_map(|v| v.split(';'))
        .find_map(|c| c.trim().strip_prefix(name)?.strip_prefix('='))
        .filter(|c| !c.is_empty())
}

/// The web session's cookie a request carries, if any.
pub(crate) fn cookie(headers: &HeaderMap) -> Option<&str> {
    cookie_named(headers, COOKIE)
}

/// A web session a browser holds: its account, and its cookie.
struct Held {
    account: Account,
    cookie: String,
}

/// The live web sessions a request's cookies hold: the one in use, if
/// any, and the others, the one used last first, each account once and
/// never the one in use's.
fn held(hud: &Hud, headers: &HeaderMap) -> (Option<Held>, Vec<Held>) {
    let auth = hud
        .auth()
        .expect("the workspace's routes are mounted with sign-in on");
    let live = |c: &str| {
        auth.web_account(c).map(|account| Held {
            account,
            cookie: c.to_string(),
        })
    };
    let current = cookie(headers).and_then(live);
    let mut others: Vec<Held> = Vec::new();
    for h in cookie_named(headers, OTHERS)
        .unwrap_or_default()
        .split('~')
        .filter_map(live)
    {
        let seen = current
            .iter()
            .chain(&others)
            .any(|o| o.account.did == h.account.did);
        if !seen {
            others.push(h);
        }
    }
    (current, others)
}

/// The other accounts a request's browser is signed in to, the one used
/// last first, as `getWorkspace`'s `accounts` lists them.
pub(crate) fn accounts(hud: &Hud, headers: &HeaderMap) -> Vec<Json> {
    held(hud, headers)
        .1
        .into_iter()
        .map(|h| match h.account.handle {
            Some(handle) => json!({ "did": h.account.did, "handle": handle }),
            None => json!({ "did": h.account.did }),
        })
        .collect()
}

/// Leave a browser in the session `current` (none: signed out), its others
/// `others`, as many as it keeps: past those, each ends. `OTHERS` is set
/// where there are any, or the request held it.
async fn settle(
    hud: &Hud,
    headers: &HeaderMap,
    current: Option<&str>,
    mut others: Vec<Held>,
    r: &mut Response,
) {
    for gone in others.split_off(MOST.min(others.len())) {
        hud.sign_out(&gone.cookie).await;
    }
    let set = r.headers_mut();
    set.append(
        header::SET_COOKIE,
        set_cookie(COOKIE, current.unwrap_or_default()),
    );
    if !others.is_empty() || cookie_named(headers, OTHERS).is_some() {
        let kept: Vec<&str> = others.iter().map(|h| h.cookie.as_str()).collect();
        set.append(header::SET_COOKIE, set_cookie(OTHERS, &kept.join("~")));
    }
}

/// Back from the account's server with a web session (`cookie`, its
/// account's): it becomes the one in use, and the one the browser was in
/// joins the front of its others. Another session of the same account, in
/// use or kept, ends.
pub(crate) async fn signed_in(hud: &Hud, headers: &HeaderMap, cookie: &str, r: &mut Response) {
    let did = hud
        .auth()
        .ok()
        .and_then(|a| a.web_account(cookie))
        .map(|a| a.did);
    let (current, others) = held(hud, headers);
    let mut kept = Vec::new();
    for h in current.into_iter().chain(others) {
        if Some(&h.account.did) == did.as_ref() {
            hud.sign_out(&h.cookie).await;
        } else {
            kept.push(h);
        }
    }
    settle(hud, headers, Some(cookie), kept, r).await;
}

/// A refusal, as JSON, never kept by a cache.
fn error(status: StatusCode, why: &str) -> Response {
    (
        status,
        [
            (header::CONTENT_TYPE, "application/json"),
            (header::CACHE_CONTROL, "no-store"),
        ],
        json!({ "error": "InvalidRequest", "message": why }).to_string(),
    )
        .into_response()
}

/// An answer, as JSON, never kept by a cache.
fn answer(body: &Json) -> Response {
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "application/json"),
            (header::CACHE_CONTROL, "no-store"),
        ],
        body.to_string(),
    )
        .into_response()
}

/// Whether a request comes from a page of the server's own origin.
pub(crate) fn same_origin(hud: &Hud, headers: &HeaderMap) -> bool {
    headers
        .get(header::ORIGIN)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|o| o.eq_ignore_ascii_case(&hud.config.public_origin))
}

/// The refusal of a sign-in's POST that is not the page's own: from
/// another origin, or without `X-HUD: 1`.
fn not_the_page(hud: &Hud, headers: &HeaderMap) -> Option<Response> {
    let said = headers.get("x-hud").and_then(|v| v.to_str().ok()) == Some("1");
    (!said || !same_origin(hud, headers)).then(|| {
        error(
            StatusCode::FORBIDDEN,
            "Only the workspace's own page may do this, with X-HUD: 1",
        )
    })
}

/// A string field of a JSON object of at most `MAX_BODY`; else the
/// refusal's status and why.
fn field(body: &[u8], k: &str) -> Result<String, (StatusCode, &'static str)> {
    if body.len() > MAX_BODY {
        return Err((StatusCode::PAYLOAD_TOO_LARGE, "The input is too large"));
    }
    match serde_json::from_slice::<Json>(body) {
        Ok(Json::Object(o)) => Ok(o
            .get(k)
            .and_then(Json::as_str)
            .unwrap_or_default()
            .to_string()),
        _ => Err((StatusCode::BAD_REQUEST, "The input must be a JSON object")),
    }
}

/// `GET /workspace`: the page, signed in or not; it asks `me` which.
async fn app(State(hud): State<Arc<Hud>>) -> Response {
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "text/html; charset=utf-8".to_string()),
            (
                header::CONTENT_SECURITY_POLICY,
                csp(
                    &hud.config.public_origin,
                    hud.config.image_cdn_origin().as_deref(),
                ),
            ),
            (header::CACHE_CONTROL, "no-cache".to_string()),
            (header::REFERRER_POLICY, "no-referrer".to_string()),
            (header::X_FRAME_OPTIONS, "DENY".to_string()),
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
        ],
        WORKSPACE_HTML,
    )
        .into_response()
}

/// `GET /`, without the web app: the workspace where it is served, with
/// sign-in on; nothing otherwise.
pub(crate) async fn home(State(hud): State<Arc<Hud>>) -> Response {
    match hud.oauth.is_some() && hud.config.workspace {
        true => see_other("/workspace"),
        false => StatusCode::NOT_FOUND.into_response(),
    }
}

/// `GET /favicon.svg`: HUD's icon, the page's favicon, kept a day.
pub(crate) async fn favicon() -> Response {
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, "image/svg+xml"),
            (header::CACHE_CONTROL, "public, max-age=86400"),
            (header::CONTENT_SECURITY_POLICY, "default-src 'none'"),
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
        ],
        FAVICON_SVG,
    )
        .into_response()
}

/// Apps on the Atmosphere, any of whose accounts signs in here, by the name
/// their logo goes by in the sign-in dialog's running row, as knotless's:
/// each a 96-pixel square, embedded.
const ATMO: &[(&str, &str, &[u8])] = &[
    (
        "anisota.jpg",
        "image/jpeg",
        include_bytes!("../atmo/anisota.jpg"),
    ),
    (
        "beacon-bits.jpg",
        "image/jpeg",
        include_bytes!("../atmo/beacon-bits.jpg"),
    ),
    (
        "blacksky.jpg",
        "image/jpeg",
        include_bytes!("../atmo/blacksky.jpg"),
    ),
    (
        "blento.jpg",
        "image/jpeg",
        include_bytes!("../atmo/blento.jpg"),
    ),
    (
        "bluesky.jpg",
        "image/jpeg",
        include_bytes!("../atmo/bluesky.jpg"),
    ),
    (
        "eurosky.jpg",
        "image/jpeg",
        include_bytes!("../atmo/eurosky.jpg"),
    ),
    (
        "flashes.jpg",
        "image/jpeg",
        include_bytes!("../atmo/flashes.jpg"),
    ),
    (
        "gander.jpg",
        "image/jpeg",
        include_bytes!("../atmo/gander.jpg"),
    ),
    ("germ.jpg", "image/jpeg", include_bytes!("../atmo/germ.jpg")),
    (
        "leaflet.jpg",
        "image/jpeg",
        include_bytes!("../atmo/leaflet.jpg"),
    ),
    (
        "northsky.jpg",
        "image/jpeg",
        include_bytes!("../atmo/northsky.jpg"),
    ),
    (
        "offprint.jpg",
        "image/jpeg",
        include_bytes!("../atmo/offprint.jpg"),
    ),
    ("pckt.jpg", "image/jpeg", include_bytes!("../atmo/pckt.jpg")),
    ("plyr.jpg", "image/jpeg", include_bytes!("../atmo/plyr.jpg")),
    (
        "popfeed.jpg",
        "image/jpeg",
        include_bytes!("../atmo/popfeed.jpg"),
    ),
    (
        "semble.jpg",
        "image/jpeg",
        include_bytes!("../atmo/semble.jpg"),
    ),
    (
        "skylight.jpg",
        "image/jpeg",
        include_bytes!("../atmo/skylight.jpg"),
    ),
    (
        "spark.png",
        "image/png",
        include_bytes!("../atmo/spark.png"),
    ),
    (
        "stream-place.jpg",
        "image/jpeg",
        include_bytes!("../atmo/stream-place.jpg"),
    ),
    (
        "tangled.jpg",
        "image/jpeg",
        include_bytes!("../atmo/tangled.jpg"),
    ),
];

/// `GET /workspace/atmo/{file}`: an app's logo for the sign-in dialog, kept
/// a day; any other name is not found.
async fn atmo(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
    embedded(ATMO, &file)
}

/// The landing's picture of the workspace, made by `just hero`
/// (`harness/look/hero.mjs`: the `hero` state, its maintainer's own
/// canvas): every theme in turn, an animated WebP; and still, light and
/// dark, 2048 pixels wide, for those who ask for less motion.
const HERO: &[(&str, &str, &[u8])] = &[
    (
        "workspace-light.webp",
        "image/webp",
        include_bytes!("../hero/workspace-light.webp"),
    ),
    (
        "workspace-dark.webp",
        "image/webp",
        include_bytes!("../hero/workspace-dark.webp"),
    ),
    (
        "workspace-themes.webp",
        "image/webp",
        include_bytes!("../hero/workspace-themes.webp"),
    ),
];

/// `GET /workspace/hero/{file}`: the landing's picture, kept a day; any
/// other name is not found.
async fn hero(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
    embedded(HERO, &file)
}

/// One of `files`, by its name, kept a day; not found by any other.
fn embedded(files: &'static [(&'static str, &'static str, &'static [u8])], file: &str) -> Response {
    let Some((_, kind, bytes)) = files.iter().find(|(name, _, _)| *name == file) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    (
        StatusCode::OK,
        [
            (header::CONTENT_TYPE, *kind),
            (header::CACHE_CONTROL, "public, max-age=86400"),
            (header::CONTENT_SECURITY_POLICY, "default-src 'none'"),
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
        ],
        *bytes,
    )
        .into_response()
}

/// `POST /workspace/signin`, `{handle}`: the account it names (a handle or
/// DID) sent on to its server, `{url}`, its authorization page, for the
/// page to go to; else why not. `{"create": true}`, "Create one": on to
/// the sign-up PDS's server (`HUD_SIGN_UP_PDS`), its sign-up page; a
/// failure there is the sign-up PDS's, answered 502.
async fn sign_in(State(hud): State<Arc<Hud>>, headers: HeaderMap, body: Bytes) -> Response {
    if let Some(r) = not_the_page(&hud, &headers) {
        return r;
    }
    let handle = match field(&body, "handle") {
        Ok(h) => h,
        Err((status, why)) => return error(status, why),
    };
    let create = serde_json::from_slice::<Json>(&body).is_ok_and(|v| v["create"] == true);
    if create {
        return match hud.web_sign_up().await {
            Ok(url) => answer(&json!({ "url": url })),
            Err(why) => error(StatusCode::BAD_GATEWAY, &why),
        };
    }
    match hud.web_sign_in(&handle).await {
        Ok(url) => answer(&json!({ "url": url })),
        Err(why) => error(StatusCode::BAD_REQUEST, &why),
    }
}

/// `POST /workspace/switch`, `{did}`: the browser's session of that
/// account, one it holds besides the one in use, becomes the one in use,
/// and that one joins the front of its others.
async fn switch(State(hud): State<Arc<Hud>>, headers: HeaderMap, body: Bytes) -> Response {
    if let Some(r) = not_the_page(&hud, &headers) {
        return r;
    }
    let did = match field(&body, "did") {
        Ok(d) => d,
        Err((status, why)) => return error(status, why),
    };
    let (current, mut others) = held(&hud, &headers);
    let Some(at) = others.iter().position(|h| h.account.did == did) else {
        return error(
            StatusCode::BAD_REQUEST,
            "This browser is not signed in to that account; sign in to it",
        );
    };
    let to = others.remove(at);
    if let Some(c) = current {
        others.insert(0, c);
    }
    let mut r = answer(&json!({}));
    settle(&hud, &headers, Some(&to.cookie), others, &mut r).await;
    r
}

/// `POST /workspace/signout`: the web session in use ends, its atproto
/// refresh token revoked; the browser goes on as the account it used last
/// before it, if it holds one, else signed out. The page reloads itself.
async fn sign_out(State(hud): State<Arc<Hud>>, headers: HeaderMap) -> Response {
    if let Some(r) = not_the_page(&hud, &headers) {
        return r;
    }
    if let Some(c) = cookie(&headers) {
        hud.sign_out(c).await;
    }
    let mut r = answer(&json!({}));
    moved_on(&hud, &headers, &mut r).await;
    r
}

/// Once the web session in use ended, the browser goes on as the account
/// it used last before it, if it holds one, else signed out: `r` says so.
pub(crate) async fn moved_on(hud: &Hud, headers: &HeaderMap, r: &mut Response) {
    // Read once it has ended: it is in use no more.
    let (_, mut others) = held(hud, headers);
    let next = (!others.is_empty()).then(|| others.remove(0));
    let next = next.map(|h| h.cookie);
    settle(hud, headers, next.as_deref(), others, r).await;
}

#[cfg(test)]
mod tests {
    use super::*;
    use hud_core::Config;
    use tower::ServiceExt;

    const ORIGIN: &str = "https://hud.example";
    const ALICE: &str = "did:plc:alice";
    const BOB: &str = "did:plc:bob";
    const CAROL: &str = "did:plc:carol";
    const DAN: &str = "did:plc:dan";
    const ERIN: &str = "did:plc:erin";
    const FRANK: &str = "did:plc:frank";

    fn hud() -> Arc<Hud> {
        let data_dir =
            std::env::temp_dir().join(format!("hud-workspace-tests-{}", atproto::jose::random(6)));
        Hud::new(Config {
            port: 8787,
            bind: "::".parse().unwrap(),
            public_origin: ORIGIN.into(),
            cache_dir: data_dir.join("cache"),
            data_dir,
            oauth: true,
            oauth_scope: hud_core::scope::asked(hud_core::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            spaces: false,
            plc_url: "https://plc.directory".into(),
            handle_resolver: None,
            allow_private: false,
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            backlinks: hud_core::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: Some("https://images.example/img".into()),
            relay: None,
            // Unreachable, offline: a loopback address, refused.
            sign_up_pds: "http://127.0.0.1:9".into(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: hud_core::logs::KEEP,
        })
        .unwrap()
    }

    /// A web session's cookie of `did`.
    fn web(hud: &Hud, did: &str) -> String {
        let handle = format!("{}.test", did.rsplit(':').next().unwrap());
        hud.auth()
            .unwrap()
            .signed_in_offline(did, Some(&handle), true)
    }

    /// Whether a web session's cookie is live.
    fn live(hud: &Hud, cookie: &str) -> bool {
        hud.auth().unwrap().web_account(cookie).is_some()
    }

    fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
        let mut h = HeaderMap::new();
        for (k, v) in pairs {
            h.append(
                header::HeaderName::from_bytes(k.as_bytes()).unwrap(),
                HeaderValue::from_str(v).unwrap(),
            );
        }
        h
    }

    /// A page's POST headers, with its cookie and the others it holds.
    fn page(cookie: &str, others: &[&str]) -> HeaderMap {
        let mut jar = format!("theme=dark; {COOKIE}={cookie}");
        if !others.is_empty() {
            jar.push_str(&format!("; {OTHERS}={}", others.join("~")));
        }
        headers(&[("cookie", &jar), ("x-hud", "1"), ("origin", ORIGIN)])
    }

    /// The cookies an answer sets, by name: their values, and the whole
    /// header.
    fn set(h: &HeaderMap) -> Vec<(String, String, String)> {
        h.get_all(header::SET_COOKIE)
            .iter()
            .map(|v| {
                let v = v.to_str().unwrap().to_string();
                let (name, rest) = v.split_once('=').unwrap();
                let value = rest.split(';').next().unwrap();
                (name.to_string(), value.to_string(), v.clone())
            })
            .collect()
    }

    /// The value an answer sets the cookie `name` to, if it sets it.
    fn set_to(h: &HeaderMap, name: &str) -> Option<String> {
        set(h)
            .into_iter()
            .find(|(n, _, _)| n == name)
            .map(|(_, v, _)| v)
    }

    async fn read(r: Response) -> (StatusCode, HeaderMap, Json) {
        let status = r.status();
        let headers = r.headers().clone();
        let bytes = axum::body::to_bytes(r.into_body(), usize::MAX)
            .await
            .unwrap();
        let body = serde_json::from_slice(&bytes)
            .unwrap_or_else(|_| Json::String(String::from_utf8_lossy(&bytes).into()));
        (status, headers, body)
    }

    /// A refusal as the page reads one: its status and message.
    fn refused(got: (StatusCode, HeaderMap, Json)) -> (StatusCode, String) {
        assert_eq!(got.2["error"], "InvalidRequest", "{}", got.2);
        (got.0, got.2["message"].as_str().unwrap().to_string())
    }

    #[tokio::test]
    async fn pages_and_cookies() {
        let hud = hud();
        let (status, h, body) = read(app(State(hud.clone())).await).await;
        assert_eq!(status, StatusCode::OK);
        let cdn = Some("https://images.example");
        assert_eq!(
            h[header::CONTENT_SECURITY_POLICY],
            csp(ORIGIN, cdn).as_str()
        );
        assert!(body.as_str().unwrap().contains("<html"));
        let img_src = |policy: &str| {
            policy
                .split("; ")
                .find(|d| d.starts_with("img-src"))
                .unwrap()
                .to_string()
        };
        let policy = csp(ORIGIN, cdn);
        assert!(policy.starts_with("default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' https://cdn.bsky.app https://images.example "), "{policy}");
        assert!(policy.ends_with("; connect-src 'self' https://tiles.grain.social; frame-ancestors 'none'; base-uri 'none'; form-action 'self' https:"), "{policy}");
        assert_eq!(
            img_src(&policy).matches("https://cdn.bsky.app").count(),
            1,
            "{policy}"
        );
        assert!(!policy.contains(ORIGIN), "the server is 'self'");
        // The image CDN for images only, never media; none without one, and
        // Bluesky's, the default, named once.
        let media = policy
            .split("; ")
            .find(|d| d.starts_with("media-src"))
            .unwrap();
        assert!(!media.contains("images.example"), "{policy}");
        // Bluesky's video service and CDN, for video, once each.
        for v in hud_core::blobs::VIDEO_ORIGINS {
            assert_eq!(media.matches(v).count(), 1, "{policy}");
        }
        assert!(!csp(ORIGIN, None).contains("images.example"));
        let bluesky = csp(ORIGIN, Some("https://cdn.bsky.app"));
        assert_eq!(
            img_src(&bluesky).matches("https://cdn.bsky.app").count(),
            1,
            "{bluesky}"
        );
        // The cookies given: the browser's alone, 30 days; empty, gone.
        assert_eq!(
            set_cookie(COOKIE, "c1"),
            "hud_session=c1; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=2592000"
        );
        assert_eq!(
            set_cookie(OTHERS, "c2~c3"),
            "hud_accounts=c2~c3; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=2592000"
        );
        assert_eq!(
            set_cookie(COOKIE, ""),
            "hud_session=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0"
        );
        // Signing out ends the session and takes the cookie away; only from
        // the server's own page.
        let cookie = web(&hud, ALICE);
        let token = hud
            .auth()
            .unwrap()
            .signed_in_offline(ALICE, Some("alice.test"), false);
        let elsewhere = headers(&[
            ("cookie", &format!("{COOKIE}={cookie}")),
            ("x-hud", "1"),
            ("origin", "https://evil.example"),
        ]);
        let (status, _) = refused(read(sign_out(State(hud.clone()), elsewhere).await).await);
        assert_eq!(status, StatusCode::FORBIDDEN);
        let unsaid = headers(&[
            ("cookie", &format!("{COOKIE}={cookie}")),
            ("origin", ORIGIN),
        ]);
        let (status, _) = refused(read(sign_out(State(hud.clone()), unsaid).await).await);
        assert_eq!(status, StatusCode::FORBIDDEN);
        assert!(live(&hud, &cookie));
        let (status, h, body) = read(sign_out(State(hud.clone()), page(&cookie, &[])).await).await;
        assert_eq!((status, body), (StatusCode::OK, json!({})));
        assert_eq!(
            h[header::SET_COOKIE],
            "hud_session=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0"
        );
        assert_eq!(set(&h).len(), 1, "no others to set");
        assert!(!live(&hud, &cookie));
        assert!(
            hud.auth().unwrap().account(&token).is_some(),
            "the MCP session goes on"
        );
    }

    #[tokio::test]
    async fn signing_in_by_json() {
        let hud = hud();
        let send = |h: HeaderMap, body: &str| {
            let hud = hud.clone();
            let body = Bytes::from(body.to_string());
            async move { read(sign_in(State(hud), h, body).await).await }
        };
        let page = headers(&[("x-hud", "1"), ("origin", ORIGIN)]);
        let elsewhere = headers(&[("x-hud", "1"), ("origin", "https://evil.example")]);
        let unsaid = headers(&[("origin", ORIGIN)]);
        let handle = r#"{"handle":"alice.test"}"#;
        for h in [elsewhere.clone(), unsaid] {
            let (status, why) = refused(send(h, handle).await);
            assert_eq!(status, StatusCode::FORBIDDEN);
            assert_eq!(
                why,
                "Only the workspace's own page may do this, with X-HUD: 1"
            );
        }
        for (body, why) in [
            ("handle=alice.test", "The input must be a JSON object"),
            (r#"{}"#, "Enter your handle, as alice.bsky.social"),
            (
                r#"{"handle":"  "}"#,
                "Enter your handle, as alice.bsky.social",
            ),
            (
                r#"{"handle":"not a handle"}"#,
                "not a handle is not a handle or a DID",
            ),
        ] {
            assert_eq!(
                refused(send(page.clone(), body).await),
                (StatusCode::BAD_REQUEST, why.to_string())
            );
        }
        let big = format!(r#"{{"handle":"{}"}}"#, "a".repeat(MAX_BODY));
        assert_eq!(
            send(page.clone(), &big).await.0,
            StatusCode::PAYLOAD_TOO_LARGE
        );
        // "Create one", no handle: on to the sign-up PDS, whose failure is
        // answered 502, in words; from the page alone.
        let create = r#"{"create":true}"#;
        assert_eq!(
            refused(send(elsewhere, create).await).0,
            StatusCode::FORBIDDEN
        );
        assert_eq!(
            refused(send(page, create).await),
            (
                StatusCode::BAD_GATEWAY,
                "Accounts can't be made at 127.0.0.1 now; try again later".to_string()
            )
        );
        // Its HTML page is gone: the page signs in in a dialog of its own.
        let r = crate::router(hud.clone(), None)
            .oneshot(
                axum::http::Request::get("/workspace/signin")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED);
    }

    #[tokio::test]
    async fn the_root_and_the_dialogs_logos() {
        let hud = hud();
        let get = |path: String| {
            let hud = hud.clone();
            async move {
                crate::router(hud, None)
                    .oneshot(
                        axum::http::Request::get(path)
                            .body(axum::body::Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap()
            }
        };
        let root = get("/".into()).await;
        assert_eq!(root.status(), StatusCode::SEE_OTHER);
        assert_eq!(root.headers()[header::LOCATION], "/workspace");
        // Every logo the dialog names, by its kind; nothing else.
        for (name, kind, _) in ATMO {
            let r = get(format!("/workspace/atmo/{name}")).await;
            assert_eq!(r.status(), StatusCode::OK, "{name}");
            assert_eq!(r.headers()[header::CONTENT_TYPE], *kind);
        }
        assert_eq!(
            get("/workspace/atmo/..%2Fworkspace.rs".into())
                .await
                .status(),
            StatusCode::NOT_FOUND
        );
    }

    #[tokio::test]
    async fn the_landings_picture() {
        let hud = hud();
        let get = |path: String| {
            let hud = hud.clone();
            async move {
                crate::router(hud, None)
                    .oneshot(
                        axum::http::Request::get(path)
                            .body(axum::body::Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap()
            }
        };
        // Every theme in turn, and still light and dark, each a WebP the
        // page names, kept a day; nothing else.
        for name in [
            "workspace-themes.webp",
            "workspace-light.webp",
            "workspace-dark.webp",
        ] {
            let r = get(format!("/workspace/hero/{name}")).await;
            assert_eq!(r.status(), StatusCode::OK, "{name}");
            assert_eq!(r.headers()[header::CONTENT_TYPE], "image/webp");
            assert_eq!(r.headers()[header::CACHE_CONTROL], "public, max-age=86400");
            let body = axum::body::to_bytes(r.into_body(), usize::MAX)
                .await
                .unwrap();
            assert!(
                body.starts_with(b"RIFF") && &body[8..12] == b"WEBP",
                "{name}"
            );
        }
        assert_eq!(
            get("/workspace/hero/workspace.webp".into()).await.status(),
            StatusCode::NOT_FOUND
        );
    }

    #[tokio::test]
    async fn switching_accounts() {
        let hud = hud();
        let (alice, bob, carol) = (web(&hud, ALICE), web(&hud, BOB), web(&hud, CAROL));
        let gone = web(&hud, DAN);
        hud.sign_out(&gone).await;
        let switch_to = |h: HeaderMap, did: &str| {
            let hud = hud.clone();
            let body = Bytes::from(json!({ "did": did }).to_string());
            async move { read(switch(State(hud), h, body).await).await }
        };
        // getWorkspace's accounts: the others, live, the one used last
        // first, by handle where it is known.
        let nameless = hud.auth().unwrap().signed_in_offline(FRANK, None, true);
        let jar = page(&alice, &[&gone, &bob, &carol, &alice]);
        let listed: Vec<Json> = accounts(&hud, &jar);
        assert_eq!(
            listed,
            [
                json!({ "did": BOB, "handle": "bob.test" }),
                json!({ "did": CAROL, "handle": "carol.test" }),
            ]
        );
        assert_eq!(
            accounts(&hud, &page(&alice, &[&nameless])),
            [json!({ "did": FRANK })]
        );
        // To carol: hers in use, alice's first of the others.
        let (status, h, body) = switch_to(jar.clone(), CAROL).await;
        assert_eq!((status, body), (StatusCode::OK, json!({})));
        assert_eq!(set_to(&h, COOKIE), Some(carol.clone()));
        assert_eq!(set_to(&h, OTHERS), Some(format!("{alice}~{bob}")));
        let all = set(&h);
        assert!(
            all.iter()
                .all(|(_, _, v)| v
                    .contains("HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=2592000")),
            "{all:?}"
        );
        // None the browser holds: refused, its cookies as they were.
        for did in [ALICE, DAN, ERIN, "not a did"] {
            let got = switch_to(jar.clone(), did).await;
            assert!(set(&got.1).is_empty());
            assert_eq!(
                refused(got),
                (
                    StatusCode::BAD_REQUEST,
                    "This browser is not signed in to that account; sign in to it".into()
                )
            );
        }
        // Only from the page.
        let mut elsewhere = jar.clone();
        elsewhere.insert(
            header::ORIGIN,
            HeaderValue::from_static("https://evil.example"),
        );
        // Not JSON: refused.
        let not_json =
            read(switch(State(hud.clone()), jar.clone(), Bytes::from("did")).await).await;
        assert_eq!(
            refused(not_json),
            (
                StatusCode::BAD_REQUEST,
                "The input must be a JSON object".into()
            )
        );
        assert_eq!(switch_to(elsewhere, BOB).await.0, StatusCode::FORBIDDEN);
        // With the one in use ended, the other becomes it, alone.
        hud.sign_out(&alice).await;
        let (status, h, _) = switch_to(page(&alice, &[&bob]), BOB).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(set_to(&h, COOKIE), Some(bob.clone()));
        assert_eq!(set_to(&h, OTHERS), Some(String::new()));
        assert!(live(&hud, &bob) && live(&hud, &carol));
    }

    #[tokio::test]
    async fn signing_out_goes_on_as_the_account_used_last() {
        let hud = hud();
        let (alice, bob, carol) = (web(&hud, ALICE), web(&hud, BOB), web(&hud, CAROL));
        let out = |h: HeaderMap| {
            let hud = hud.clone();
            async move { read(sign_out(State(hud), h).await).await }
        };
        let (status, h, body) = out(page(&alice, &[&bob, &carol])).await;
        assert_eq!((status, body), (StatusCode::OK, json!({})));
        assert!(!live(&hud, &alice));
        assert_eq!(set_to(&h, COOKIE), Some(bob.clone()));
        assert_eq!(set_to(&h, OTHERS), Some(carol.clone()));
        let (_, h, _) = out(page(&bob, &[&carol])).await;
        assert!(!live(&hud, &bob));
        assert_eq!(set_to(&h, COOKIE), Some(carol.clone()));
        let (_, _, others) = set(&h).into_iter().find(|(n, _, _)| n == OTHERS).unwrap();
        assert!(others.ends_with("Max-Age=0"), "{others}");
        let (_, h, _) = out(page(&carol, &[])).await;
        assert!(!live(&hud, &carol));
        assert_eq!(set_to(&h, COOKIE), Some(String::new()));
        assert_eq!(set_to(&h, OTHERS), None);
    }

    #[tokio::test]
    async fn signing_in_keeps_the_session_it_was_in() {
        let hud = hud();
        let [alice, bob, carol, dan, erin, frank] =
            [ALICE, BOB, CAROL, DAN, ERIN, FRANK].map(|d| web(&hud, d));
        let back = async |h: HeaderMap, cookie: &str| {
            let mut r = StatusCode::SEE_OTHER.into_response();
            signed_in(&hud, &h, cookie, &mut r).await;
            r.headers().clone()
        };
        // Signed in afresh: nothing more.
        let h = back(HeaderMap::new(), &alice).await;
        assert_eq!(set_to(&h, COOKIE), Some(alice.clone()));
        assert_eq!(set_to(&h, OTHERS), None);
        // As alice, with four others: frank's in use, alice's first of the
        // others, erin's, the one used least lately, ended.
        let h = back(page(&alice, &[&bob, &carol, &dan, &erin]), &frank).await;
        assert_eq!(set_to(&h, COOKIE), Some(frank.clone()));
        assert_eq!(
            set_to(&h, OTHERS),
            Some(format!("{alice}~{bob}~{carol}~{dan}"))
        );
        assert!(!live(&hud, &erin));
        assert!(
            [&alice, &bob, &carol, &dan, &frank]
                .iter()
                .all(|c| live(&hud, c))
        );
        // As bob, signing in to alice again: her session kept ends, the new
        // one in use, bob's first of the others.
        let alice_again = web(&hud, ALICE);
        let h = back(page(&bob, &[&alice, &carol]), &alice_again).await;
        assert_eq!(set_to(&h, COOKIE), Some(alice_again.clone()));
        assert_eq!(set_to(&h, OTHERS), Some(format!("{bob}~{carol}")));
        assert!(!live(&hud, &alice));
        // Signing in to the account in use: that session ends, the others
        // stay.
        let bob_again = web(&hud, BOB);
        let h = back(page(&bob, &[&carol]), &bob_again).await;
        assert_eq!(set_to(&h, COOKIE), Some(bob_again.clone()));
        assert_eq!(set_to(&h, OTHERS), Some(carol.clone()));
        assert!(!live(&hud, &bob));
    }

    #[tokio::test]
    async fn the_icon() {
        let r = favicon().await;
        let (status, h) = (r.status(), r.headers().clone());
        let body = axum::body::to_bytes(r.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(status, StatusCode::OK);
        assert_eq!(h[header::CONTENT_TYPE], "image/svg+xml");
        assert_eq!(h[header::CACHE_CONTROL], "public, max-age=86400");
        assert_eq!(h[header::CONTENT_SECURITY_POLICY], "default-src 'none'");
        assert_eq!(body, FAVICON_SVG.as_bytes());
    }

    #[tokio::test]
    async fn sign_in_and_out_refused_or_with_nothing_to_end() {
        let hud = hud();
        // Signing out with no session: answered all the same, the cookie
        // taken away.
        let (status, h, body) = read(
            sign_out(
                State(hud.clone()),
                headers(&[("x-hud", "1"), ("origin", ORIGIN)]),
            )
            .await,
        )
        .await;
        assert_eq!((status, body), (StatusCode::OK, json!({})));
        assert_eq!(
            h[header::SET_COOKIE],
            "hud_session=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0"
        );
        // With as many sign-ins waiting as are kept, the page says so.
        let client = json!({ "redirect_uris": ["http://127.0.0.1/cb"], "client_name": "Test host",
            "token_endpoint_auth_method": "none" });
        let client = hud.register(client.to_string().as_bytes()).unwrap();
        let challenge = atproto::jose::sha256("verifier");
        let asked: Vec<(String, String)> = [
            ("client_id", client["client_id"].as_str().unwrap()),
            ("redirect_uri", "http://127.0.0.1/cb"),
            ("response_type", "code"),
            ("code_challenge", &challenge),
            ("code_challenge_method", "S256"),
            ("resource", "https://hud.example/mcp"),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();
        while hud.authorize(&asked).await.is_ok() {}
        let page = headers(&[("x-hud", "1"), ("origin", ORIGIN)]);
        let body = Bytes::from_static(br#"{"handle":"alice.test"}"#);
        assert_eq!(
            refused(read(sign_in(State(hud.clone()), page, body).await).await),
            (
                StatusCode::BAD_REQUEST,
                "Too many sign-ins are waiting; try again in a few minutes".to_string()
            )
        );
    }
}