use axum::{
body::Body,
http::{Request, header},
middleware::Next,
response::Response,
};
pub async fn security_headers_middleware(
req: Request<Body>,
next: Next,
) -> Response {
let mut response = next.run(req).await;
let headers = response.headers_mut();
headers.insert(header::X_FRAME_OPTIONS, "DENY".parse().unwrap());
headers.insert(header::X_CONTENT_TYPE_OPTIONS, "nosniff".parse().unwrap());
headers.insert(header::X_XSS_PROTECTION, "1; mode=block".parse().unwrap());
let cfg = crate::Config::load();
let csp = if cfg.app_debug {
concat!(
"default-src 'self'; ",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:5173 http://127.0.0.1:5173 https:; ",
"style-src 'self' 'unsafe-inline' http://localhost:5173 http://127.0.0.1:5173 https:; ",
"font-src 'self' https: data:; ",
"img-src 'self' data: https:; ",
"connect-src 'self' ws://localhost:5173 ws://127.0.0.1:5173 http://localhost:5173 http://127.0.0.1:5173 https:;"
)
} else {
concat!(
"default-src 'self'; ",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; ",
"style-src 'self' 'unsafe-inline' https:; ",
"font-src 'self' https: data:; ",
"img-src 'self' data: https:; ",
"connect-src 'self' https:;"
)
};
headers.insert(header::CONTENT_SECURITY_POLICY, csp.parse().unwrap());
response
}