| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| use crate::agent_state::AgentStateDb; |
| use crate::config::SpfConfig; |
| use crate::config_db::SpfConfigDb; |
| use crate::fs::SpfFs; |
| use crate::mcp; |
| use crate::session::Session; |
| use crate::storage::SpfStorage; |
| use crate::tmp_db::SpfTmpDb; |
| use ed25519_dalek::{Signature, Verifier, VerifyingKey}; |
| use iroh::Endpoint; |
| use serde_json::{json, Value}; |
| use sha2::{Sha256, Digest}; |
| use std::collections::{HashMap, HashSet}; |
| use std::sync::{Arc, Mutex}; |
| use std::time::{Duration, Instant}; |
|
|
| |
| #[derive(Debug, Clone)] |
| pub struct MeshPeerStatus { |
| pub role: crate::config::AgentRole, |
| pub name: String, |
| pub last_seen: Instant, |
| } |
| use axum::{ |
| Router, |
| middleware, |
| routing::{get, post}, |
| extract::{Request, State, Query, Path, ws::{WebSocketUpgrade, WebSocket, Message}}, |
| http::{HeaderMap, HeaderName, Method, StatusCode, header}, |
| response::{IntoResponse, Response}, |
| body::Body, |
| Json, |
| }; |
| use tower::ServiceBuilder; |
| use tower_http::{ |
| trace::TraceLayer, |
| limit::RequestBodyLimitLayer, |
| catch_panic::CatchPanicLayer, |
| sensitive_headers::SetSensitiveRequestHeadersLayer, |
| compression::CompressionLayer, |
| }; |
|
|
| const PROTOCOL_VERSION: &str = "2024-11-05"; |
| const TIMESTAMP_WINDOW_SECS: u64 = 30; |
| const NONCE_EXPIRY_SECS: u64 = 60; |
|
|
| |
| |
| pub struct ServerState { |
| pub config: SpfConfig, |
| pub config_db: Option<SpfConfigDb>, |
| pub session: Mutex<Session>, |
| pub storage: SpfStorage, |
| pub tmp_db: Option<SpfTmpDb>, |
| pub agent_db: Option<AgentStateDb>, |
| pub fs_db: Option<SpfFs>, |
| pub pub_key_hex: String, |
| pub trusted_keys: HashSet<String>, |
| pub auth_mode: String, |
| pub nonce_cache: Mutex<HashMap<String, Instant>>, |
| pub listeners: Vec<Box<dyn crate::dispatch::DispatchListener>>, |
| |
| pub mesh_tx: Option<std::sync::mpsc::Sender<crate::mesh::MeshRequest>>, |
| |
| pub peers: HashMap<String, crate::identity::PeerInfo>, |
| |
| pub transformer: Option<std::sync::Arc<std::sync::RwLock<crate::transformer_tools::TransformerState>>>, |
| |
| pub transformer_config: crate::config::TransformerConfig, |
| |
| pub pipeline: std::sync::Arc<std::sync::Mutex<crate::pipeline::PipelineState>>, |
| |
| pub signing_key: ed25519_dalek::SigningKey, |
| |
| pub network_config: crate::config::NetworkConfig, |
| |
| pub pool_state: Option<std::sync::Arc<crate::network::PoolState>>, |
| |
| pub browser: std::sync::Mutex<crate::browser::BrowserSession>, |
| |
| pub ws_browser_channels: std::sync::Mutex<Option<crate::browser::WsBrowserChannels>>, |
| |
| pub http_port: u16, |
| |
| pub tracked_peers: Mutex<HashMap<String, MeshPeerStatus>>, |
| |
| pub orchestrator_state: Mutex<Option<Arc<std::sync::Mutex<crate::orchestrator::OrchestratorState>>>>, |
| |
| pub endpoint: Mutex<Option<Endpoint>>, |
| |
| pub tokio_handle: Mutex<Option<tokio::runtime::Handle>>, |
| } |
|
|
| |
| pub fn tracked_peer_count(state: &Arc<ServerState>) -> usize { |
| state.tracked_peers.lock().unwrap().len() |
| } |
|
|
| |
| |
| #[derive(Clone)] |
| struct AppState { |
| inner: Arc<ServerState>, |
| api_key: String, |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| fn extract_header(headers: &HeaderMap, name: &str) -> Option<String> { |
| headers.get(name) |
| .and_then(|v| v.to_str().ok()) |
| .map(|s| s.to_string()) |
| } |
|
|
| |
| |
| fn check_auth(headers: &HeaderMap, method_str: &str, path: &str, |
| body: &str, api_key: &str, state: &ServerState) -> bool { |
| let mode = state.auth_mode.as_str(); |
|
|
| |
| if mode == "key" || mode == "both" { |
| if let Some(key) = extract_header(headers, "x-spf-key") { |
| return key == api_key; |
| } |
| } |
|
|
| |
| if mode == "crypto" || mode == "both" { |
| if let (Some(pub_hex), Some(sig_hex), Some(time_str), Some(nonce)) = ( |
| extract_header(headers, "x-spf-pub"), |
| extract_header(headers, "x-spf-sig"), |
| extract_header(headers, "x-spf-time"), |
| extract_header(headers, "x-spf-nonce"), |
| ) { |
| return verify_crypto_auth( |
| &pub_hex, &sig_hex, &time_str, &nonce, |
| method_str, path, body, |
| &state.trusted_keys, &state.nonce_cache, |
| ); |
| } |
| } |
|
|
| |
| if mode == "both" || mode == "key" { |
| if let Some(peer_key_header) = extract_header(headers, "x-spf-peer-key") { |
| if let Some(peer_pub) = extract_header(headers, "x-spf-peer-pub") { |
| |
| if state.trusted_keys.contains(&peer_pub) { |
| let expected = crate::identity::derive_peer_api_key( |
| &state.signing_key, &peer_pub |
| ); |
| if let Some(expected_key) = expected { |
| if peer_key_header == expected_key { |
| return true; |
| } |
| } |
| } |
| } |
| } |
| } |
|
|
| false |
| } |
|
|
| |
| fn verify_crypto_auth(pub_hex: &str, sig_hex: &str, time_str: &str, nonce: &str, |
| method: &str, path: &str, body: &str, |
| trusted_keys: &HashSet<String>, |
| nonce_cache: &Mutex<HashMap<String, Instant>>) -> bool { |
| |
| if !trusted_keys.contains(pub_hex) { |
| return false; |
| } |
|
|
| |
| let timestamp: u64 = match time_str.parse() { |
| Ok(t) => t, |
| Err(_) => return false, |
| }; |
| let now = std::time::SystemTime::now() |
| .duration_since(std::time::UNIX_EPOCH) |
| .unwrap_or_default() |
| .as_secs(); |
| if now.abs_diff(timestamp) > TIMESTAMP_WINDOW_SECS { |
| return false; |
| } |
|
|
| |
| { |
| let mut cache = nonce_cache.lock().unwrap(); |
| let instant_now = Instant::now(); |
| cache.retain(|_, t| instant_now.duration_since(*t).as_secs() < NONCE_EXPIRY_SECS); |
| if cache.contains_key(nonce) { |
| return false; |
| } |
| cache.insert(nonce.to_string(), instant_now); |
| } |
|
|
| |
| let body_hash = hex::encode(Sha256::digest(body.as_bytes())); |
| let canonical = format!("{}\n{}\n{}\n{}\n{}", method, path, body_hash, time_str, nonce); |
|
|
| |
| let pub_bytes: [u8; 32] = match hex::decode(pub_hex) { |
| Ok(b) if b.len() == 32 => match b.try_into() { |
| Ok(arr) => arr, |
| Err(_) => return false, |
| }, |
| _ => return false, |
| }; |
| let verifying_key = match VerifyingKey::from_bytes(&pub_bytes) { |
| Ok(vk) => vk, |
| Err(_) => return false, |
| }; |
|
|
| |
| let sig_bytes: [u8; 64] = match hex::decode(sig_hex) { |
| Ok(b) if b.len() == 64 => match b.try_into() { |
| Ok(arr) => arr, |
| Err(_) => return false, |
| }, |
| _ => return false, |
| }; |
| let signature = Signature::from_bytes(&sig_bytes); |
|
|
| |
| verifying_key.verify(canonical.as_bytes(), &signature).is_ok() |
| } |
|
|
| |
| |
| |
|
|
| |
| fn unauthorized() -> Response { |
| (StatusCode::UNAUTHORIZED, Json(json!({ |
| "jsonrpc": "2.0", |
| "id": null, |
| "error": {"code": -32000, "message": "Unauthorized: invalid or missing authentication"} |
| }))).into_response() |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| fn handle_jsonrpc(body: &str, state: &Arc<ServerState>) -> (StatusCode, Value) { |
| if body.is_empty() { |
| return (StatusCode::BAD_REQUEST, json!({ |
| "jsonrpc": "2.0", "id": null, |
| "error": {"code": -32700, "message": "Parse error: empty body"} |
| })); |
| } |
|
|
| let msg: Value = match serde_json::from_str(body) { |
| Ok(v) => v, |
| Err(_) => { |
| return (StatusCode::BAD_REQUEST, json!({ |
| "jsonrpc": "2.0", "id": null, |
| "error": {"code": -32700, "message": "Parse error: invalid JSON"} |
| })); |
| } |
| }; |
|
|
| let method = msg["method"].as_str().unwrap_or(""); |
| let id = &msg["id"]; |
| let params = &msg["params"]; |
|
|
| match method { |
| "initialize" => { |
| (StatusCode::OK, json!({ |
| "jsonrpc": "2.0", |
| "id": id, |
| "result": { |
| "protocolVersion": PROTOCOL_VERSION, |
| "capabilities": { "tools": {} }, |
| "serverInfo": { |
| "name": "spf-smart-gate", |
| "version": env!("CARGO_PKG_VERSION"), |
| } |
| } |
| })) |
| } |
|
|
| "tools/list" => { |
| (StatusCode::OK, json!({ |
| "jsonrpc": "2.0", |
| "id": id, |
| "result": { "tools": mcp::tool_definitions() } |
| })) |
| } |
|
|
| "tools/call" => { |
| let name = params["name"].as_str().unwrap_or(""); |
| let args = params.get("arguments").cloned().unwrap_or(json!({})); |
|
|
| |
| let resp = crate::dispatch::call(state, crate::dispatch::Source::Http, name, &args); |
| (StatusCode::OK, json!({ |
| "jsonrpc": "2.0", |
| "id": id, |
| "result": { "content": [resp.result] } |
| })) |
| } |
|
|
| "ping" => (StatusCode::OK, json!({"jsonrpc": "2.0", "id": id, "result": {}})), |
|
|
| _ => (StatusCode::BAD_REQUEST, json!({ |
| "jsonrpc": "2.0", |
| "id": id, |
| "error": {"code": -32601, "message": format!("Unknown method: {}", method)} |
| })), |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| async fn cors_middleware(request: Request, next: middleware::Next) -> Response { |
| |
| if request.method() == Method::OPTIONS { |
| return Response::builder() |
| .status(StatusCode::OK) |
| .header("access-control-allow-origin", "*") |
| .header("access-control-allow-methods", "GET, POST, OPTIONS") |
| .header("access-control-allow-headers", |
| "content-type, authorization, x-spf-key, x-spf-sig, x-spf-pub, x-spf-time, x-spf-nonce") |
| .header("access-control-max-age", "3600") |
| .body(axum::body::Body::empty()) |
| .unwrap(); |
| } |
|
|
| let mut response = next.run(request).await; |
| let headers = response.headers_mut(); |
| headers.insert("access-control-allow-origin", "*".parse().unwrap()); |
| headers.insert("access-control-allow-methods", "GET, POST, OPTIONS".parse().unwrap()); |
| headers.insert("access-control-allow-headers", |
| "content-type, authorization, x-spf-key, x-spf-sig, x-spf-pub, x-spf-time, x-spf-nonce".parse().unwrap()); |
| response |
| } |
|
|
| |
| |
| |
|
|
| |
| async fn health_handler(State(app): State<AppState>) -> Response { |
| let session = app.inner.session.lock().unwrap(); |
| let action_count = session.action_count; |
| drop(session); |
|
|
| Json(json!({ |
| "status": "ok", |
| "version": env!("CARGO_PKG_VERSION"), |
| "actions": action_count, |
| })).into_response() |
| } |
|
|
| |
| async fn status_handler( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| ) -> Response { |
| if !check_auth(&headers, "GET", "/status", "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
|
|
| let session = app.inner.session.lock().unwrap(); |
| let summary = session.status_summary(); |
| drop(session); |
|
|
| Json(json!({ |
| "version": env!("CARGO_PKG_VERSION"), |
| "mode": format!("{:?}", app.inner.config.enforce_mode), |
| "session": summary, |
| })).into_response() |
| } |
|
|
| |
| async fn tools_handler( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| ) -> Response { |
| if !check_auth(&headers, "GET", "/tools", "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
|
|
| Json(json!({ |
| "tools": mcp::tool_definitions() |
| })).into_response() |
| } |
|
|
| |
| |
| |
| async fn mcp_handler( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| body: String, |
| ) -> Response { |
| if !check_auth(&headers, "POST", "/mcp/v1", &body, &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
|
|
| let state = app.inner.clone(); |
| let result = tokio::time::timeout( |
| Duration::from_secs(30), |
| tokio::task::spawn_blocking(move || handle_jsonrpc(&body, &state)), |
| ).await; |
|
|
| match result { |
| Ok(Ok((status, json))) => (status, Json(json)).into_response(), |
| Ok(Err(_)) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ |
| "jsonrpc": "2.0", "id": null, |
| "error": {"code": -32603, "message": "Internal error"} |
| }))).into_response(), |
| Err(_) => (StatusCode::REQUEST_TIMEOUT, Json(json!({ |
| "jsonrpc": "2.0", "id": null, |
| "error": {"code": -32000, "message": "Request timeout (30s)"} |
| }))).into_response(), |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| async fn ws_handler( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| ws: WebSocketUpgrade, |
| ) -> Response { |
| if !check_auth(&headers, "GET", "/ws", "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
|
|
| let state = app.inner.clone(); |
| ws.on_upgrade(move |socket| handle_ws(socket, state)) |
| } |
|
|
| |
| |
| async fn handle_ws(mut socket: WebSocket, state: Arc<ServerState>) { |
| eprintln!("[SPF-WS] Client connected"); |
|
|
| while let Some(Ok(msg)) = socket.recv().await { |
| match msg { |
| Message::Text(text) => { |
| let state_ref = state.clone(); |
| let result = tokio::time::timeout( |
| Duration::from_secs(30), |
| tokio::task::spawn_blocking(move || handle_jsonrpc(&text, &state_ref)), |
| ).await; |
|
|
| let resp_json = match result { |
| Ok(Ok((_, json))) => json, |
| Ok(Err(_)) => json!({"jsonrpc": "2.0", "id": null, |
| "error": {"code": -32603, "message": "Internal error"}}), |
| Err(_) => json!({"jsonrpc": "2.0", "id": null, |
| "error": {"code": -32000, "message": "Request timeout (30s)"}}), |
| }; |
| let resp = serde_json::to_string(&resp_json).unwrap_or_default(); |
| if socket.send(Message::Text(resp.into())).await.is_err() { |
| break; |
| } |
| } |
| Message::Ping(data) => { |
| if socket.send(Message::Pong(data)).await.is_err() { |
| break; |
| } |
| } |
| Message::Close(_) => break, |
| _ => {} |
| } |
| } |
|
|
| eprintln!("[SPF-WS] Client disconnected"); |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| fn find_available_port(bind: &str, preferred: u16) -> u16 { |
| let range_end = preferred.saturating_add(1000); |
| for port in preferred..=range_end { |
| let addr = format!("{}:{}", bind, port); |
| match std::net::TcpListener::bind(&addr) { |
| Ok(listener) => { |
| drop(listener); |
| if port != preferred { |
| eprintln!( |
| "[SPF] Port {} in use — auto-selected port {}", |
| preferred, port |
| ); |
| } |
| return port; |
| } |
| Err(_) => continue, |
| } |
| } |
| eprintln!( |
| "[SPF] WARNING: No port available in {}..={}, falling back to {}", |
| preferred, range_end, preferred |
| ); |
| preferred |
| } |
|
|
| |
| |
| |
| |
|
|
| |
| async fn proxy_handler( |
| State(app): State<AppState>, |
| Query(params): Query<HashMap<String, String>>, |
| ) -> Response { |
| let url = match params.get("url") { |
| Some(u) if !u.is_empty() => u.clone(), |
| _ => return (StatusCode::BAD_REQUEST, "Missing url parameter").into_response(), |
| }; |
| if let Err(e) = crate::web::validate_url(&url) { |
| return (StatusCode::BAD_REQUEST, e).into_response(); |
| } |
| let ws_port = app.inner.http_port; |
| let state = app.inner.clone(); |
| match tokio::task::spawn_blocking(move || { |
| state.browser.lock().unwrap().proxy_page(&url, ws_port) |
| }).await { |
| Ok(Ok(page)) => Response::builder() |
| .header(header::CONTENT_TYPE, "text/html; charset=utf-8") |
| .body(Body::from(page.html)) |
| .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()), |
| Ok(Err(e)) => (StatusCode::BAD_GATEWAY, format!("Proxy error: {}", e)).into_response(), |
| Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), |
| } |
| } |
|
|
| |
| async fn proxy_asset_handler( |
| State(app): State<AppState>, |
| Query(params): Query<HashMap<String, String>>, |
| ) -> Response { |
| let url = match params.get("url") { |
| Some(u) if !u.is_empty() => u.clone(), |
| _ => return (StatusCode::BAD_REQUEST, "Missing url parameter").into_response(), |
| }; |
| if let Err(e) = crate::web::validate_url(&url) { |
| return (StatusCode::BAD_REQUEST, e).into_response(); |
| } |
| let state = app.inner.clone(); |
| match tokio::task::spawn_blocking(move || { |
| state.browser.lock().unwrap().proxy_asset(&url) |
| }).await { |
| Ok(Ok(asset)) => Response::builder() |
| .header(header::CONTENT_TYPE, asset.content_type) |
| .body(Body::from(asset.data)) |
| .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()), |
| Ok(Err(e)) => (StatusCode::BAD_GATEWAY, format!("Asset error: {}", e)).into_response(), |
| Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), |
| } |
| } |
|
|
| |
| |
| async fn ws_browser_handler( |
| ws: WebSocketUpgrade, |
| State(app): State<AppState>, |
| ) -> impl IntoResponse { |
| ws.on_upgrade(move |socket| async move { |
| |
| let channels = app.inner.ws_browser_channels.lock() |
| .ok() |
| .and_then(|mut g| g.take()); |
| if let Some(channels) = channels { |
| handle_browser_ws(socket, channels).await; |
| } |
| |
| }) |
| } |
|
|
| |
| async fn handle_browser_ws( |
| mut socket: WebSocket, |
| channels: crate::browser::WsBrowserChannels, |
| ) { |
| loop { |
| |
| while let Ok(cmd) = channels.cmd_rx.try_recv() { |
| if socket.send(Message::Text(cmd.into())).await.is_err() { |
| return; |
| } |
| } |
| |
| match tokio::time::timeout( |
| std::time::Duration::from_millis(50), |
| socket.recv(), |
| ).await { |
| Ok(Some(Ok(Message::Text(text)))) => { |
| if channels.resp_tx.send(text.to_string()).is_err() { |
| return; |
| } |
| } |
| Ok(Some(Ok(Message::Close(_)))) | Ok(Some(Err(_))) | Ok(None) => return, |
| _ => {} |
| } |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| async fn ws_channel_handler( |
| State(app): State<AppState>, |
| Path(channel_id): Path<String>, |
| headers: HeaderMap, |
| Query(params): Query<HashMap<String, String>>, |
| ws: WebSocketUpgrade, |
| ) -> Response { |
| if !check_auth(&headers, "GET", &format!("/ws/channel/{}", channel_id), "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
|
|
| |
| let peer_key = extract_header(&headers, "x-spf-pub") |
| .or_else(|| params.get("key").cloned()) |
| .unwrap_or_else(|| "anonymous".to_string()); |
| let peer_name = extract_header(&headers, "x-spf-name") |
| .or_else(|| params.get("name").cloned()) |
| .unwrap_or_else(|| peer_key[..8.min(peer_key.len())].to_string()); |
|
|
| ws.on_upgrade(move |socket| { |
| crate::channel::handle_channel_ws(socket, channel_id, peer_key, peer_name) |
| }) |
| } |
|
|
| |
| |
| async fn api_channel_create( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| Json(body): Json<Value>, |
| ) -> Response { |
| if !check_auth(&headers, "POST", "/api/channel/create", "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
| let name = body["name"].as_str().unwrap_or("unnamed"); |
| let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex); |
| let display_name = body["display_name"].as_str().unwrap_or("Agent"); |
| Json(crate::channel::api_create_channel(name, key, display_name)).into_response() |
| } |
|
|
| |
| |
| async fn api_channel_join( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| Json(body): Json<Value>, |
| ) -> Response { |
| if !check_auth(&headers, "POST", "/api/channel/join", "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
| let channel_id = body["channel_id"].as_str().unwrap_or(""); |
| let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex); |
| let name = body["name"].as_str().unwrap_or("Agent"); |
| Json(crate::channel::api_join_channel(channel_id, key, name)).into_response() |
| } |
|
|
| |
| |
| async fn api_channel_leave( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| Json(body): Json<Value>, |
| ) -> Response { |
| if !check_auth(&headers, "POST", "/api/channel/leave", "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
| let channel_id = body["channel_id"].as_str().unwrap_or(""); |
| let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex); |
| Json(crate::channel::api_leave_channel(channel_id, key)).into_response() |
| } |
|
|
| |
| |
| async fn api_channel_send( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| Json(body): Json<Value>, |
| ) -> Response { |
| if !check_auth(&headers, "POST", "/api/channel/send", "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
| let channel_id = body["channel_id"].as_str().unwrap_or(""); |
| let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex); |
| let name = body["name"].as_str().unwrap_or("Agent"); |
| let text = body["text"].as_str().unwrap_or(""); |
| let msg_type = match body["msg_type"].as_str() { |
| Some("tool_result") => crate::channel::MessageType::ToolResult, |
| Some("system") => crate::channel::MessageType::System, |
| _ => crate::channel::MessageType::Text, |
| }; |
| Json(crate::channel::api_send_message(channel_id, key, name, text, msg_type)).into_response() |
| } |
|
|
| |
| async fn api_channel_list( |
| State(app): State<AppState>, |
| headers: HeaderMap, |
| ) -> Response { |
| if !check_auth(&headers, "GET", "/api/channel/list", "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
| Json(crate::channel::api_list_channels()).into_response() |
| } |
|
|
| |
| async fn api_channel_history( |
| State(app): State<AppState>, |
| Path(channel_id): Path<String>, |
| headers: HeaderMap, |
| Query(params): Query<HashMap<String, String>>, |
| ) -> Response { |
| if !check_auth(&headers, "GET", &format!("/api/channel/{}/history", channel_id), "", &app.api_key, &app.inner) { |
| return unauthorized(); |
| } |
| let limit: usize = params.get("limit") |
| .and_then(|l| l.parse().ok()) |
| .unwrap_or(50); |
| Json(crate::channel::api_channel_history(&channel_id, limit)).into_response() |
| } |
|
|
| |
| fn build_router(app_state: AppState) -> Router { |
| |
| |
| |
| |
| let middleware_stack = ServiceBuilder::new() |
| |
| .layer(TraceLayer::new_for_http()) |
| |
| .layer(SetSensitiveRequestHeadersLayer::new([ |
| HeaderName::from_static("x-spf-key"), |
| HeaderName::from_static("x-spf-sig"), |
| ])) |
| |
| .layer(RequestBodyLimitLayer::new(10 * 1024 * 1024)) |
| |
| .layer(CatchPanicLayer::new()); |
|
|
| Router::new() |
| |
| .route("/health", get(health_handler)) |
| |
| .route("/status", get(status_handler)) |
| .route("/tools", get(tools_handler)) |
| .route("/mcp/v1", post(mcp_handler)) |
| |
| .route("/ws", get(ws_handler)) |
| |
| .route("/proxy", get(proxy_handler)) |
| .route("/proxy/asset", get(proxy_asset_handler)) |
| .route("/ws/browser", get(ws_browser_handler)) |
| |
| .route("/ws/channel/{id}", get(ws_channel_handler)) |
| |
| .route("/api/channel/create", post(api_channel_create)) |
| .route("/api/channel/join", post(api_channel_join)) |
| .route("/api/channel/leave", post(api_channel_leave)) |
| .route("/api/channel/send", post(api_channel_send)) |
| .route("/api/channel/list", get(api_channel_list)) |
| .route("/api/channel/{id}/history", get(api_channel_history)) |
| |
| .layer(middleware::from_fn(cors_middleware)) |
| |
| .layer(CompressionLayer::new()) |
| |
| .layer(middleware_stack) |
| .with_state(app_state) |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| pub async fn serve( |
| state: Arc<ServerState>, |
| bind: String, |
| port: u16, |
| api_key: String, |
| tls: Option<(Vec<u8>, Vec<u8>)>, |
| ) { |
| rustls::crypto::ring::default_provider().install_default().ok(); |
|
|
| |
| |
| |
| let api_key = match std::env::var("SPF_API_KEY") { |
| Ok(env_key) if !env_key.is_empty() => { |
| eprintln!("[SPF-HTTP] API key loaded from SPF_API_KEY env var"); |
| env_key |
| } |
| _ => api_key, |
| }; |
|
|
| let port = find_available_port(&bind, port); |
| let addr = format!("{}:{}", bind, port); |
|
|
| let app_state = AppState { |
| inner: state, |
| api_key, |
| }; |
|
|
| let app = build_router(app_state); |
|
|
| eprintln!("[SPF-HTTP] Listening on {}", addr); |
|
|
| if let Some((cert_pem, key_pem)) = tls { |
| |
| let tls_config = axum_server::tls_rustls::RustlsConfig::from_pem(cert_pem, key_pem) |
| .await |
| .expect("[SPF-HTTP] Failed to load TLS config from PEM"); |
|
|
| let sock_addr: std::net::SocketAddr = addr.parse() |
| .expect("[SPF-HTTP] Invalid bind address"); |
|
|
| |
| let handle = axum_server::Handle::new(); |
| let shutdown_handle = handle.clone(); |
| tokio::spawn(async move { |
| tokio::signal::ctrl_c().await.ok(); |
| eprintln!("[SPF-HTTP] Graceful shutdown initiated (10s timeout)..."); |
| shutdown_handle.graceful_shutdown(Some(Duration::from_secs(10))); |
| }); |
|
|
| axum_server::bind_rustls(sock_addr, tls_config) |
| .handle(handle) |
| .serve(app.into_make_service()) |
| .await |
| .expect("[SPF-HTTP] HTTPS server failed"); |
| } else { |
| |
| let listener = tokio::net::TcpListener::bind(&addr) |
| .await |
| .expect("[SPF-HTTP] Failed to bind TCP"); |
|
|
| |
| axum::serve(listener, app) |
| .with_graceful_shutdown(async { |
| tokio::signal::ctrl_c().await.ok(); |
| eprintln!("[SPF-HTTP] Graceful shutdown initiated..."); |
| }) |
| .await |
| .expect("[SPF-HTTP] HTTP server failed"); |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| pub fn start(state: Arc<ServerState>, bind: &str, port: u16, api_key: String, tls: Option<(Vec<u8>, Vec<u8>)>) { |
| let bind = bind.to_string(); |
| let rt = tokio::runtime::Builder::new_multi_thread() |
| .worker_threads(2) |
| .enable_all() |
| .build() |
| .expect("[SPF-HTTP] Failed to build tokio runtime"); |
|
|
| rt.block_on(serve(state, bind, port, api_key, tls)); |
| } |
|
|