Skip to main content

toolblox_lib/
theme.rs

1//! The custom theme, which is custom CSS. It's applied after the theme tokens in `src/theme.css`,
2//! so a theme changes colors and radii by setting those tokens.
3//!
4//! The saved `theme.css` and exported theme files are the same plain CSS. Nothing in a theme may
5//! load from outside this device: it can reference only embedded data URLs, so a shared theme
6//! can't reveal anything to a remote server. The CSS editor can name local files, which are
7//! embedded before the theme is saved.
8
9use base64::Engine;
10use std::path::{Path, PathBuf};
11
12/// Room for images and fonts embedded as data URLs.
13const MAX_CSS_BYTES: usize = 16 * 1024 * 1024;
14/// How deeply local CSS files can import each other.
15const MAX_IMPORT_DEPTH: usize = 8;
16
17/// Embeds the local files that theme CSS names. Each `@import` of a local CSS file is replaced
18/// with that file's contents, and each `url()` naming a local file becomes a data URL. Absolute
19/// paths and `file:` URLs are local, and inside an imported file, relative paths resolve against
20/// its folder. Other URLs are left for `validate` to reject.
21pub fn embed_files(css: &str) -> Result<String, String> {
22    embed(css, None, 0)
23}
24
25fn embed(css: &str, folder: Option<&Path>, depth: usize) -> Result<String, String> {
26    let css = inline_imports(css, folder, depth)?;
27    embed_urls(&css, folder)
28}
29
30/// Replaces each unconditional `@import` of a local CSS file with the file's embedded contents.
31fn inline_imports(css: &str, folder: Option<&Path>, depth: usize) -> Result<String, String> {
32    let lower = css.to_ascii_lowercase();
33    let mut output = String::with_capacity(css.len());
34    let mut rest = css;
35    while let Some(start) = lower[css.len() - rest.len()..].find("@import") {
36        output.push_str(&rest[..start]);
37        let rule = &rest[start + 7..];
38        let target =
39            import_target(rule).and_then(|(value, end)| Some((local_path(value, folder)?, end)));
40        let Some((path, end)) = target else {
41            output.push_str(&rest[start..start + 7]);
42            rest = rule;
43            continue;
44        };
45        let name = path.display();
46        if depth == MAX_IMPORT_DEPTH {
47            return Err(format!(
48                "{name} is imported too many times in a row. Does a file import itself?"
49            ));
50        }
51        let text = String::from_utf8(read_file(&path)?)
52            .map_err(|_| format!("{name} isn't a text file. Is it the right CSS file?"))?;
53        output.push_str(&embed(&text, path.parent(), depth + 1)?);
54        check_size(&output)?;
55        rest = &rule[end..];
56    }
57    output.push_str(rest);
58    Ok(output)
59}
60
61/// The path an `@import` names as a string or `url()`, when only `;` follows it, and the length
62/// of the rule after `@import`.
63fn import_target(rule: &str) -> Option<(&str, usize)> {
64    let trimmed = rule.trim_start();
65    let (value, tail) = if trimmed
66        .get(..4)
67        .is_some_and(|function| function.eq_ignore_ascii_case("url("))
68    {
69        let (_, value, tail) = split_url(&trimmed[4..]);
70        let tail = tail.strip_prefix(['"', '\'']).unwrap_or(tail);
71        (value, tail.trim_start().strip_prefix(')')?)
72    } else {
73        let quote = trimmed.chars().next().filter(|c| *c == '"' || *c == '\'')?;
74        let body = &trimmed[1..];
75        let end = body.find(quote)?;
76        (&body[..end], &body[end + 1..])
77    };
78    let after = tail.trim_start().strip_prefix(';')?;
79    Some((value, rule.len() - after.len()))
80}
81
82/// Replaces each `url()` that names a local file with the file as a data URL.
83fn embed_urls(css: &str, folder: Option<&Path>) -> Result<String, String> {
84    let lower = css.to_ascii_lowercase();
85    let mut output = String::with_capacity(css.len());
86    let mut rest = css;
87    while let Some(start) = lower[css.len() - rest.len()..].find("url(") {
88        let (before, after) = rest.split_at(start + 4);
89        output.push_str(before);
90        let (opening, value, tail) = split_url(after);
91        output.push_str(opening);
92        match local_path(value, folder) {
93            Some(path) => {
94                output.push_str(&data_url(&path)?);
95                check_size(&output)?;
96            }
97            None => output.push_str(value),
98        }
99        rest = tail;
100    }
101    output.push_str(rest);
102    Ok(output)
103}
104
105/// Splits the text after `url(` into the whitespace and opening quote, the value, and the rest,
106/// which starts at the closing quote or parenthesis.
107fn split_url(text: &str) -> (&str, &str, &str) {
108    let start = text.len() - text.trim_start().len();
109    let quote = text[start..]
110        .chars()
111        .next()
112        .filter(|c| *c == '"' || *c == '\'');
113    let start = start + quote.map_or(0, char::len_utf8);
114    let body = &text[start..];
115    let end = match quote {
116        Some(quote) => body.find(quote),
117        None => body.find(|c: char| c == ')' || c.is_whitespace()),
118    }
119    .unwrap_or(body.len());
120    (&text[..start], &body[..end], &body[end..])
121}
122
123/// The local file a value names: an absolute path, a `file:` URL, or a path relative to
124/// `folder`. Network paths and other URLs aren't local.
125fn local_path(value: &str, folder: Option<&Path>) -> Option<PathBuf> {
126    if value.is_empty()
127        || value.starts_with(['#', '?'])
128        || value.starts_with("//")
129        || value.starts_with("\\\\")
130    {
131        return None;
132    }
133    if value
134        .get(..5)
135        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("file:"))
136    {
137        let url = url::Url::parse(value).ok()?;
138        if url.host_str().is_some_and(|host| !host.is_empty()) {
139            return None;
140        }
141        return url.to_file_path().ok();
142    }
143    let path = PathBuf::from(value);
144    if path.is_absolute() {
145        return Some(path);
146    }
147    if url::Url::parse(value).is_ok() {
148        return None;
149    }
150    folder.map(|folder| folder.join(path))
151}
152
153fn check_size(css: &str) -> Result<(), String> {
154    if css.len() > MAX_CSS_BYTES {
155        return Err("The theme is larger than 16 MB. Can its files be smaller?".into());
156    }
157    Ok(())
158}
159
160fn read_file(path: &Path) -> Result<Vec<u8>, String> {
161    let name = path.display();
162    let size = std::fs::metadata(path)
163        .map_err(|_| format!("{name} couldn't be read. Does the file exist?"))?
164        .len();
165    if size > MAX_CSS_BYTES as u64 {
166        return Err(format!("{name} is larger than 16 MB. Can it be smaller?"));
167    }
168    std::fs::read(path).map_err(|_| format!("{name} couldn't be read. Is it readable?"))
169}
170
171/// Reads an image or font file as a data URL, typed by its extension. The file name is kept as a
172/// form-encoded `name` parameter, which browsers ignore, so the CSS editor can show it.
173fn data_url(path: &Path) -> Result<String, String> {
174    let extension = path
175        .extension()
176        .and_then(|extension| extension.to_str())
177        .unwrap_or_default()
178        .to_ascii_lowercase();
179    let mime = match extension.as_str() {
180        "png" => "image/png",
181        "jpg" | "jpeg" => "image/jpeg",
182        "gif" => "image/gif",
183        "webp" => "image/webp",
184        "avif" => "image/avif",
185        "svg" => "image/svg+xml",
186        "bmp" => "image/bmp",
187        "ico" | "cur" => "image/x-icon",
188        "woff" => "font/woff",
189        "woff2" => "font/woff2",
190        "ttf" => "font/ttf",
191        "otf" => "font/otf",
192        _ => {
193            return Err(format!(
194                "{} isn't an image or font file. Can it be converted?",
195                path.display()
196            ));
197        }
198    };
199    let data = base64::engine::general_purpose::STANDARD.encode(read_file(path)?);
200    let name: String = path
201        .file_name()
202        .map(|name| url::form_urlencoded::byte_serialize(name.as_encoded_bytes()).collect())
203        .unwrap_or_default();
204    Ok(format!("data:{mime};name={name};base64,{data}"))
205}
206
207/// Checks that theme CSS is within the size limit and loads nothing from outside this device.
208pub fn validate(css: &str) -> Result<(), String> {
209    if css.len() > MAX_CSS_BYTES {
210        return Err("The theme is larger than 16 MB. Can its images be smaller?".into());
211    }
212    if !css_is_local(css) {
213        return Err(
214            "The theme loads something from outside this device. Can it use local files or data URLs instead?"
215                .into(),
216        );
217    }
218    Ok(())
219}
220
221/// True when the CSS can't load anything except embedded data URLs. `url(#id)` refers to an
222/// element in the same document.
223///
224/// Escapes are decoded and comments removed first, the way the CSS tokenizer reads them, so
225/// `u\72l(` and `ur/**/l(` can't hide a URL. Text inside strings is kept, which can only make
226/// the check stricter.
227pub fn css_is_local(css: &str) -> bool {
228    let text = normalize_css(css);
229    if ["@import", "image-set(", "src("]
230        .iter()
231        .any(|pattern| text.contains(pattern))
232    {
233        return false;
234    }
235    text.match_indices("url(").all(|(index, _)| {
236        let value = text[index + 4..]
237            .trim_start_matches(|c: char| c.is_whitespace() || c == '"' || c == '\'');
238        value.starts_with("data:") || value.starts_with('#')
239    })
240}
241
242/// Lowercases CSS, decodes escapes, and drops comments outside strings.
243fn normalize_css(css: &str) -> String {
244    let mut output = String::with_capacity(css.len());
245    let mut chars = css.chars().peekable();
246    let mut quote: Option<char> = None;
247    while let Some(c) = chars.next() {
248        match c {
249            '\\' => {
250                let mut hex = String::new();
251                while hex.len() < 6 && chars.peek().is_some_and(char::is_ascii_hexdigit) {
252                    hex.extend(chars.next());
253                }
254                if hex.is_empty() {
255                    output.extend(chars.next().map(|c| c.to_ascii_lowercase()));
256                } else {
257                    if chars.peek().is_some_and(|c| c.is_whitespace()) {
258                        chars.next();
259                    }
260                    let decoded = u32::from_str_radix(&hex, 16)
261                        .ok()
262                        .and_then(char::from_u32)
263                        .unwrap_or('\u{fffd}');
264                    output.push(decoded.to_ascii_lowercase());
265                }
266            }
267            '/' if quote.is_none() && chars.peek() == Some(&'*') => {
268                chars.next();
269                let mut previous = '\0';
270                for c in chars.by_ref() {
271                    if previous == '*' && c == '/' {
272                        break;
273                    }
274                    previous = c;
275                }
276            }
277            '"' | '\'' if quote.is_none() => {
278                quote = Some(c);
279                output.push(c);
280            }
281            '\n' if quote.is_some() => {
282                quote = None;
283                output.push(c);
284            }
285            _ if quote == Some(c) => {
286                quote = None;
287                output.push(c);
288            }
289            _ => output.push(c.to_ascii_lowercase()),
290        }
291    }
292    output
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    const PIXEL: &str = "data:image/png;base64,iVBORw0KGgo=";
300
301    #[test]
302    fn local_css_is_allowed() {
303        assert!(css_is_local(""));
304        assert!(css_is_local(":root { --radius: 12px; }"));
305        assert!(css_is_local(&format!(
306            "main {{ background: url({PIXEL}); }} a {{ background: URL( '{PIXEL}' ) }}"
307        )));
308        assert!(css_is_local("[data-page=\"dashboard\"] { color: red }"));
309        assert!(css_is_local("a { mask: url('#shape') }"));
310    }
311
312    #[test]
313    fn css_that_loads_remote_content_is_rejected() {
314        for css in [
315            "a { background: url(https://example.com/a.png) }",
316            "a { background: url( \"//example.com/a.png\" ) }",
317            "a { background: url(a.png) }",
318            "@import 'https://example.com/a.css';",
319            "@IMPORT url(a.css);",
320            "a { background: image-set('https://example.com/a.png' 1x) }",
321            "a { background: -webkit-image-set('a.png' 1x) }",
322            "a { background: src('https://example.com/a.png') }",
323            "a { background: u\\72l(https://example.com/a.png) }",
324            "a { background: u\\000072 l(https://example.com/a.png) }",
325            "a { background: \\75 rl(https://example.com/a.png) }",
326            "a { background: ur\\l(https://example.com/a.png) }",
327            "@imp/**/ort 'a.css';",
328            "a { content: '/*' } b { background: url(https://example.com) } c { content: '*/' }",
329            "a { background: url(data:image/png;base64,AA), url(https://example.com) }",
330        ] {
331            assert!(!css_is_local(css), "{css}");
332        }
333    }
334
335    #[test]
336    fn css_is_validated() {
337        assert!(validate(&format!("main {{ background: url({PIXEL}) }}")).is_ok());
338        assert!(validate("a { background: url(https://example.com) }").is_err());
339        let large = format!(
340            "main {{ background: url(data:image/png;base64,{}) }}",
341            "A".repeat(MAX_CSS_BYTES)
342        );
343        assert!(validate(&large).is_err());
344    }
345
346    fn temp_folder() -> PathBuf {
347        let folder = std::env::temp_dir().join(format!(
348            "toolblox-theme-{}-{}",
349            std::process::id(),
350            uuid::Uuid::new_v4()
351        ));
352        std::fs::create_dir_all(&folder).unwrap();
353        folder
354    }
355
356    fn data(mime: &str, name: &str, bytes: &[u8]) -> String {
357        let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
358        format!("data:{mime};name={name};base64,{encoded}")
359    }
360
361    #[test]
362    fn local_files_are_embedded() {
363        let folder = temp_folder();
364        let image = folder.join("bg%&1.png");
365        std::fs::write(&image, b"png").unwrap();
366        let font = folder.join("Face.WOFF2");
367        std::fs::write(&font, b"font").unwrap();
368        let png = data("image/png", "bg%25%261.png", b"png");
369        let woff2 = data("font/woff2", "Face.WOFF2", b"font");
370        let file_url = url::Url::from_file_path(&image).unwrap();
371        let (image, font) = (image.display(), font.display());
372        let css = format!(
373            "a {{ background: url(\"{image}\") }} b {{ background: URL( '{file_url}' ) }} c {{ background: url({image}) }} d {{ background: url({PIXEL}) }} @font-face {{ src: url(\"{font}\") }}"
374        );
375        let embedded = embed_files(&css).unwrap();
376        assert_eq!(
377            embedded,
378            format!(
379                "a {{ background: url(\"{png}\") }} b {{ background: URL( '{png}' ) }} c {{ background: url({png}) }} d {{ background: url({PIXEL}) }} @font-face {{ src: url(\"{woff2}\") }}"
380            )
381        );
382        assert!(validate(&embedded).is_ok());
383    }
384
385    #[test]
386    fn local_css_files_are_inlined() {
387        let folder = temp_folder();
388        std::fs::create_dir_all(folder.join("parts")).unwrap();
389        std::fs::write(folder.join("parts/bg.svg"), b"<svg/>").unwrap();
390        std::fs::write(
391            folder.join("parts/colors.css"),
392            ":root { --primary: red; }\nmain { background: url(bg.svg) }",
393        )
394        .unwrap();
395        std::fs::write(
396            folder.join("theme.css"),
397            "@import \"parts/colors.css\";\na { mask: url('#shape') }",
398        )
399        .unwrap();
400        let svg = data("image/svg+xml", "bg.svg", b"<svg/>");
401        let theme = folder.join("theme.css");
402        for css in [
403            format!("@import \"{}\";", theme.display()),
404            format!("@IMPORT url( '{}' ) ;", theme.display()),
405            format!(
406                "@import url({});",
407                url::Url::from_file_path(&theme).unwrap()
408            ),
409        ] {
410            let embedded = embed_files(&format!("{css}\nb {{ color: blue }}")).unwrap();
411            assert_eq!(
412                embedded,
413                format!(
414                    ":root {{ --primary: red; }}\nmain {{ background: url({svg}) }}\na {{ mask: url('#shape') }}\nb {{ color: blue }}"
415                )
416            );
417            assert!(validate(&embedded).is_ok());
418        }
419    }
420
421    #[test]
422    fn conditional_and_remote_imports_are_left_for_validation() {
423        let folder = temp_folder();
424        let theme = folder.join("theme.css");
425        std::fs::write(&theme, "a { color: red }").unwrap();
426        for css in [
427            format!("@import \"{}\" screen;", theme.display()),
428            "@import 'https://example.com/a.css';".to_string(),
429            "@import 'a.css';".to_string(),
430            "@import".to_string(),
431        ] {
432            assert_eq!(embed_files(&css).unwrap(), css);
433            assert!(validate(&css).is_err());
434        }
435    }
436
437    #[test]
438    fn a_file_that_imports_itself_is_rejected() {
439        let folder = temp_folder();
440        std::fs::write(folder.join("loop.css"), "@import 'loop.css';").unwrap();
441        let css = format!("@import '{}';", folder.join("loop.css").display());
442        assert!(embed_files(&css).unwrap_err().contains("import itself"));
443    }
444
445    #[test]
446    fn remote_and_network_urls_are_not_embedded() {
447        for css in [
448            "a { background: url(https://example.com/a.png) }",
449            "a { background: url(//example.com/a.png) }",
450            "a { background: url('\\\\server\\share\\a.png') }",
451            "a { background: url(file://server/share/a.png) }",
452            "a { background: url(a.png) }",
453            "a { background: url(",
454        ] {
455            assert_eq!(embed_files(css).unwrap(), css);
456        }
457    }
458
459    #[test]
460    fn unsupported_and_missing_files_are_rejected() {
461        let folder = temp_folder();
462        let notes = folder.join("notes.txt");
463        std::fs::write(&notes, b"secret").unwrap();
464        let css = format!("a {{ background: url(\"{}\") }}", notes.display());
465        assert!(
466            embed_files(&css)
467                .unwrap_err()
468                .contains("isn't an image or font")
469        );
470        let css = format!(
471            "a {{ background: url(\"{}\") }}",
472            folder.join("missing.png").display()
473        );
474        assert!(
475            embed_files(&css)
476                .unwrap_err()
477                .contains("Does the file exist?")
478        );
479    }
480}