Skip to main content

serenade_view/
asset.rs

1//! Asset URL helper.
2
3use crate::ViewError;
4
5/// Base path for application assets (default `/assets`).
6#[derive(Clone, Debug, Eq, PartialEq)]
7pub struct AssetConfig {
8    base: String,
9}
10
11impl Default for AssetConfig {
12    fn default() -> Self {
13        Self {
14            base: "/assets".to_owned(),
15        }
16    }
17}
18
19impl AssetConfig {
20    /// Configures the asset URL prefix (for example `/static` or `/assets`).
21    #[must_use]
22    pub fn with_base(base: impl Into<String>) -> Self {
23        Self { base: base.into() }
24    }
25
26    /// Joins `relative` under the configured base.
27    ///
28    /// Rejects `..`, scheme-like segments (`:`), and empty traversal abuse.
29    /// An optional `?query` suffix is preserved for cache-busting.
30    ///
31    /// # Errors
32    ///
33    /// Returns [`ViewError`] when `relative` is unsafe.
34    pub fn join(&self, relative: &str) -> Result<String, ViewError> {
35        let trimmed = relative.trim().trim_start_matches('/');
36        if trimmed.is_empty() {
37            return Ok(normalize_base(&self.base));
38        }
39        let (file_part, query) = match trimmed.split_once('?') {
40            Some((file, q)) => (file, Some(q)),
41            None => (trimmed, None),
42        };
43        if file_part.is_empty() || file_part.contains("..") || file_part.contains(':') {
44            return Err(ViewError::msg(format!("unsafe asset path `{relative}`")));
45        }
46        for part in file_part.split('/') {
47            if part.is_empty() || part == "." {
48                return Err(ViewError::msg(format!("unsafe asset path `{relative}`")));
49            }
50        }
51        let base = normalize_base(&self.base);
52        let joined = format!("{base}/{file_part}");
53        Ok(match query {
54            Some(q) => format!("{joined}?{q}"),
55            None => joined,
56        })
57    }
58}
59
60/// Builds an asset URL under the default `/assets` base.
61///
62/// # Errors
63///
64/// Returns [`ViewError`] when `relative` is unsafe.
65pub fn asset(relative: &str) -> Result<String, ViewError> {
66    AssetConfig::default().join(relative)
67}
68
69fn normalize_base(base: &str) -> String {
70    let trimmed = base.trim().trim_end_matches('/');
71    if trimmed.is_empty() {
72        return String::new();
73    }
74    if trimmed.starts_with('/') {
75        trimmed.to_owned()
76    } else {
77        format!("/{trimmed}")
78    }
79}