//! HTTP routes: the JSON API, the event feed, the presence socket, and //! the built client. pub mod auth; pub mod files; pub mod messages; pub mod profile; pub mod rooms; pub mod settings; use axum::Router; use axum::body::Body; use axum::extract::{DefaultBodyLimit, Request, State}; use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri, header}; use axum::middleware::{self, Next}; use axum::response::{Html, IntoResponse, Response}; use axum::routing::{delete, get, post}; use axum_extra::extract::CookieJar; use crate::auth::require_csrf; use crate::state::Shared; /// The whole application router. pub fn router(state: Shared) -> Router { let api = Router::new() .route("/bootstrap", get(auth::bootstrap)) .route("/me", get(auth::me)) .route("/setup", post(auth::setup)) .route("/register", post(auth::register)) .route("/login", post(auth::login)) .route("/logout", post(auth::logout)) .route( "/profile/avatar", post(profile::upload_avatar) .delete(profile::delete_avatar) .layer(DefaultBodyLimit::max(profile::MAX_AVATAR_BYTES + 64 * 1024)), ) .route("/avatars/{account}", get(profile::get_avatar)) .route( "/provider-configs", get(settings::list_providers).post(settings::create_provider), ) .route( "/provider-configs/login", post(settings::start_provider_login), ) .route( "/provider-configs/login/{id}", get(settings::provider_login_status).delete(settings::cancel_provider_login), ) .route("/provider-configs/{id}", delete(settings::delete_provider)) .route( "/provider-configs/{id}/models", get(settings::list_provider_models), ) .route( "/sandbox-targets", get(settings::list_targets).post(settings::create_target), ) .route("/sandbox-targets/{id}", delete(settings::delete_target)) .route("/sandbox-targets/{id}/test", post(settings::test_target)) .route("/rooms", get(rooms::list).post(rooms::create)) .route( "/rooms/{id}", get(rooms::detail) .patch(rooms::update) .delete(rooms::archive), ) .route("/rooms/{id}/members/{member}", delete(rooms::remove_member)) .route("/rooms/{id}/invites", post(rooms::create_invite)) .route( "/invites/{token}", get(rooms::invite_preview).post(rooms::join), ) .route( "/rooms/{id}/messages", get(messages::list).post(messages::send), ) .route("/rooms/{id}/events", get(messages::events)) .route("/rooms/{id}/presence", get(messages::presence)) .route("/rooms/{id}/files", get(files::list)) .route("/rooms/{id}/preview", get(rooms::preview)) .route("/rooms/{id}/file", get(files::read)) .route("/rooms/{id}/git", get(files::git)) .route("/rooms/{id}/interrupt", post(messages::interrupt)) .route("/rooms/{id}/terminal", get(files::terminal)); Router::new() .nest("/api", api) .fallback(fallback) .layer(middleware::from_fn_with_state(state.clone(), csrf)) .layer(middleware::from_fn_with_state(state.clone(), headers)) .with_state(state) } /// Whether a browser WebSocket handshake came from the page's own /// origin. The request carries the Host the browser used, so the check /// works behind a proxy and on any LAN address without relying on /// `public_url` alone. `public_url` is still accepted for a proxy that /// rewrites Host to its upstream. A client that sends no `Origin` is /// not a browser page and is left to the cookie check. pub(crate) fn websocket_origin_ok(config: &crate::config::Config, headers: &HeaderMap) -> bool { let Some(origin) = headers .get(header::ORIGIN) .and_then(|value| value.to_str().ok()) else { return true; }; let origin = origin.trim_end_matches('/'); if origin.eq_ignore_ascii_case(config.public_url.trim_end_matches('/')) { return true; } let Some(host) = headers .get(header::HOST) .and_then(|value| value.to_str().ok()) else { return false; }; let origin_authority = origin .split_once("://") .map(|(_, rest)| rest) .and_then(|rest| rest.split('/').next()) .unwrap_or(origin); origin_authority.eq_ignore_ascii_case(host) } /// Rejects a mutating API request without the matching CSRF header. /// Setup, login, registration, and joining with an invite happen before /// the client has a CSRF cookie. async fn csrf(State(_state): State, request: Request, next: Next) -> Response { let method = request.method().clone(); let path = request.uri().path().to_owned(); let exempt = path == "/api/setup" || path == "/api/login" || path == "/api/register" || (path.starts_with("/api/invites/") && method == axum::http::Method::POST); let mutating = matches!( method, axum::http::Method::POST | axum::http::Method::PATCH | axum::http::Method::PUT | axum::http::Method::DELETE ); if mutating && path.starts_with("/api") && !exempt { let jar = CookieJar::from_headers(request.headers()); if let Err(err) = require_csrf(request.headers(), &jar) { return err.into_response(); } } next.run(request).await } /// Security headers, including the CSP that names the preview origin. async fn headers(State(state): State, request: Request, next: Next) -> Response { let host = request .headers() .get(header::HOST) .and_then(|value| value.to_str().ok()) .unwrap_or("") .to_owned(); let is_preview = crate::preview::is_preview_host(&state.config, &host); let mut response = next.run(request).await; if is_preview { // The previewed app owns its own headers, including frame policy. return response; } let h = response.headers_mut(); h.insert( header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"), ); h.insert( header::REFERRER_POLICY, HeaderValue::from_static("strict-origin-when-cross-origin"), ); h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); if state.config.secure_cookies() { h.insert( header::STRICT_TRANSPORT_SECURITY, HeaderValue::from_static("max-age=31536000"), ); } let frame_src = match state.config.preview_frame_source() { Some(source) => format!("'self' {source}"), None => "'self'".to_owned(), }; let csp = format!( "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; \ script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; frame-src {frame_src}; \ frame-ancestors 'self'; base-uri 'self'; form-action 'self'" ); if let Ok(value) = HeaderValue::from_str(&csp) { h.insert(header::CONTENT_SECURITY_POLICY, value); } response } /// Sends preview hosts to the proxy and everything else to the client. async fn fallback(State(state): State, request: Request) -> Response { let host = request .headers() .get(header::HOST) .and_then(|value| value.to_str().ok()) .unwrap_or("") .to_owned(); if crate::preview::is_preview_host(&state.config, &host) { return crate::preview::proxy(state, request).await; } let uri = request.uri().clone(); spa(State(state), uri).await } /// Serves the built Nuxt app, falling back to its index for client-side /// routes. A missing build gets a page that says how to make one. async fn spa(State(state): State, uri: Uri) -> Response { let requested = uri.path().trim_start_matches('/'); if requested.contains("..") { return (StatusCode::NOT_FOUND, "not found").into_response(); } let root = &state.config.web_dir; let mut file = if requested.is_empty() { root.join("index.html") } else { root.join(requested) }; if !file.is_file() { file = root.join("index.html"); } if !file.is_file() { return ( StatusCode::SERVICE_UNAVAILABLE, Html( "rhema-together\ \

No client build

\

The server is running, but the Nuxt build is missing. Run \ pnpm install && pnpm build in web/, then reload.

", ), ) .into_response(); } let bytes = match tokio::fs::read(&file).await { Ok(bytes) => bytes, Err(_) => return (StatusCode::NOT_FOUND, "not found").into_response(), }; let mime = mime_guess::from_path(&file).first_or_octet_stream(); let cache = if file.ends_with("index.html") { "no-cache" } else { "public, max-age=3600" }; Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, mime.as_ref()) .header(header::CACHE_CONTROL, cache) .body(Body::from(bytes)) .unwrap_or_else(|_| (StatusCode::INTERNAL_SERVER_ERROR, "error").into_response()) } #[cfg(test)] mod tests { use super::*; use axum::http::{HeaderMap, HeaderValue, header}; fn config() -> crate::config::Config { crate::config::Config { public_url: "http://10.4.1.222:7800".into(), ..Default::default() } } fn headers(origin: &str, host: &str) -> HeaderMap { let mut headers = HeaderMap::new(); headers.insert(header::ORIGIN, HeaderValue::from_str(origin).unwrap()); headers.insert(header::HOST, HeaderValue::from_str(host).unwrap()); headers } #[test] fn websocket_origin_matches_the_request_host() { assert!(websocket_origin_ok( &config(), &headers("http://10.4.1.222:7800", "10.4.1.222:7800") )); assert!(websocket_origin_ok( &config(), &headers("https://together.example.com", "together.example.com") )); assert!(websocket_origin_ok( &config(), &headers("http://localhost:7800", "localhost:7800") )); } #[test] fn the_configured_public_url_survives_a_rewritten_host() { assert!(websocket_origin_ok( &config(), &headers("http://10.4.1.222:7800", "127.0.0.1:7800") )); } #[test] fn websocket_origin_rejects_another_host() { assert!(!websocket_origin_ok( &config(), &headers("http://evil.example", "10.4.1.222:7800") )); } #[test] fn a_missing_origin_is_left_to_the_cookie() { let mut headers = HeaderMap::new(); headers.insert(header::HOST, HeaderValue::from_static("localhost:7800")); assert!(websocket_origin_ok(&config(), &headers)); } }