Skip to main content

zagens_runtime_api/
cors.rs

1//! Default CORS layer for the runtime HTTP API.
2
3use axum::http::{HeaderValue, Method};
4use tower_http::cors::{Any, CorsLayer};
5
6const DEFAULT_CORS_ORIGINS: &[&str] = &[
7    "http://localhost:3000",
8    "http://127.0.0.1:3000",
9    "http://localhost:1420",
10    "http://127.0.0.1:1420",
11    "tauri://localhost",
12    "http://tauri.localhost",
13    "https://tauri.localhost",
14];
15
16pub fn cors_layer(extra_origins: &[String]) -> CorsLayer {
17    let mut origins: Vec<HeaderValue> = DEFAULT_CORS_ORIGINS
18        .iter()
19        .filter_map(|o| HeaderValue::from_str(o).ok())
20        .collect();
21    for raw in extra_origins {
22        let trimmed = raw.trim();
23        if trimmed.is_empty() {
24            continue;
25        }
26        match HeaderValue::from_str(trimmed) {
27            Ok(value) if !origins.contains(&value) => origins.push(value),
28            Ok(_) => {}
29            Err(err) => tracing::warn!(
30                "Ignoring invalid CORS origin '{trimmed}': {err}; expected scheme://host[:port]"
31            ),
32        }
33    }
34    CorsLayer::new()
35        .allow_origin(origins)
36        .allow_methods([
37            Method::GET,
38            Method::POST,
39            Method::PATCH,
40            Method::DELETE,
41            Method::OPTIONS,
42        ])
43        .allow_headers(Any)
44}