//! Development server for the management app's screens (`app/src/admin.spec.md`, "Screens"): //! serves `app/ui` and passes `POST /api/` to the same `AdminApi` the Tauri shell uses, //! so the screens can be opened and tested in a browser. Loopback only, and every API call needs //! the random token printed at start (in the page URL's `#token=`). //! //! jarvis-admin-dev [--port N] [--ui DIR] [--location FILE] use std::path::{Path, PathBuf}; use std::sync::Arc; use jarvis_app::admin_api::AdminApi; use serde_json::{json, Value}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; fn arg(name: &str) -> Option { let args: Vec = std::env::args().collect(); args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) } fn content_type(path: &Path) -> &'static str { match path.extension().and_then(|e| e.to_str()) { Some("html") => "text/html; charset=utf-8", Some("js") => "text/javascript; charset=utf-8", Some("css") => "text/css; charset=utf-8", Some("svg") => "image/svg+xml", Some("png") => "image/png", _ => "application/octet-stream", } } async fn respond(s: &mut TcpStream, status: &str, ctype: &str, body: &[u8]) { let head = format!("HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n", body.len()); let _ = s.write_all(head.as_bytes()).await; let _ = s.write_all(body).await; } async fn handle(mut s: TcpStream, api: Arc, ui: Arc, token: Arc) { let mut buf = Vec::new(); let mut chunk = [0u8; 8192]; let head_end = loop { let Ok(n) = s.read(&mut chunk).await else { return }; if n == 0 { return; } buf.extend_from_slice(&chunk[..n]); if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") { break i + 4; } if buf.len() > 64 * 1024 { return; } }; let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); let mut lines = head.lines(); let mut first = lines.next().unwrap_or("").split_whitespace(); let (method, path) = (first.next().unwrap_or(""), first.next().unwrap_or("/").to_owned()); let header = |name: &str| head.lines().find_map(|l| l.split_once(':') .filter(|(k, _)| k.trim().eq_ignore_ascii_case(name)).map(|(_, v)| v.trim().to_owned())); let len: usize = header("content-length").and_then(|v| v.parse().ok()).unwrap_or(0).min(4 * 1024 * 1024); while buf.len() < head_end + len { let Ok(n) = s.read(&mut chunk).await else { return }; if n == 0 { break; } buf.extend_from_slice(&chunk[..n]); } if method == "POST" && path.starts_with("/api/") { if header("x-admin-token").as_deref() != Some(token.as_str()) { return respond(&mut s, "403 Forbidden", "text/plain", b"bad token").await; } let args: Value = serde_json::from_slice(&buf[head_end..(head_end + len).min(buf.len())]).unwrap_or(json!({})); let out = match api.call(&path[5..], args).await { Ok(v) => json!({"ok": true, "value": v}), Err(e) => json!({"ok": false, "error": e}), }; return respond(&mut s, "200 OK", "application/json", out.to_string().as_bytes()).await; } if method != "GET" { return respond(&mut s, "405 Method Not Allowed", "text/plain", b"").await; } let rel = path.split(['?', '#']).next().unwrap_or("/").trim_start_matches('/'); let rel = if rel.is_empty() { "index.html" } else { rel }; if rel.split('/').any(|p| p == ".." || p.is_empty()) { return respond(&mut s, "404 Not Found", "text/plain", b"").await; } let file = ui.join(rel); match tokio::fs::read(&file).await { Ok(b) => respond(&mut s, "200 OK", content_type(&file), &b).await, Err(_) => respond(&mut s, "404 Not Found", "text/plain", b"").await, } } #[tokio::main] async fn main() { let ui = arg("--ui").map(PathBuf::from).unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("ui")); let location = arg("--location").map(PathBuf::from).or_else(jarvis_app::datadir::default_location_file) .expect("no location file path: pass --location"); let port: u16 = arg("--port").and_then(|p| p.parse().ok()).unwrap_or(0); // Log files go to the data folder once there is one (from the next start after the wizard). let logs = jarvis_app::datadir::DataDir::locate(&location).map(|d| d.logs()); let hub = jarvis_app::logs::LogHub::new(logs.as_deref()); jarvis_app::logs::install(hub.clone()); let api = Arc::new(AdminApi::new(&location, hub)); let token: String = (0..16).map(|_| format!("{:02x}", rand::random::())).collect(); let listener = TcpListener::bind(("127.0.0.1", port)).await.expect("bind"); println!("http://127.0.0.1:{}/#token={token}", listener.local_addr().unwrap().port()); let (ui, token) = (Arc::new(ui), Arc::new(token)); loop { let Ok((s, _)) = listener.accept().await else { continue }; tokio::spawn(handle(s, api.clone(), ui.clone(), token.clone())); } }