Skip to main content

yaiko_core/
script.rs

1//! Safe script loading strategy metadata.
2use std::collections::BTreeMap;
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum ScriptStrategy {
5    Defer,
6    Lazy,
7    Worker,
8}
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum ScriptError {
11    InvalidSource,
12    InvalidIntegrity,
13}
14#[derive(Debug, Clone, Default)]
15pub struct ScriptRegistry {
16    scripts: BTreeMap<String, (ScriptStrategy, Option<String>)>,
17}
18impl ScriptRegistry {
19    pub fn new() -> Self {
20        Self::default()
21    }
22    pub fn add(
23        mut self,
24        src: impl Into<String>,
25        strategy: ScriptStrategy,
26        integrity: Option<String>,
27    ) -> Result<Self, ScriptError> {
28        let src = source(src.into())?;
29        if let Some(i) = &integrity {
30            if i.len() < 16 || i.chars().any(|c| c.is_control() || c.is_whitespace()) {
31                return Err(ScriptError::InvalidIntegrity);
32            }
33        }
34        self.scripts.insert(src, (strategy, integrity));
35        Ok(self)
36    }
37    pub fn render(&self) -> String {
38        let mut o = String::new();
39        for (src, (strategy, integrity)) in &self.scripts {
40            let mode = match strategy {
41                ScriptStrategy::Defer => " defer",
42                ScriptStrategy::Lazy => " data-loading=\"lazy\"",
43                ScriptStrategy::Worker => " type=\"text/worker\"",
44            };
45            let hash = integrity
46                .as_ref()
47                .map(|i| format!(" integrity=\"{}\" crossorigin=\"anonymous\"", esc(i)))
48                .unwrap_or_default();
49            o.push_str(&format!(
50                "<script src=\"{}\"{}{}></script>",
51                esc(src),
52                mode,
53                hash
54            ))
55        }
56        o
57    }
58}
59fn source(x: String) -> Result<String, ScriptError> {
60    if x.is_empty()
61        || x.chars().any(|c| c.is_control() || c.is_whitespace())
62        || (!x.starts_with('/') && !x.starts_with("https://"))
63    {
64        Err(ScriptError::InvalidSource)
65    } else {
66        Ok(x)
67    }
68}
69fn esc(x: &str) -> String {
70    x.replace('&', "&amp;")
71        .replace('"', "&quot;")
72        .replace('<', "&lt;")
73}
74#[cfg(test)]
75mod tests {
76    use super::*;
77    #[test]
78    fn renders_strategies_and_deduplicates() {
79        let r = ScriptRegistry::new()
80            .add("/app.js", ScriptStrategy::Defer, None)
81            .unwrap()
82            .add("/lazy.js", ScriptStrategy::Lazy, None)
83            .unwrap()
84            .add(
85                "https://cdn.example/x.js",
86                ScriptStrategy::Worker,
87                Some("sha256-abcdef0123456789".into()),
88            )
89            .unwrap();
90        let o = r.render();
91        assert!(o.contains(" defer"));
92        assert!(o.contains("data-loading=\"lazy\""));
93        assert!(o.contains("text/worker"));
94        assert!(o.contains("integrity"))
95    }
96    #[test]
97    fn rejects_unsafe_sources_and_integrity() {
98        assert!(matches!(
99            ScriptRegistry::new().add("javascript:bad", ScriptStrategy::Defer, None),
100            Err(ScriptError::InvalidSource)
101        ));
102        assert!(matches!(
103            ScriptRegistry::new().add("/x.js", ScriptStrategy::Defer, Some("bad".into())),
104            Err(ScriptError::InvalidIntegrity)
105        ));
106    }
107}