use crate::guard::{refuse_hidden_files, refuse_paths_outside};
use axum::Router;
use axum::extract::Request;
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use http::{HeaderName, HeaderValue, StatusCode, header};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::Mutex;
use tower_http::compression::CompressionLayer;
use tower_http::services::ServeDir;
use tower_http::set_header::SetResponseHeaderLayer;
use tower_livereload::LiveReloadLayer;
pub(crate) const INDEX_FILE: &str = "index.html";
const ASSETS: &str = "/assets/";
const KEEP_FOR_A_YEAR: &str = "public, max-age=31536000, immutable";
pub(crate) fn app(
static_dir: &Path,
spa: bool,
cache_assets: bool,
livereload: Option<LiveReloadLayer>,
no_app_page: bool,
) -> Router {
let mut app = Router::new().fallback_service(ServeDir::new(static_dir));
if spa {
let index = static_dir.join(INDEX_FILE);
let missing = Arc::new(Mutex::new(no_app_page));
app = app.layer(middleware::from_fn(move |request, next| {
serve_app_shell(index.clone(), Arc::clone(&missing), request, next)
}));
}
if let Some(livereload) = livereload {
app = app.layer(livereload);
}
let root = static_dir.to_path_buf();
let mut app = app
.layer(CompressionLayer::new())
.layer(middleware::from_fn(refuse_hidden_files))
.layer(middleware::from_fn(move |request, next| {
refuse_paths_outside(root.clone(), request, next)
}));
if cache_assets {
app = app.layer(middleware::from_fn(keep_hashed_assets));
} else {
app = app
.layer(middleware::from_fn(always_answer_in_full))
.layer(set_header(header::CACHE_CONTROL, "no-store"));
}
app.layer(set_header(header::X_CONTENT_TYPE_OPTIONS, "nosniff"))
.layer(set_header(header::X_FRAME_OPTIONS, "SAMEORIGIN"))
.layer(set_header(
header::REFERRER_POLICY,
"strict-origin-when-cross-origin",
))
}
async fn serve_app_shell(
index: PathBuf,
missing: Arc<Mutex<bool>>,
request: Request,
next: Next,
) -> Response {
let wants_page = request
.headers()
.get(header::ACCEPT)
.and_then(|accept| accept.to_str().ok())
.is_some_and(|accept| accept.contains("text/html"));
let could_be_a_route = !request.uri().path().starts_with(ASSETS);
let response = next.run(request).await;
if response.status() != StatusCode::NOT_FOUND || !wants_page || !could_be_a_route {
let mut missing = missing.lock().await;
if *missing && is_there(&index).await {
*missing = false;
}
return response;
}
let mut missing = missing.lock().await;
match tokio::fs::read(&index).await {
Ok(page) => {
*missing = false;
([(header::CONTENT_TYPE, "text/html; charset=utf-8")], page).into_response()
}
Err(error) => {
if !std::mem::replace(&mut *missing, true) {
let gone = error.kind() == ErrorKind::NotFound;
let reason = if gone { "is gone" } else { "cannot be read" };
eprintln!(" {INDEX_FILE} {reason}, so no page will load");
}
response
}
}
}
async fn always_answer_in_full(mut request: Request, next: Next) -> Response {
let headers = request.headers_mut();
headers.remove(header::IF_MODIFIED_SINCE);
headers.remove(header::IF_NONE_MATCH);
next.run(request).await
}
async fn keep_hashed_assets(request: Request, next: Next) -> Response {
let hashed = request.uri().path().starts_with(ASSETS);
let mut response = next.run(request).await;
let there = response.status().is_success() || response.status() == StatusCode::NOT_MODIFIED;
let keep = hashed && there;
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static(if keep { KEEP_FOR_A_YEAR } else { "no-cache" }),
);
response
}
async fn is_there(index: &Path) -> bool {
let Ok(page) = tokio::fs::File::open(index).await else {
return false;
};
page.metadata().await.is_ok_and(|found| found.is_file())
}
fn set_header(name: HeaderName, value: &'static str) -> SetResponseHeaderLayer<HeaderValue> {
SetResponseHeaderLayer::overriding(name, HeaderValue::from_static(value))
}