~ 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
142 lines · 5.2 KB Raw History
//! The web app's pages, with `HUD_WEB`: every request HUD doesn't answer
//! itself, `/` and the icons among them, handed to the operator's own web
//! app (`hud_core::net::Web`), as a SvelteKit app that draws pages on the
//! server. Its answer goes back as it comes, each part as the app sends
//! it, so a page it streams reaches the browser as it's drawn; and it's
//! compressed as HUD's own answers are (`crate::compressed`), but for what
//! the app compressed itself. A path under HUD's own (`OWN`) is HUD's even
//! where no route of its takes it, so a mistyped method or sign-in path is
//! never drawn as a page. Logged and counted as the route `web`.

use crate::telemetry::{Cause, name};
use axum::Router;
use axum::body::{Body, HttpBody};
use axum::extract::{ConnectInfo, Request};
use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use hud_core::Hud;
use hud_core::net::Web;
use std::net::SocketAddr;
use std::sync::Arc;

/// The paths under which every request is HUD's, a route of its there or
/// not.
const OWN: [&str; 6] = [
    "/oauth/",
    "/.well-known/",
    "/xrpc/",
    "/blob/",
    "/icon/",
    "/workspace/",
];

/// Headers about one hop of a connection, which aren't handed on either
/// way. The length goes too, as a body is handed on as it comes.
const HOP: [HeaderName; 9] = [
    header::CONNECTION,
    HeaderName::from_static("keep-alive"),
    HeaderName::from_static("proxy-connection"),
    header::PROXY_AUTHORIZATION,
    header::TE,
    header::TRAILER,
    header::TRANSFER_ENCODING,
    header::UPGRADE,
    header::CONTENT_LENGTH,
];

/// The forwarding headers the app reads its public host, scheme and
/// client's address from.
const FORWARDED_HOST: HeaderName = HeaderName::from_static("x-forwarded-host");
const FORWARDED_PROTO: HeaderName = HeaderName::from_static("x-forwarded-proto");
const FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for");

/// The app, and the scheme HUD is reached by, where no proxy in front of it
/// said one.
struct Pages {
    web: Web,
    scheme: HeaderValue,
}

/// `routes`, every request they don't take handed to the app at `web`.
/// The scheme the app is told is `public_origin`'s, unless a proxy in front
/// of HUD says one (`X-Forwarded-Proto`).
pub fn pages(routes: Router<Arc<Hud>>, web: Web, public_origin: &str) -> Router<Arc<Hud>> {
    let scheme = public_origin.split(':').next().unwrap_or_default();
    let pages = Arc::new(Pages {
        web,
        scheme: HeaderValue::try_from(scheme).expect("a URL's scheme is a header value"),
    });
    routes.fallback(move |req: Request| {
        let pages = pages.clone();
        async move { page(&pages, req).await }
    })
}

async fn page(pages: &Pages, req: Request) -> Response {
    if OWN.iter().any(|p| req.uri().path().starts_with(p)) {
        return StatusCode::NOT_FOUND.into_response();
    }
    name(&req, "web");
    match handed(pages, req).await {
        Ok(res) => res,
        Err(e) => {
            let why = hud_core::net::describe(&e);
            let mut res =
                (StatusCode::BAD_GATEWAY, "The pages can't be reached now.\n").into_response();
            res.extensions_mut()
                .insert(Cause(format!("the web app: {why}")));
            res
        }
    }
}

/// `req`, as the app answers it. The app sees the host it was asked for,
/// as `Host` and `X-Forwarded-Host`, the scheme, and the client's address
/// after any a proxy in front of HUD named (`X-Forwarded-For`). Cookies go
/// both ways, a redirect goes back to the browser to follow, and a body
/// goes on as it comes, either way.
async fn handed(pages: &Pages, req: Request) -> reqwest::Result<Response> {
    let (parts, body) = req.into_parts();
    let at = parts.uri.path_and_query().map_or("/", |p| p.as_str());
    let mut headers = kept(&parts.headers);
    if let Some(host) = parts.headers.get(header::HOST) {
        headers.entry(FORWARDED_HOST).or_insert(host.clone());
    }
    headers
        .entry(FORWARDED_PROTO)
        .or_insert(pages.scheme.clone());
    let peer = parts.extensions.get::<ConnectInfo<SocketAddr>>();
    let peer = peer.map(|c| c.0.ip().to_string());
    let named = parts.headers.get_all(FORWARDED_FOR).iter();
    let named = named.filter_map(|v| v.to_str().ok());
    let forwarded = named.chain(peer.as_deref()).collect::<Vec<_>>().join(", ");
    if let Ok(value) = HeaderValue::try_from(forwarded)
        && !value.is_empty()
    {
        headers.insert(FORWARDED_FOR, value);
    }
    let asked = pages.web.request(parts.method, at).headers(headers);
    let asked = match body.is_end_stream() {
        true => asked,
        false => asked.body(reqwest::Body::wrap_stream(body.into_data_stream())),
    };
    let answer = pages.web.execute(asked).await?;
    let status = answer.status();
    let headers = kept(answer.headers());
    let mut res = Response::new(Body::from_stream(answer.bytes_stream()));
    *res.status_mut() = status;
    *res.headers_mut() = headers;
    Ok(res)
}

/// `headers`, but for those about one hop.
fn kept(headers: &HeaderMap) -> HeaderMap {
    let mut out = headers.clone();
    for name in &HOP {
        out.remove(name);
    }
    out
}

#[cfg(test)]
mod tests;