use include_dir::{Dir, File, include_dir};
static APP_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/assets/tui-web-dist");
const API_BASE_TOKEN: &str = "%%APALIS_RTUI_API_BASE%%";
const DEFAULT_API_BASE: &str = "/api/v1";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CspPolicy(String);
impl Default for CspPolicy {
fn default() -> Self {
Self(
"default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; \
connect-src 'self'; style-src 'self' 'unsafe-inline'"
.to_owned(),
)
}
}
impl CspPolicy {
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug)]
pub struct ServeUI {
api_base: String,
csp: Option<CspPolicy>,
}
impl Default for ServeUI {
#[allow(clippy::use_self)]
fn default() -> ServeUI {
Self::new()
}
}
impl ServeUI {
#[must_use]
pub fn new() -> Self {
Self {
api_base: DEFAULT_API_BASE.to_owned(),
csp: None,
}
}
#[must_use]
pub fn with_api_base(mut self, base: impl Into<String>) -> Self {
self.api_base = base.into();
self
}
#[must_use]
pub fn csp(mut self, policy: CspPolicy) -> Self {
self.csp = Some(policy);
self
}
#[must_use]
pub fn get_file(path: &str) -> Option<&File<'static>> {
let normalized = path.trim_start_matches('/');
APP_DIST.get_file(normalized).or_else(|| {
if normalized.is_empty() || !normalized.contains('.') {
APP_DIST.get_file("index.html")
} else {
None
}
})
}
#[must_use]
pub fn content_type(path: &str) -> &'static str {
if path.ends_with(".html") {
"text/html; charset=utf-8"
} else if path.ends_with(".js") {
"application/javascript"
} else if path.ends_with(".css") {
"text/css"
} else if path.ends_with(".wasm") {
"application/wasm"
} else {
"application/octet-stream"
}
}
#[must_use]
pub fn cache_control(path: &str) -> Option<&'static str> {
if path.ends_with(".html") {
Some("no-cache")
} else if path.ends_with(".js") || path.ends_with(".css") || path.ends_with(".wasm") {
Some("public, max-age=31536000, immutable")
} else {
None
}
}
#[must_use]
pub(crate) fn render(&self, path: &str) -> Option<Rendered> {
let file = Self::get_file(path).or_else(|| Self::get_file("index.html"))?;
let path_str = file.path().to_str().unwrap_or("");
let content_type = Self::content_type(path_str);
let cache_control = Self::cache_control(path_str);
let body = if path_str == "index.html" {
String::from_utf8_lossy(file.contents())
.replace(API_BASE_TOKEN, &self.api_base)
.into_bytes()
} else {
file.contents().to_vec()
};
Some(Rendered {
content_type,
cache_control,
body,
})
}
#[must_use]
pub(crate) fn csp_header(&self) -> Option<&str> {
self.csp.as_ref().map(CspPolicy::as_str)
}
}
pub(crate) struct Rendered {
pub(crate) content_type: &'static str,
pub(crate) cache_control: Option<&'static str>,
pub(crate) body: Vec<u8>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_api_base_is_api_v1() {
assert_eq!(ServeUI::new().api_base, "/api/v1");
assert_eq!(ServeUI::default().api_base, "/api/v1");
}
#[test]
fn with_api_base_overrides_default() {
let ui = ServeUI::new().with_api_base("/custom/v2");
assert_eq!(ui.api_base, "/custom/v2");
}
#[test]
fn index_html_gets_api_base_substituted() {
let ui = ServeUI::new().with_api_base("/custom/v2");
let rendered = ui.render("/index.html").expect("index.html is embedded");
let body = String::from_utf8(rendered.body).expect("index.html is UTF-8");
assert!(body.contains("data-api-base=\"/custom/v2\""));
assert!(!body.contains(API_BASE_TOKEN));
}
#[test]
fn unmatched_path_falls_back_to_index_html() {
let ui = ServeUI::new();
let rendered = ui
.render("/tasks/01K7EXAMPLE")
.expect("falls back to index.html");
let body = String::from_utf8(rendered.body).expect("index.html is UTF-8");
assert!(body.contains("<html"));
assert_eq!(rendered.content_type, "text/html; charset=utf-8");
}
#[test]
fn non_html_asset_is_served_as_opaque_bytes() {
assert_eq!(
ServeUI::content_type("pkg/app.js"),
"application/javascript"
);
assert_eq!(ServeUI::content_type("pkg/app.css"), "text/css");
assert_eq!(ServeUI::content_type("pkg/app_bg.wasm"), "application/wasm");
assert_eq!(
ServeUI::content_type("pkg/app.unknown"),
"application/octet-stream"
);
}
#[test]
fn cache_control_by_extension() {
assert_eq!(ServeUI::cache_control("index.html"), Some("no-cache"));
assert_eq!(
ServeUI::cache_control("pkg/app.js"),
Some("public, max-age=31536000, immutable")
);
assert_eq!(
ServeUI::cache_control("pkg/app.wasm"),
Some("public, max-age=31536000, immutable")
);
assert_eq!(ServeUI::cache_control("robots.txt"), None);
}
#[test]
fn no_csp_header_by_default() {
let ui = ServeUI::new();
assert_eq!(ui.csp_header(), None);
}
#[test]
fn csp_builder_sets_the_header() {
let ui = ServeUI::new().csp(CspPolicy::default());
assert_eq!(
ui.csp_header(),
Some(
"default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; \
connect-src 'self'; style-src 'self' 'unsafe-inline'"
)
);
}
#[test]
fn custom_csp_policy_is_used_verbatim() {
let ui = ServeUI::new().csp(CspPolicy::new("default-src 'none'"));
assert_eq!(ui.csp_header(), Some("default-src 'none'"));
}
#[test]
fn extensionless_path_resolves_get_file_to_index_html() {
let file = ServeUI::get_file("/tasks").expect("extensionless path falls back");
assert_eq!(file.path().to_str(), Some("index.html"));
}
#[test]
fn path_with_unknown_extension_has_no_get_file_match() {
assert!(ServeUI::get_file("/missing.js").is_none());
}
}