use std::borrow::Cow;
use axum::body::Body;
use axum::http::{HeaderValue, StatusCode, Uri, header};
use axum::response::{Html, IntoResponse, Response};
use rust_embed::RustEmbed;
use crate::{AppIdentity, security};
#[must_use]
pub fn embed_marker(app: &AppIdentity) -> String {
format!("<script>window.{}=true</script>", app.embedded_global)
}
fn missing_spa_html(app: &AppIdentity) -> String {
format!(
"<!doctype html><html><head><meta charset=\"utf-8\">\
<title>{name}</title></head><body><h1>{name} SPA not built</h1>\
<p>Run <code>bun run build</code> in <code>web/</code>, then rebuild.</p></body></html>",
name = app.name
)
}
#[must_use]
pub fn injected_index<E: RustEmbed>(app: &AppIdentity) -> String {
let marker = embed_marker(app);
let marker = marker.as_str();
let raw = match E::get("index.html") {
Some(file) => String::from_utf8_lossy(&file.data).into_owned(),
None => return missing_spa_html(app),
};
match raw.find("<head>") {
Some(head) => {
let at = head + "<head>".len();
let mut out = String::with_capacity(raw.len() + marker.len());
out.push_str(&raw[..at]);
out.push_str(marker);
out.push_str(&raw[at..]);
out
}
None => format!("{marker}{raw}"),
}
}
fn shell_response<E: RustEmbed>(app: &AppIdentity) -> Response {
let html = injected_index::<E>(app);
let csp = security::shell_csp(app, &html);
let mut response = Html(html).into_response();
let headers = response.headers_mut();
headers.insert(header::CONTENT_SECURITY_POLICY, csp);
headers.insert(header::CACHE_CONTROL, security::no_store());
response
}
fn asset_response(path: &str, data: Cow<'static, [u8]>) -> Response {
let mime = mime_guess::from_path(path).first_or_octet_stream();
let mut response = Body::from(data.into_owned()).into_response();
if let Ok(value) = HeaderValue::from_str(mime.as_ref()) {
response.headers_mut().insert(header::CONTENT_TYPE, value);
}
if path.starts_with("_app/immutable/") {
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
);
}
response
}
#[must_use]
pub fn respond<E: RustEmbed>(app: &AppIdentity, uri: &Uri) -> Response {
let path = uri.path().trim_start_matches('/');
if path.is_empty() || path == "index.html" {
return shell_response::<E>(app);
}
if path.starts_with("api/") {
return StatusCode::NOT_FOUND.into_response();
}
match E::get(path) {
Some(file) => asset_response(path, file.data),
None => shell_response::<E>(app),
}
}
pub fn fallback<E: RustEmbed>(
app: &'static AppIdentity,
) -> impl Fn(Uri) -> std::future::Ready<Response> + Clone + Send + Sync + 'static {
move |uri: Uri| std::future::ready(respond::<E>(app, &uri))
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(RustEmbed)]
#[folder = "$CARGO_MANIFEST_DIR/testdata/spa"]
struct TestSpa;
const APP: AppIdentity = AppIdentity {
name: "Ledgeline",
bundle_id: "com.zmre.ledgeline",
log_prefix: "ledgeline",
token_env: "LEDGELINE_TOKEN",
token_global: "__LEDGELINE_TOKEN__",
embedded_global: "__LEDGELINE_EMBEDDED__",
spa_base: "/",
spa_frame_src: None,
};
#[test]
fn the_marker_is_byte_for_byte_ledgelines() {
assert_eq!(
embed_marker(&APP),
"<script>window.__LEDGELINE_EMBEDDED__=true</script>"
);
}
#[test]
fn the_marker_goes_right_after_head() {
let html = injected_index::<TestSpa>(&APP);
assert!(
html.contains(&format!("<head>{}", embed_marker(&APP))),
"{html}"
);
}
#[test]
fn the_shell_carries_the_marker_and_no_token() {
let html = injected_index::<TestSpa>(&APP);
assert!(html.contains(&embed_marker(&APP)));
assert!(!html.contains("__LEDGELINE_TOKEN__"));
}
#[test]
fn shell_csp_hashes_the_injected_marker_script() {
let html = injected_index::<TestSpa>(&APP);
let csp = security::shell_csp(&APP, &html);
let csp = csp.to_str().expect("ascii policy");
for script in inline_scripts(&html) {
let hash = security::csp_sha256(script);
assert!(
csp.contains(&hash),
"CSP is missing the hash for an inline script it serves: {script:?}"
);
}
assert!(csp.contains("connect-src 'self'"));
}
#[test]
fn the_shell_is_never_stored() {
assert_eq!(
shell_response::<TestSpa>(&APP)
.headers()
.get(header::CACHE_CONTROL)
.and_then(|value| value.to_str().ok()),
Some("no-store")
);
}
#[test]
fn immutable_assets_keep_their_long_cache() {
let response = asset_response("_app/immutable/chunks/x.js", Cow::Borrowed(b"//"));
assert_eq!(
response
.headers()
.get(header::CACHE_CONTROL)
.and_then(|value| value.to_str().ok()),
Some("public, max-age=31536000, immutable")
);
}
fn inline_scripts(html: &str) -> Vec<&str> {
html.split("<script")
.skip(1)
.filter_map(|chunk| chunk.split_once('>'))
.filter(|(open, _)| !open.contains("src="))
.filter_map(|(_, rest)| rest.split_once("</script>"))
.map(|(body, _)| body)
.collect()
}
}