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