diff --git a/Cargo.toml b/Cargo.toml index 48d7aeab..bc9365e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,9 @@ serde_json = "1" anyhow = "1" strsim = "0.11" crossterm = "0.28" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "fs", "signal"] } +axum = "0.8" +tower-http = { version = "0.6", features = ["fs", "cors", "set-header"] } [profile.release] debug = "line-tables-only" diff --git a/crates/fastled-cli/Cargo.toml b/crates/fastled-cli/Cargo.toml index 5138ebf5..c5f78f23 100644 --- a/crates/fastled-cli/Cargo.toml +++ b/crates/fastled-cli/Cargo.toml @@ -25,6 +25,9 @@ serde_json = { workspace = true } anyhow = { workspace = true } strsim = { workspace = true } crossterm = { workspace = true } +tokio = { workspace = true } +axum = { workspace = true } +tower-http = { workspace = true } tempfile = "3" [package.metadata.binstall] diff --git a/crates/fastled-cli/src/main.rs b/crates/fastled-cli/src/main.rs index 9377ccdc..d6dec2c6 100644 --- a/crates/fastled-cli/src/main.rs +++ b/crates/fastled-cli/src/main.rs @@ -6,6 +6,7 @@ mod archive; mod build; mod keyboard; mod project; +mod server; mod viewer; mod watcher; diff --git a/crates/fastled-cli/src/server.rs b/crates/fastled-cli/src/server.rs new file mode 100644 index 00000000..fde22a57 --- /dev/null +++ b/crates/fastled-cli/src/server.rs @@ -0,0 +1,180 @@ +#![allow(dead_code)] // Server module is being wired in incrementally. + +//! Embedded HTTP/HTTPS static file server. +//! +//! Serves compiled FastLED output (JS, WASM, HTML) with the correct +//! COOP/COEP headers for SharedArrayBuffer support. When index.html +//! does not exist yet (compilation in progress) a built-in loading page +//! is returned that polls `/build-status.json` for live updates. + +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; + +use axum::extract::State; +use axum::http::{header, HeaderValue, StatusCode}; +use axum::response::{Html, IntoResponse, Response}; +use axum::routing::get; +use axum::Router; +use tower_http::set_header::SetResponseHeaderLayer; + +// --------------------------------------------------------------------------- +// Loading page (shown while compilation is in progress) +// --------------------------------------------------------------------------- + +const LOADING_PAGE: &str = r#" + + +FastLED - Compiling... + + + +
+
Compiling...
+
+"#; + +// --------------------------------------------------------------------------- +// Server state +// --------------------------------------------------------------------------- + +#[derive(Clone)] +struct AppState { + serve_dir: Arc, +} + +// --------------------------------------------------------------------------- +// Handlers +// --------------------------------------------------------------------------- + +/// Serve index.html or the loading page if it doesn't exist yet. +async fn serve_index(State(state): State) -> Response { + let index = state.serve_dir.join("index.html"); + if index.is_file() { + match tokio::fs::read(&index).await { + Ok(data) => ( + StatusCode::OK, + [(header::CONTENT_TYPE, "text/html; charset=utf-8")], + data, + ) + .into_response(), + Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + } + } else { + Html(LOADING_PAGE).into_response() + } +} + +/// Serve any file from the output directory. +async fn serve_file( + State(state): State, + axum::extract::Path(path): axum::extract::Path, +) -> Response { + let file_path = state.serve_dir.join(&path); + + // Prevent directory traversal. + let canonical = match file_path.canonicalize() { + Ok(p) => p, + Err(_) => return StatusCode::NOT_FOUND.into_response(), + }; + let serve_canonical = match state.serve_dir.canonicalize() { + Ok(p) => p, + Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(), + }; + if !canonical.starts_with(&serve_canonical) { + return StatusCode::FORBIDDEN.into_response(); + } + + match tokio::fs::read(&file_path).await { + Ok(data) => { + let mime = mime_for_path(&path); + (StatusCode::OK, [(header::CONTENT_TYPE, mime)], data).into_response() + } + Err(_) => StatusCode::NOT_FOUND.into_response(), + } +} + +fn mime_for_path(path: &str) -> &'static str { + match path.rsplit('.').next().unwrap_or("") { + "html" => "text/html; charset=utf-8", + "js" => "text/javascript; charset=utf-8", + "mjs" => "text/javascript; charset=utf-8", + "wasm" => "application/wasm", + "css" => "text/css; charset=utf-8", + "json" => "application/json", + "png" => "image/png", + "svg" => "image/svg+xml", + "ico" => "image/x-icon", + "ttf" | "otf" => "font/ttf", + "woff" => "font/woff", + "woff2" => "font/woff2", + "map" => "application/json", + _ => "application/octet-stream", + } +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// Start the HTTP server in a background tokio task. +/// +/// Returns the actual address the server bound to (useful when port 0 is +/// requested for automatic assignment). +pub async fn start_server(serve_dir: PathBuf, port: u16) -> anyhow::Result { + let state = AppState { + serve_dir: Arc::new(serve_dir), + }; + + let app = Router::new() + .route("/", get(serve_index)) + .route("/{*path}", get(serve_file)) + .layer(SetResponseHeaderLayer::overriding( + axum::http::HeaderName::from_static("cross-origin-embedder-policy"), + HeaderValue::from_static("credentialless"), + )) + .layer(SetResponseHeaderLayer::overriding( + axum::http::HeaderName::from_static("cross-origin-opener-policy"), + HeaderValue::from_static("same-origin"), + )) + .layer(SetResponseHeaderLayer::overriding( + header::CACHE_CONTROL, + HeaderValue::from_static("no-cache, no-store, must-revalidate"), + )) + .with_state(state); + + let listener = tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], port))).await?; + let addr = listener.local_addr()?; + + tokio::spawn(async move { + axum::serve(listener, app).await.ok(); + }); + + Ok(addr) +}