1use 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
24pub struct FrontendParams<S = ()> {
30 pub(super) base: BaseTemplateData,
32 pub(super) pages: Pages<S>,
34 pub(super) analytics: AnalyticsConfig,
36 pub(super) sentry_browser_dsn: String,
40 pub(super) browser_traces_sample_rate: TracesSampleRate,
42 pub(super) not_found: NotFound<S>,
44 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 #[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 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 #[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 #[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 #[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#[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 pub feeds: Option<FeedSet>,
141}
142
143pub struct Frontend<S> {
145 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 pub not_found: NotFound<S>,
155 pub has_svg_icon: bool,
157}
158
159#[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 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(¶ms.sentry_browser_dsn).map_err(WebServerError::SentryDsn)?;
183
184 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 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(¶ms.base, cache_buster);
205
206 if !social_image.is_large_enough() {
207 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 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(¶ms.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(¶ms.base),
265 webmanifest: webmanifest(¶ms.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
311fn 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
317fn 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#[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 fn derive(project: &str, sentry_bundle: &str) -> Self {
355 let slug: String = slugify(project);
356 let analytics: String = short_hash(project);
357 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
371fn 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
387fn short_hash(input: &str) -> String {
390 format!("{:x}", md5::compute(input.as_bytes()))
391 .chars()
392 .take(8)
393 .collect()
394}
395
396fn 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 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
424fn probe_social_image(base: &BaseTemplateData, cache_buster: &CacheBuster) -> SocialImageMetadata {
426 crate::assets::probe_social_image(cache_buster.file(base.social_image()))
427}
428
429fn robots_txt(base_url: &str, sitemaps: &SitemapSet, has_feed: bool) -> String {
443 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 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#[cfg(feature = "preset")]
477fn humans_txt(_base: &BaseTemplateData) -> String {
478 String::from(PRESET_HUMANS_TXT)
479}
480
481#[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
492fn 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 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}