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