Skip to main content

webserver_base/webserver/
frontend.rs

1//! What it takes to serve HTML to humans.
2//!
3//! `WebServer::frontend` is the line between a site and a service. Everything a
4//! frontend *must* have is a field here, so omitting one is a compile error
5//! rather than a page that quietly ships without a share card. A server that
6//! never calls it — a sidecar, a JSON API — needs none of it and boots clean.
7
8use crate::analytics::{AnalyticsConfig, SentryDsn};
9use crate::assets::CacheBuster;
10use crate::feed::{ATOM_PATH, Feed, FeedSet, FeedSite, JSON_PATH, RSS_PATH, build_feeds};
11use crate::sitemap::{SitemapSet, SitemapUrl, build_sitemaps};
12use handlebars::HelperDef;
13
14use crate::templates::{
15    AnalyticsPaths, BaseTemplateData, FeedLinks, FrontendRuntime, SentryBrowser,
16    SocialImageMetadata,
17};
18use crate::{Environment, env};
19use chrono::Datelike as _;
20
21use super::error::WebServerError;
22use super::not_found::NotFound;
23use super::pages::Pages;
24
25/// Everything a frontend requires, plus what it may add.
26///
27/// The four required inputs are constructor arguments, so omitting one is a
28/// compile error; each has its own type, so none can be passed in another's
29/// place. The optional ones are `with_*` builders with a working default.
30pub struct FrontendParams<S = ()> {
31    /// What is true of every page on the site.
32    pub(super) base: BaseTemplateData,
33    /// The pages themselves, which become both routes and sitemap entries.
34    pub(super) pages: Pages<S>,
35    /// Which Plausible site this frontend reports to.
36    pub(super) analytics: AnalyticsConfig,
37    /// The browser Sentry DSN — separate from the server's, because Sentry
38    /// recommends a project per language and per deployable, and mixing Rust
39    /// panics with JavaScript exceptions in one stream helps nobody.
40    pub(super) sentry_browser_dsn: String,
41    /// The router-fallback 404's `{{app}}`.
42    pub(super) not_found: NotFound<S>,
43    /// The project's own Handlebars helpers.
44    pub(super) helpers: Vec<(String, Box<dyn HelperDef + Send + Sync + 'static>)>,
45}
46
47impl<S> FrontendParams<S>
48where
49    S: Clone + Send + Sync + 'static,
50{
51    /// A frontend from its four required inputs.
52    #[must_use]
53    pub fn new(
54        base: BaseTemplateData,
55        pages: Pages<S>,
56        analytics: AnalyticsConfig,
57        sentry_browser_dsn: impl Into<String>,
58    ) -> Self {
59        Self {
60            base,
61            pages,
62            analytics,
63            sentry_browser_dsn: sentry_browser_dsn.into(),
64            not_found: NotFound::none(),
65            helpers: Vec::new(),
66        }
67    }
68
69    /// Reads the analytics script id and browser DSN from the environment.
70    /// Analytics is off when `WSB_ENVIRONMENT` is `local` or the id is unset
71    /// or blank.
72    ///
73    /// # Errors
74    ///
75    /// [`WebServerError::Env`] if `WSB_ENVIRONMENT` or the browser DSN is
76    /// unset, blank or invalid.
77    pub fn from_env(base: BaseTemplateData, pages: Pages<S>) -> Result<Self, WebServerError> {
78        Ok(Self::new(
79            base,
80            pages,
81            AnalyticsConfig::from_env().map_err(WebServerError::Env)?,
82            env::required(crate::analytics::ENV_SENTRY_BROWSER_DSN).map_err(WebServerError::Env)?,
83        ))
84    }
85
86    /// What the router-fallback 404 shows as `{{app}}`. Defaults to
87    /// [`NotFound::none`].
88    #[must_use]
89    pub fn with_not_found(mut self, not_found: NotFound<S>) -> Self {
90        self.not_found = not_found;
91        self
92    }
93
94    /// Registers a Handlebars helper of the project's own, under `name`.
95    ///
96    /// A name the library or Handlebars already uses is a boot error, never a
97    /// silent override. A helper several projects reimplement belongs in the
98    /// library instead.
99    #[must_use]
100    pub fn with_helper(
101        mut self,
102        name: impl Into<String>,
103        helper: impl HelperDef + Send + Sync + 'static,
104    ) -> Self {
105        self.helpers.push((name.into(), Box::new(helper)));
106        self
107    }
108}
109
110/// The well-known documents a frontend serves, held in memory.
111///
112/// None of these is written to disk. They are generated (robots, sitemaps, the
113/// web manifest) or embedded (humans.txt), they are served at fixed never-cached
114/// routes where a content hash would mean nothing, and keeping them in memory is
115/// what lets a production image be read-only.
116#[derive(Debug, Clone)]
117pub struct WellKnown {
118    pub robots_txt: String,
119    pub humans_txt: String,
120    pub webmanifest: String,
121    pub sitemaps: SitemapSet,
122    /// The three feed documents, when the site declared a feed. Unlike the rest
123    /// of this struct these are *not* served uncached: a feed is the most-polled
124    /// document a site has, and stripping its validators would re-send every
125    /// byte on every poll.
126    pub feeds: Option<FeedSet>,
127}
128
129/// A frontend, assembled.
130pub struct Frontend<S> {
131    pub pages: Pages<S>,
132    pub base: BaseTemplateData,
133    pub runtime: FrontendRuntime,
134    pub well_known: WellKnown,
135    pub analytics: AnalyticsConfig,
136    pub sentry_dsn: SentryDsn,
137    /// The router-fallback 404's `{{app}}`.
138    pub not_found: NotFound<S>,
139    /// Whether an SVG icon exists to link.
140    pub has_svg_icon: bool,
141}
142
143/// The bytes of Todd Everett Griffin's humans.txt, shared by every project that
144/// enables `preset` so it is written once and never drifts.
145#[cfg(feature = "preset")]
146const PRESET_HUMANS_TXT: &str = include_str!("../../assets/humans.txt");
147
148impl<S> Frontend<S>
149where
150    S: Clone + Send + Sync + 'static,
151{
152    /// Builds a frontend: derives the proxy paths, probes the social image,
153    /// and renders the well-known documents.
154    ///
155    /// # Errors
156    ///
157    /// [`WebServerError::SentryDsn`] if the browser DSN is malformed, or
158    /// [`WebServerError::Sitemap`] if the sitemaps cannot be built.
159    pub fn build(
160        params: FrontendParams<S>,
161        feed: Option<Feed>,
162        cache_buster: &CacheBuster,
163        environment: Environment,
164    ) -> Result<Self, WebServerError> {
165        let sentry_dsn: SentryDsn =
166            SentryDsn::parse(&params.sentry_browser_dsn).map_err(WebServerError::SentryDsn)?;
167
168        // Every asset a page will reference is proved to resolve before the
169        // server binds. Falling back to an un-hashed path would produce a link
170        // that 404s for the visitor and reports nothing to us.
171        let mut declared: Vec<String> = Vec::new();
172        declared.extend(params.base.style_sheets().iter().cloned());
173        declared.extend(params.base.scripts().iter().cloned());
174        declared.push(params.base.social_image().to_string());
175        declared.extend(params.pages.declared_assets());
176        crate::assets::validate_declared(cache_buster, &declared)?;
177
178        let icon_source: crate::assets::IconSource = crate::assets::validate_icons(cache_buster)?;
179
180        // Local runs never reach Plausible, whatever id was configured.
181        let analytics: AnalyticsConfig = params.analytics.clone().for_environment(environment);
182        if analytics.is_enabled() {
183            tracing::info!("analytics enabled");
184        } else if environment.is_local() {
185            tracing::info!("analytics disabled: WSB_ENVIRONMENT is local");
186        } else {
187            tracing::warn!("analytics disabled in production: WSB_ANALYTICS_ID is unset or empty");
188        }
189
190        let paths: ProxyPaths = ProxyPaths::derive(params.base.project());
191        let social_image: SocialImageMetadata = probe_social_image(&params.base, cache_buster);
192
193        if !social_image.is_large_enough() {
194            // Boots, but every X share renders a thumbnail instead of the wide
195            // card the layout declares — exactly the kind of silent degradation
196            // that must reach Sentry, and `warn!` never does.
197            tracing::error!(
198                "the social image is {}x{}, below the 600x314 floor for a \
199                 `summary_large_image` card; shares will degrade to a thumbnail",
200                social_image.width.unwrap_or_default(),
201                social_image.height.unwrap_or_default(),
202            );
203        }
204
205        // Images are declared logically but served hashed; the sitemap has to
206        // name the URL that actually resolves.
207        let sitemap_urls: Vec<SitemapUrl> = params
208            .pages
209            .sitemap_urls()?
210            .into_iter()
211            .map(|url| url.map_images(|image| cache_buster.get_file(image)))
212            .collect();
213        let last_modified: Option<chrono::DateTime<chrono::Utc>> =
214            crate::assets::content_modified_in(cache_buster.root(), &["html", "static"]);
215        let sitemaps: SitemapSet =
216            build_sitemaps(params.base.base_url(), &sitemap_urls, last_modified)
217                .map_err(WebServerError::Sitemap)?;
218
219        let feed_title: Option<String> = feed.as_ref().map(|feed| feed.title.clone());
220        let feeds: Option<FeedSet> = match feed {
221            None => None,
222            Some(feed) => {
223                if !params.pages.paths().contains(&feed.page_url.as_str()) {
224                    return Err(WebServerError::Feed(
225                        crate::feed::FeedError::PageNotDeclared {
226                            page_url: feed.page_url.clone(),
227                        },
228                    ));
229                }
230                let site: FeedSite = feed_site(&params.base, cache_buster);
231                Some(
232                    build_feeds(&site, &feed, |path: &str| {
233                        cache_buster
234                            .is_hashed(path)
235                            .then(|| cache_buster.get_file(path))
236                    })
237                    .map_err(WebServerError::Feed)?,
238                )
239            }
240        };
241
242        let feed_links: Option<FeedLinks> = feed_title.map(|title| FeedLinks {
243            title,
244            rss: format!("{}{RSS_PATH}", params.base.base_url()),
245            atom: format!("{}{ATOM_PATH}", params.base.base_url()),
246            json: format!("{}{JSON_PATH}", params.base.base_url()),
247        });
248
249        let well_known: WellKnown = WellKnown {
250            robots_txt: robots_txt(params.base.base_url(), &sitemaps, feeds.is_some()),
251            humans_txt: humans_txt(&params.base),
252            webmanifest: webmanifest(&params.base),
253            sitemaps,
254            feeds,
255        };
256
257        let runtime: FrontendRuntime = FrontendRuntime {
258            theme_script: params.base.theme_script().source(),
259            social_image,
260            has_svg_icon: icon_source.is_vector(),
261            analytics: analytics.is_enabled().then(|| AnalyticsPaths {
262                script_path: paths.analytics_script.clone(),
263                event_path: paths.analytics_event.clone(),
264            }),
265            sentry_browser: SentryBrowser {
266                script_path: paths.sentry_script.clone(),
267                tunnel_path: paths.sentry_tunnel.clone(),
268                environment: environment.to_string(),
269            },
270            feed: feed_links,
271        };
272
273        Ok(Self {
274            pages: params.pages,
275            base: params.base,
276            runtime,
277            well_known,
278            analytics,
279            sentry_dsn,
280            not_found: params.not_found,
281            has_svg_icon: icon_source.is_vector(),
282        })
283    }
284}
285
286/// Where the first-party proxies live on this origin.
287///
288/// Derived from the project name, never configured. Plausible's guidance is to
289/// avoid their documented default paths because blocklists target them, and to
290/// avoid words like "analytics" or "stats". A per-project name also means no
291/// single filter rule can take out every site at once, which a shared
292/// library-wide constant would invite. The shape — `name-hash.js` — is what
293/// every bundler on the web already emits.
294#[derive(Debug, Clone, PartialEq, Eq)]
295struct ProxyPaths {
296    analytics_script: String,
297    analytics_event: String,
298    sentry_script: String,
299    sentry_tunnel: String,
300}
301
302impl ProxyPaths {
303    fn derive(project: &str) -> Self {
304        let slug: String = slugify(project);
305        let analytics: String = short_hash(project);
306        // A second, unrelated hash, so the two scripts do not visibly belong to
307        // one another.
308        let sentry: String = short_hash(&format!("{project}:sentry"));
309
310        Self {
311            analytics_script: format!("/script/{slug}-{analytics}.js"),
312            analytics_event: format!("{}/{slug}-{analytics}", super::server::API_PREFIX),
313            sentry_script: format!("/script/{slug}-{sentry}.js"),
314            sentry_tunnel: format!("{}/{slug}-{sentry}", super::server::API_PREFIX),
315        }
316    }
317}
318
319/// `Boggledygook!` → `boggledygook`.
320fn slugify(project: &str) -> String {
321    let mut slug: String = String::with_capacity(project.len());
322    let mut previous_dash: bool = true;
323    for character in project.chars() {
324        if character.is_ascii_alphanumeric() {
325            slug.push(character.to_ascii_lowercase());
326            previous_dash = false;
327        } else if !previous_dash {
328            slug.push('-');
329            previous_dash = true;
330        }
331    }
332    String::from(slug.trim_matches('-'))
333}
334
335/// Eight hex characters: enough to be unguessable, short enough to look like
336/// ordinary bundler output.
337fn short_hash(input: &str) -> String {
338    format!("{:x}", md5::compute(input.as_bytes()))
339        .chars()
340        .take(8)
341        .collect()
342}
343
344/// Channel metadata for the feed, derived rather than configured a second time.
345///
346/// Everything here already exists on [`BaseTemplateData`] or in the generated
347/// icon set; asking a project to restate it would be one more pair of values
348/// free to drift apart.
349fn feed_site(base: &BaseTemplateData, cache_buster: &CacheBuster) -> FeedSite {
350    let absolute = |path: &str| format!("{}{path}", base.base_url());
351    let year: i32 = chrono::Utc::now().year();
352
353    FeedSite {
354        base_url: String::from(base.base_url()),
355        author: String::from(base.author()),
356        // RFC 5646 wants a hyphen where `og:locale` wants an underscore.
357        language: format!("{}-{}", base.language_code(), base.country_code()),
358        icon_url: cache_buster
359            .is_hashed("static/image/favicon/favicon-512.png")
360            .then(|| absolute("/icon-512.png")),
361        favicon_url: cache_buster
362            .is_hashed("static/image/favicon/favicon.ico")
363            .then(|| absolute("/favicon.ico")),
364        copyright: format!("© {}–{year} {}", base.copyright_start(), base.author()),
365    }
366}
367
368/// Resolves and measures the social card image on disk.
369fn probe_social_image(base: &BaseTemplateData, cache_buster: &CacheBuster) -> SocialImageMetadata {
370    crate::assets::probe_social_image(cache_buster.file(base.social_image()))
371}
372
373/// `robots.txt`, naming the sitemap index, then the feed, then every url set.
374///
375/// Order is deliberate: Google discards a robots.txt past 500 KiB and
376/// truncation is positional, so the lines that must survive go at the top.
377///
378/// Only Atom is listed, and only once. Google accepts an RSS 2.0 or Atom 1.0
379/// file as a sitemap and recommends submitting one *alongside* a full sitemap —
380/// the sitemap is the inventory, the feed is the recency signal. Atom wins
381/// because it has a real per-entry `<updated>`; RSS carries publication dates
382/// only, so a revised post looks untouched. Listing both would report the same
383/// URLs twice for nothing, and JSON Feed is not a supported sitemap format at
384/// all. The feed outranks the `sitemap-N.xml` lines for survival because those
385/// are already named by the index above them.
386fn robots_txt(base_url: &str, sitemaps: &SitemapSet, has_feed: bool) -> String {
387    /// Well under Google's 500 KiB ceiling, with room for the directives above.
388    const BUDGET: usize = 400 * 1024;
389
390    let mut paths: Vec<String> = sitemaps.paths();
391    if has_feed {
392        paths.insert(1, String::from(ATOM_PATH));
393    }
394
395    let mut robots: String = String::from("User-agent: *\nAllow: /\n\n");
396    let mut omitted: usize = 0;
397    for path in paths {
398        let line: String = format!("Sitemap: {base_url}{path}\n");
399        if robots.len() + line.len() > BUDGET {
400            omitted += 1;
401            continue;
402        }
403        robots.push_str(&line);
404    }
405
406    if omitted > 0 {
407        // Silent truncation is the failure mode this whole design avoids, so
408        // the generator must not commit it either.
409        tracing::error!(
410            "omitted {omitted} sitemap line(s) from robots.txt to stay under \
411             Google's 500 KiB limit; the index is still listed first"
412        );
413    }
414
415    robots
416}
417
418/// The site's humans.txt: the author's own, written once and inherited by every
419/// project that enables `preset`.
420#[cfg(feature = "preset")]
421fn humans_txt(_base: &BaseTemplateData) -> String {
422    String::from(PRESET_HUMANS_TXT)
423}
424
425/// A minimal humans.txt, so the layout's `rel="author"` link never 404s on a
426/// project that does not use the author's own.
427#[cfg(not(feature = "preset"))]
428fn humans_txt(base: &BaseTemplateData) -> String {
429    format!(
430        "/* TEAM */\n\nName: {}\nSite: {}\n",
431        base.author(),
432        base.base_url()
433    )
434}
435
436/// The web app manifest.
437///
438/// `minimal-ui` rather than `standalone`: an installed multi-page content site
439/// with no back button strands the reader. It still satisfies the installability
440/// bar, so nothing is given up.
441fn webmanifest(base: &BaseTemplateData) -> String {
442    const ICONS: [(&str, &str); 2] = [("/icon-192.png", "192x192"), ("/icon-512.png", "512x512")];
443
444    let icons: Vec<String> = ICONS
445        .iter()
446        .map(|(source, sizes)| {
447            format!(
448                "{{ \"src\": \"{source}\", \"sizes\": \"{sizes}\", \"type\": \"image/png\", \"purpose\": \"any maskable\" }}"
449            )
450        })
451        .collect();
452
453    let color: &str = base.theme_color().primary();
454
455    format!(
456        "{{\n  \"name\": {name:?},\n  \"short_name\": {name:?},\n  \"description\": {description:?},\n  \"start_url\": \"/\",\n  \"scope\": \"/\",\n  \"display\": \"minimal-ui\",\n  \"theme_color\": {color:?},\n  \"background_color\": {color:?},\n  \"icons\": [\n    {icons}\n  ]\n}}\n",
457        name = base.project(),
458        description = base.description(),
459        icons = icons.join(",\n    "),
460    )
461}
462
463#[cfg(test)]
464mod tests {
465    use super::{ProxyPaths, short_hash, slugify};
466
467    #[test]
468    fn a_project_name_becomes_a_lowercase_dashed_slug() {
469        assert_eq!(String::from("boggledygook"), slugify("Boggledygook"));
470        assert_eq!(String::from("eat-out"), slugify("Eat Out"));
471        assert_eq!(
472            String::from("template-web-server"),
473            slugify("Template Web Server")
474        );
475        assert_eq!(
476            String::from("palms-small-engine"),
477            slugify("Palms  Small!Engine")
478        );
479    }
480
481    #[test]
482    fn the_proxy_paths_look_like_ordinary_bundler_output() {
483        let paths: ProxyPaths = ProxyPaths::derive("Boggledygook");
484
485        assert!(paths.analytics_script.starts_with("/script/boggledygook-"));
486        assert!(
487            std::path::Path::new(&paths.analytics_script)
488                .extension()
489                .is_some_and(|extension| extension.eq_ignore_ascii_case("js"))
490        );
491        assert!(paths.analytics_event.starts_with("/api/v1/boggledygook-"));
492
493        // None of Plausible's forbidden words appear anywhere.
494        for path in [&paths.analytics_script, &paths.analytics_event] {
495            for forbidden in ["plausible", "analytics", "tracking", "stats"] {
496                assert!(!path.contains(forbidden), "`{path}` contains `{forbidden}`");
497            }
498        }
499    }
500
501    #[test]
502    fn the_two_proxies_do_not_share_a_hash() {
503        let paths: ProxyPaths = ProxyPaths::derive("Boggledygook");
504
505        assert_ne!(paths.analytics_script, paths.sentry_script);
506        assert_ne!(paths.analytics_event, paths.sentry_tunnel);
507    }
508
509    #[test]
510    fn two_projects_never_share_a_path_so_one_filter_rule_cannot_block_both() {
511        let first: ProxyPaths = ProxyPaths::derive("Boggledygook");
512        let second: ProxyPaths = ProxyPaths::derive("Eat Out");
513
514        assert_ne!(first.analytics_script, second.analytics_script);
515    }
516
517    #[test]
518    fn the_derived_hash_is_stable_across_runs() {
519        let expected: String = short_hash("Boggledygook");
520        let actual: String = short_hash("Boggledygook");
521        assert_eq!(expected, actual);
522
523        let expected: usize = 8;
524        let actual: usize = short_hash("Boggledygook").len();
525        assert_eq!(expected, actual);
526    }
527}