favicons 1.1.0

Privacy-first favicon and logo API: any site's icon as a clean, sandboxed SVG with light and dark theme colours
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::sync::{Arc, LazyLock};

use axum::body::Body;
use axum::response::Response;
use base64::Engine;
use bytes::Bytes;
use http::header::{
    CACHE_CONTROL, CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, HOST, IF_NONE_MATCH,
};
use http::{HeaderMap, HeaderName, HeaderValue, StatusCode, Uri};

use crate::config::Config;

const ROBOTS: &str = include_str!("../site/robots.txt");
const LLMS: &str = include_str!("../site/llms.txt");

#[cfg(feature = "site")]
mod page {
    pub const INDEX: &str = include_str!("../site/index.html");
    pub const SITEMAP: &str = include_str!("../site/sitemap.xml");
    pub const FAVICON: &[u8] = include_bytes!("../site/favicon.svg");
    pub const APPLE_TOUCH_ICON: &[u8] = include_bytes!("../site/apple-touch-icon.png");
    pub const OG_IMAGE: &[u8] = include_bytes!("../site/og.png");
    pub const FONT_DISPLAY: &[u8] = include_bytes!("../site/fonts/archivo.woff2");
    pub const FONT_MONO: &[u8] = include_bytes!("../site/fonts/martian-mono.woff2");
    pub const CONFIG_EXAMPLE: &[u8] = include_bytes!("../config.example.toml");
}

#[cfg(not(feature = "site"))]
mod page {
    pub const INDEX: &str = "";
    pub const SITEMAP: &str = "";
    pub const FAVICON: &[u8] = &[];
    pub const APPLE_TOUCH_ICON: &[u8] = &[];
    pub const OG_IMAGE: &[u8] = &[];
    pub const FONT_DISPLAY: &[u8] = &[];
    pub const FONT_MONO: &[u8] = &[];
    pub const CONFIG_EXAMPLE: &[u8] = &[];
}

pub const ENABLED: bool = cfg!(feature = "site");

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Asset {
    Index,
    Robots,
    Sitemap,
    Llms,
    OpenApi,
    Favicon,
    AppleTouchIcon,
    OgImage,
    FontDisplay,
    FontMono,
    ConfigExample,
}

impl Asset {
    const TEMPLATED: [Asset; 5] = [
        Asset::Index,
        Asset::Robots,
        Asset::Sitemap,
        Asset::Llms,
        Asset::OpenApi,
    ];

    fn template(self) -> Option<&'static str> {
        match self {
            Asset::Index => Some(page::INDEX),
            Asset::Robots => Some(ROBOTS),
            Asset::Sitemap => Some(page::SITEMAP),
            Asset::Llms => Some(LLMS),
            _ => None,
        }
    }

    fn content_type(self) -> &'static str {
        match self {
            Asset::Index => "text/html; charset=utf-8",
            Asset::Robots | Asset::Llms | Asset::ConfigExample => "text/plain; charset=utf-8",
            Asset::Sitemap => "application/xml; charset=utf-8",
            Asset::OpenApi => "application/json",
            Asset::Favicon => "image/svg+xml",
            Asset::AppleTouchIcon | Asset::OgImage => "image/png",
            Asset::FontDisplay | Asset::FontMono => "font/woff2",
        }
    }

    fn cache_control(self) -> &'static str {
        match self {
            Asset::Index => "public, max-age=300, stale-while-revalidate=86400",
            Asset::Robots
            | Asset::Sitemap
            | Asset::Llms
            | Asset::OpenApi
            | Asset::ConfigExample => "public, max-age=3600, stale-while-revalidate=86400",
            Asset::Favicon | Asset::AppleTouchIcon | Asset::OgImage => {
                "public, max-age=86400, stale-while-revalidate=604800"
            }
            Asset::FontDisplay | Asset::FontMono => "public, max-age=31536000, immutable",
        }
    }

    fn indexable(self) -> bool {
        matches!(
            self,
            Asset::Index | Asset::Favicon | Asset::AppleTouchIcon | Asset::OgImage
        )
    }
}

pub struct Page {
    body: Bytes,
    asset: Asset,
    etag: HeaderValue,
    csp: Option<HeaderValue>,
}

impl Page {
    fn new(asset: Asset, body: Bytes) -> Self {
        let csp = match asset {
            Asset::Index => Some(index_csp(std::str::from_utf8(&body).unwrap_or_default())),
            Asset::Favicon => Some(HeaderValue::from_static(
                "default-src 'none'; style-src 'unsafe-inline'",
            )),
            _ => None,
        };
        Self {
            etag: etag(&body),
            body,
            asset,
            csp,
        }
    }

    fn rendered(asset: Asset, origin: &str, catalogs: &[String]) -> Self {
        if asset == Asset::OpenApi {
            let spec = crate::openapi::Spec {
                origin,
                catalogs,
                site: ENABLED,
            };
            return Page::new(asset, Bytes::from(spec.render()));
        }
        let template = asset.template().unwrap_or_default();
        Page::new(asset, Bytes::from(render(template, origin)))
    }
}

fn binary(asset: Asset) -> Option<&'static Page> {
    static FAVICON: LazyLock<Page> =
        LazyLock::new(|| Page::new(Asset::Favicon, Bytes::from_static(page::FAVICON)));
    static APPLE: LazyLock<Page> = LazyLock::new(|| {
        Page::new(
            Asset::AppleTouchIcon,
            Bytes::from_static(page::APPLE_TOUCH_ICON),
        )
    });
    static OG: LazyLock<Page> =
        LazyLock::new(|| Page::new(Asset::OgImage, Bytes::from_static(page::OG_IMAGE)));
    static DISPLAY: LazyLock<Page> =
        LazyLock::new(|| Page::new(Asset::FontDisplay, Bytes::from_static(page::FONT_DISPLAY)));
    static MONO: LazyLock<Page> =
        LazyLock::new(|| Page::new(Asset::FontMono, Bytes::from_static(page::FONT_MONO)));
    static CONFIG: LazyLock<Page> = LazyLock::new(|| {
        Page::new(
            Asset::ConfigExample,
            Bytes::from_static(page::CONFIG_EXAMPLE),
        )
    });
    match asset {
        Asset::ConfigExample => Some(&CONFIG),
        Asset::Favicon => Some(&FAVICON),
        Asset::AppleTouchIcon => Some(&APPLE),
        Asset::OgImage => Some(&OG),
        Asset::FontDisplay => Some(&DISPLAY),
        Asset::FontMono => Some(&MONO),
        _ => None,
    }
}

pub struct Site {
    fixed: Option<Vec<Arc<Page>>>,
    catalogs: Vec<String>,
}

impl Site {
    pub fn new(cfg: &Config) -> Self {
        let catalogs: Vec<String> = cfg.catalogs.iter().map(|c| c.id.clone()).collect();
        let fixed = public_origin(cfg).map(|origin| {
            Asset::TEMPLATED
                .iter()
                .map(|a| Arc::new(Page::rendered(*a, &origin, &catalogs)))
                .collect()
        });
        Self { fixed, catalogs }
    }

    pub fn serve(&self, asset: Asset, headers: &HeaderMap, uri: &Uri) -> Response {
        if let Some(page) = binary(asset) {
            return respond(page, headers);
        }
        if let Some(page) = self
            .fixed
            .as_ref()
            .and_then(|pages| pages.iter().find(|p| p.asset == asset))
        {
            return respond(page, headers);
        }
        respond(
            &Page::rendered(asset, &origin_from_request(headers, uri), &self.catalogs),
            headers,
        )
    }
}

pub fn public_origin(cfg: &Config) -> Option<String> {
    if let Some(url) = &cfg.server.public_url {
        return Some(url.trim_end_matches('/').to_string());
    }
    if cfg.tls.enabled {
        return cfg.tls.domains.first().map(|d| format!("https://{d}"));
    }
    None
}

fn origin_from_request(headers: &HeaderMap, uri: &Uri) -> String {
    let host = uri
        .authority()
        .map(|a| a.as_str().to_string())
        .or_else(|| {
            headers
                .get(HOST)
                .and_then(|v| v.to_str().ok())
                .map(str::to_string)
        })
        .map(|h| h.to_ascii_lowercase())
        .filter(|h| is_safe_host(h))
        .unwrap_or_else(|| "localhost".into());
    let local = host.starts_with("localhost")
        || host.starts_with("127.")
        || host.starts_with("[::1]")
        || host.starts_with('[');
    let scheme = if local { "http" } else { "https" };
    format!("{scheme}://{host}")
}

fn is_safe_host(host: &str) -> bool {
    !host.is_empty()
        && host.len() <= 255
        && host
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b':' | b'[' | b']'))
}

const LIVE_OG: &str = "https://stats.favicons.page/og.png";

fn render(template: &str, origin: &str) -> String {
    let host = origin.split_once("://").map(|(_, h)| h).unwrap_or(origin);
    let og = if host == "favicons.page" {
        LIVE_OG.to_string()
    } else {
        format!("{origin}/og.png")
    };
    template
        .replace("{{og_image}}", &og)
        .replace("{{origin}}", origin)
        .replace("{{host}}", host)
}

fn etag(body: &[u8]) -> HeaderValue {
    let hash = blake3::hash(body).to_hex();
    HeaderValue::from_str(&format!("\"{}\"", &hash[..20])).expect("hex etag")
}

fn index_csp(html: &str) -> HeaderValue {
    let script = inline_script(html).unwrap_or_default();
    let digest = ring::digest::digest(&ring::digest::SHA256, script.as_bytes());
    let hash = base64::engine::general_purpose::STANDARD.encode(digest.as_ref());
    HeaderValue::from_str(&format!(
        "default-src 'none'; script-src 'sha256-{hash}'; style-src 'unsafe-inline'; \
         font-src 'self'; img-src 'self' blob:; connect-src 'self' https://stats.favicons.page; base-uri 'none'; \
         form-action 'none'; frame-ancestors 'none'"
    ))
    .expect("ascii csp")
}

fn inline_script(html: &str) -> Option<&str> {
    let start = html.find("<script>")? + "<script>".len();
    let end = start + html[start..].find("</script>")?;
    Some(&html[start..end])
}

fn respond(page: &Page, headers: &HeaderMap) -> Response {
    let fresh = headers
        .get(IF_NONE_MATCH)
        .and_then(|v| v.to_str().ok())
        .zip(page.etag.to_str().ok())
        .is_some_and(|(inm, e)| crate::http::etag_matches(inm, e));
    let mut r = if fresh {
        let mut r = Response::new(Body::empty());
        *r.status_mut() = StatusCode::NOT_MODIFIED;
        r
    } else {
        Response::new(Body::from(page.body.clone()))
    };
    let h = r.headers_mut();
    h.insert(
        CONTENT_TYPE,
        HeaderValue::from_static(page.asset.content_type()),
    );
    h.insert(
        CACHE_CONTROL,
        HeaderValue::from_static(page.asset.cache_control()),
    );
    h.insert(ETAG, page.etag.clone());
    if let Some(csp) = &page.csp {
        h.insert(CONTENT_SECURITY_POLICY, csp.clone());
    }
    if page.asset.indexable() {
        h.insert(
            HeaderName::from_static("x-robots-tag"),
            HeaderValue::from_static("all"),
        );
    }
    r
}

#[cfg(test)]
mod tests {
    use super::*;

    fn site(origin: Option<&str>) -> Site {
        let mut cfg = Config::default();
        cfg.server.public_url = origin.map(str::to_string);
        Site::new(&cfg)
    }

    fn body(r: Response) -> String {
        let bytes = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap()
            .block_on(axum::body::to_bytes(r.into_body(), usize::MAX))
            .unwrap();
        String::from_utf8_lossy(&bytes).into_owned()
    }

    #[cfg(feature = "site")]
    #[test]
    fn script_hash_covers_the_inline_script() {
        let script = inline_script(page::INDEX).unwrap();
        assert!(script.contains("fetch(`/${style}/"));
        assert!(!script.contains("{{"));
        let page = Page::rendered(Asset::Index, "https://favicons.page", &[]);
        let csp = page.csp.unwrap();
        let csp = csp.to_str().unwrap();
        assert!(csp.contains("script-src 'sha256-"));
        assert!(csp.contains("font-src 'self'"));
        assert!(csp.contains("connect-src 'self' https://stats.favicons.page;"));
        assert_eq!(csp.matches("https:").count(), 1);
        assert_eq!(page::INDEX.matches("<script>").count(), 1);
    }

    #[cfg(feature = "site")]
    #[test]
    fn page_loads_nothing_from_other_origins() {
        for needle in [
            "googleapis",
            "gstatic",
            "src=\"http",
            "href=\"//",
            "@import",
        ] {
            assert!(!page::INDEX.contains(needle), "{needle}");
        }
        assert!(page::INDEX.contains("url(\"/fonts/archivo.woff2\")"));
        assert!(!page::FONT_DISPLAY.is_empty() && !page::FONT_MONO.is_empty());
    }

    #[cfg(feature = "site")]
    #[test]
    fn names_itself_after_the_configured_origin() {
        let s = site(Some("https://favicons.page/"));
        let html = body(s.serve(Asset::Index, &HeaderMap::new(), &Uri::from_static("/")));
        assert!(html.contains("<title>favicons.page"));
        assert!(html.contains(r#"<link rel="canonical" href="https://favicons.page/">"#));
        assert!(html.contains("https://stats.favicons.page/og.png"));
        assert!(!html.contains("{{"));
    }

    #[test]
    fn docs_name_themselves_after_the_origin() {
        let s = site(Some("https://favicons.page/"));
        let robots = body(s.serve(Asset::Robots, &HeaderMap::new(), &Uri::from_static("/")));
        assert!(robots.contains("Sitemap: https://favicons.page/sitemap.xml"));
        assert!(robots.contains("Disallow: /color/"));
        let api = body(s.serve(Asset::OpenApi, &HeaderMap::new(), &Uri::from_static("/")));
        let json: serde_json::Value = serde_json::from_str(&api).unwrap();
        assert_eq!(json["servers"][0]["url"], "https://favicons.page");
    }

    #[test]
    fn falls_back_to_a_sanitized_host_header() {
        let s = site(None);
        let mut h = HeaderMap::new();
        h.insert(HOST, HeaderValue::from_static("icons.example.org"));
        let llms = body(s.serve(Asset::Llms, &h, &Uri::from_static("/llms.txt")));
        assert!(llms.starts_with("# icons.example.org"));
        h.insert(HOST, HeaderValue::from_static("evil.com\"><script>"));
        let llms = body(s.serve(Asset::Llms, &h, &Uri::from_static("/llms.txt")));
        assert!(llms.starts_with("# localhost"));
    }

    #[test]
    fn every_template_is_well_formed() {
        for asset in Asset::TEMPLATED {
            let page = Page::rendered(asset, "https://favicons.page", &["selfhst".into()]);
            let text = std::str::from_utf8(&page.body).unwrap();
            assert!(!text.contains("{{"), "{asset:?}");
        }
    }
}