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