proa_framework_axum 0.4.2

Axum and Tokio adapter for Proa SSR applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

#![forbid(unsafe_code)]

mod asset_urls;
pub mod csp;
pub mod csrf;
pub mod dev_reload;
mod dev_startup;
pub use dev_startup::DevServerStartup;
pub mod discovery;
pub mod public_assets;
pub mod readiness;
pub mod route;
pub mod rsjs_assets;
pub mod security_headers;
pub mod server;
pub mod static_service;
pub use asset_urls::base_path_assets;

pub use csp::{CspNonceLayer, CspPolicy};
pub use csrf::CrossOriginProtectionLayer;
pub use dev_reload::{DevReloadLayer, RELOAD_PORT_ENV, RELOAD_TOKEN_ENV};
pub use discovery::{robots_txt, sitemap_index_xml, sitemap_xml};
pub use proa_core::{
    AppUrl, ArticleMetadata, BasePath, ComponentRole, CspNonce, HeadAlternate, HeadAuthor,
    HeadConfig, HeadDefaults, HeadIcon, HeadMedia, HeadMetadata, HeadTitle, HeadUrlPolicy,
    HeadValue, HeadVerification, IconKind, ImagePreview, InvalidBasePath, ReferrerPolicy, Robots,
    SyncHeadOperation, Twitter, TwitterCard,
};
pub use proa_framework_core::{
    absolute_http_url, ChangeFreq, DiscoveryError, RobotsGroup, RobotsRule, RobotsTxt, Sitemap,
    SitemapFile, SitemapIndex, SitemapIndexEntry, SitemapPriority, SitemapUrl, MAX_ROBOTS_BYTES,
    MAX_SITEMAP_BYTES, MAX_SITEMAP_ENTRIES,
};
pub use public_assets::{
    AssetPrefix, InvalidAssetPrefix, PublicAssetError, PublicAssets, ASSET_PREFIX_ENV,
};
pub use readiness::{Readiness, DEFAULT_READINESS_TIMEOUT};
pub use route::{
    app_url, drive_dyn_render, drive_dyn_send_render, explicit_markdown,
    explicit_markdown_async_with_loader, negotiate, negotiate_async_with_loader,
    render_metadata_head, resolved_metadata, router_from_spec, CascadeOpenGraph, CascadeValue,
    ComputedRouteMeta, DynRenderOutcome, DynSendRenderOutcome, DynWebRender, DynWebRenderSend,
    Layout, LayoutRef, LocalStreamExecutorConfig, ManagedPreparationTimeout, MarkdownAlternate,
    Metadata, MetadataRef, OpenGraph, OpenGraphImage, OpenGraphMedia, PageCacheLayer,
    PageCacheService, RepresentationResponse, ResolvedMetadata, ResolvedOpenGraphImage,
    ResolvedOpenGraphMedia, Route, RouteContextLayer, RouteMode, RouteResponse,
    RouteResponseFuture, RouteSpec, StaticPathsFn,
};
pub use rsjs_assets::{RsjsAssets, RsjsAssetsError, RsjsFile};
pub use security_headers::{FrameOptions, SecurityHeadersConfig, SecurityHeadersLayer};
pub use server::{serve, serve_with_shutdown, ShutdownOutcome, DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT};
pub use static_service::EmbeddedStaticService;

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use axum::http::{header, HeaderValue};
use axum::{extract::DefaultBodyLimit, Router};
use tower::limit::GlobalConcurrencyLimitLayer;
use tower::Layer as _;
use tower_http::catch_panic::CatchPanicLayer;
use tower_http::services::ServeDir;
use tower_http::set_header::SetResponseHeaderLayer;
use tower_http::timeout::TimeoutLayer;

/// Default request body size limit applied by `FrameworkBuilder::build`.
///
/// 1 MiB. Override per builder via `with_body_limit(usize)`. Override
/// per route via Axum's `DefaultBodyLimit::max(...)` layer applied to a
/// nested router. Prior versions shipped with no global body limit, so a
/// single POST with a multi-GB body could pin a worker indefinitely.
pub const DEFAULT_BODY_LIMIT_BYTES: usize = 1024 * 1024;

/// Default request timeout applied by `FrameworkBuilder::build`.
///
/// The timeout covers producing the response (routing, middleware,
/// rendering) but not draining the response body, so long-lived
/// streaming SSR responses are unaffected once their first bytes are
/// out. Override via `with_request_timeout(Duration)`; disable via
/// `without_request_timeout()`.
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// Errors that prevent the framework router from starting.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FrameworkBuildError {
    #[error(transparent)]
    Discovery(#[from] DiscoveryError),
    #[error("could not load published public assets: {0}")]
    PublicAssets(#[from] PublicAssetError),
    #[error(transparent)]
    RsjsAssets(#[from] RsjsAssetsError),
}

/// Builder for the framework's axum `Router`.
///
/// Security defaults applied by [`build`](Self::build):
///
/// - Cross-origin protection (CSRF defense) is **on** for unsafe methods
///   (everything except GET / HEAD / OPTIONS). Browser-issued
///   cross-origin POSTs are rejected with 403 based on `Sec-Fetch-Site`
///   / `Origin`; non-browser clients are unaffected. Disable with
///   [`with_cross_origin_protection(false)`](Self::with_cross_origin_protection)
///   or allow specific callers with
///   [`with_trusted_origin`](Self::with_trusted_origin).
/// - Security response headers (`X-Content-Type-Options: nosniff`,
///   `X-Frame-Options: DENY`, `Referrer-Policy:
///   strict-origin-when-cross-origin`) are stamped on every response
///   that does not already set them; tune via
///   [`with_security_headers`](Self::with_security_headers).
/// - A 30 second request timeout
///   ([`DEFAULT_REQUEST_TIMEOUT`]) bounds response production.
/// - A global request body limit of 1 MiB
///   ([`DEFAULT_BODY_LIMIT_BYTES`]).
///
/// Opt-in hardening: [`with_strict_csp`](Self::with_strict_csp) (nonce-based
/// Content Security Policy), [`with_concurrency_limit`](Self::with_concurrency_limit),
/// and [`with_catch_panic`](Self::with_catch_panic).
pub struct FrameworkBuilder {
    base_path: BasePath,
    public_origin: Option<String>,
    head: Option<proa_core::HeadConfig>,
    sitemaps: Option<discovery::SitemapConfig>,
    robots: Option<RobotsTxt>,
    /// Serve the linked RSJS runtimes and modules under `/_proa/immutable/rsjs/`.
    /// ON by default; disable with [`without_rsjs_assets`](Self::without_rsjs_assets).
    rsjs_assets: bool,
    public_assets: Option<PublicAssets>,
    static_router: Option<Router>,
    dynamic_router: Option<Router>,
    computed_metadata: Option<Arc<HashMap<String, ComputedRouteMeta>>>,
    /// Global request-body size limit applied via `DefaultBodyLimit`
    /// in `build`. `None` means use `DEFAULT_BODY_LIMIT_BYTES`. Set to
    /// `Some(usize::MAX)` only when a specific deployment knows it
    /// must accept very large request bodies (file uploads in a
    /// closed admin path); generally prefer a per-route override on a
    /// nested router instead of removing the global cap.
    body_limit: Option<usize>,
    /// Cross-origin protection (CSRF defense). ON by default.
    cross_origin_protection: bool,
    /// Extra origins trusted by the cross-origin protection layer.
    trusted_origins: Vec<String>,
    /// Security response header policy applied to every response.
    security_headers: SecurityHeadersConfig,
    /// Per-request CSP nonce plus policy. OFF by default: a strict policy
    /// has to match what the app's own markup loads.
    csp: Option<CspPolicy>,
    /// Request timeout. `None` disables the timeout layer entirely.
    request_timeout: Option<Duration>,
    /// Optional global in-flight request cap. OFF by default.
    concurrency_limit: Option<usize>,
    /// Opt-in `CatchPanicLayer` turning handler panics into 500s.
    catch_panic: bool,
    /// Bounded pinned-worker policy for non-`Send` render streams.
    local_stream_executor: LocalStreamExecutorConfig,
}

impl Default for FrameworkBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl FrameworkBuilder {
    /// Create a builder with secure defaults.
    pub fn new() -> Self {
        Self {
            base_path: BasePath::default(),
            public_origin: None,
            head: None,
            sitemaps: None,
            robots: None,
            rsjs_assets: true,
            public_assets: None,
            static_router: None,
            dynamic_router: None,
            computed_metadata: None,
            body_limit: None,
            cross_origin_protection: true,
            trusted_origins: Vec::new(),
            security_headers: SecurityHeadersConfig::default(),
            csp: None,
            request_timeout: Some(DEFAULT_REQUEST_TIMEOUT),
            concurrency_limit: None,
            catch_panic: false,
            local_stream_executor: LocalStreamExecutorConfig::default(),
        }
    }

    /// Configure reusable document head defaults once for all rendered routes.
    /// The origin/mount policy belongs to HeadConfig and is never inferred from Host.
    pub fn with_head(mut self, head: proa_core::HeadConfig) -> Self {
        self.head = Some(head);
        self
    }

    /// Set the browser-visible mount prefix for a prefix-stripping proxy.
    /// Configure from an environment variable at startup with
    /// `BasePath::new(&std::env::var("PROA_BASE_PATH").unwrap_or_default())?`.
    /// Incoming routes remain rooted at `/`. Application-authored links and
    /// redirects use `app_url` or `cx.url` explicitly.
    pub fn with_base_path(mut self, base_path: BasePath) -> Self {
        self.base_path = base_path;
        self
    }

    /// Set the public HTTP(S) origin used by discovery routes.
    ///
    /// Supply only the scheme, host and optional port, for example
    /// `https://example.com`. The mount prefix comes from `with_base_path`.
    /// This is explicit configuration; request headers are not used to infer it.
    pub fn with_public_origin(mut self, origin: &str) -> Result<Self, DiscoveryError> {
        let validated = Sitemap::new(origin)?;
        self.public_origin = Some(validated.origin().to_owned());
        Ok(self)
    }

    /// Serve `/sitemap.xml` from these entries using the builder's final public
    /// origin and base path. Configuration order does not matter.
    ///
    /// Entries are application-local paths or same-origin absolute URLs inside
    /// the final base path directory (checked after URL normalization). The
    /// document is validated and rendered once at startup. Do not also register
    /// a custom `/sitemap.xml` handler. Requires `with_public_origin`.
    /// Replaces any previous `with_sitemap` or `with_sitemaps` configuration.
    ///
    /// ```
    /// use proa_framework_axum::{
    ///     BasePath, FrameworkBuildError, FrameworkBuilder,
    ///     RobotsTxt, SitemapUrl,
    /// };
    /// let app = FrameworkBuilder::new()
    ///     .with_base_path(BasePath::new("/apps/demo").unwrap())
    ///     .with_public_origin("https://example.com")?
    ///     .with_sitemap([SitemapUrl::new("/")?, SitemapUrl::new("/pricing")?])
    ///     .with_robots(RobotsTxt::new().disallow("/admin")?)
    ///     .try_build()?;
    /// # Ok::<(), FrameworkBuildError>(())
    /// ```
    pub fn with_sitemap(mut self, urls: impl IntoIterator<Item = SitemapUrl>) -> Self {
        self.sitemaps = Some(discovery::SitemapConfig::Single(urls.into_iter().collect()));
        self
    }

    /// Serve multiple named sitemaps at `/sitemap-{id}.xml`, with a sitemap
    /// index at `/sitemap.xml`. Robots advertises the index when enabled.
    ///
    /// Await an application-owned async generator before calling this method:
    /// `.with_sitemaps(generate_sitemaps(&db).await?)`. All documents are
    /// validated and rendered at startup using the final origin and base path.
    /// New database content requires regeneration/restart, or custom handlers.
    /// Requires `with_public_origin`. IDs must be unique; an empty set is an error.
    /// This replaces a previous `with_sitemap` or `with_sitemaps` configuration.
    /// Siblings share the [index directory's scope](https://www.sitemaps.org/protocol.html#location);
    /// limits follow the [sitemap-index specification](https://www.sitemaps.org/protocol.html#index).
    ///
    /// ```
    /// use proa_framework_axum::{
    ///     DiscoveryError, FrameworkBuildError, FrameworkBuilder,
    ///     RobotsTxt, SitemapFile, SitemapUrl,
    /// };
    /// async fn generate_sitemaps() -> Result<Vec<SitemapFile>, DiscoveryError> {
    ///     // Application code can await database or CMS queries here.
    ///     Ok(vec![
    ///         SitemapFile::new("pages", [SitemapUrl::new("/")?])?,
    ///         SitemapFile::new("products-0", [SitemapUrl::new("/products/1")?])?,
    ///     ])
    /// }
    /// # let run = async move {
    /// let app = FrameworkBuilder::new()
    ///     .with_public_origin("https://example.com")?
    ///     .with_sitemaps(generate_sitemaps().await?)
    ///     .with_robots(RobotsTxt::new())
    ///     .try_build()?;
    /// # Ok::<(), FrameworkBuildError>(())
    /// # };
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run).unwrap();
    /// ```
    pub fn with_sitemaps(mut self, files: impl IntoIterator<Item = SitemapFile>) -> Self {
        self.sitemaps = Some(discovery::SitemapConfig::Multiple(
            files.into_iter().collect(),
        ));
        self
    }

    /// Serve `/robots.txt`, prefixing root-relative application rules using the
    /// final `with_base_path` (it replaces any base path already set on
    /// `robots`). Empty and wildcard-leading rules remain unchanged; a root rule
    /// also matches the bare mount URL. If a sitemap is enabled, advertise its
    /// public URL automatically.
    ///
    /// Crawlers still need this handler exposed at the origin root: a
    /// prefix-stripping proxy must explicitly forward origin-root `/robots.txt`.
    /// Do not also register a custom `/robots.txt` handler. Existing absolute
    /// sitemap links in `robots` pass through unchanged.
    /// Root routing follows [RFC 9309 §2.3](https://www.rfc-editor.org/rfc/rfc9309.html#section-2.3).
    /// Startup rejects documents exceeding [Google's 500 KiB limit](https://developers.google.com/crawling/docs/robots-txt/robots-txt-spec#file-format).
    ///
    /// Await an application-owned async function to generate rules from data.
    /// Generation and rendering run at startup; HTTP requests serve cached bytes.
    /// Shared user-agent groups, optional crawl delays, host, and custom
    /// directives are configured on `RobotsTxt` before passing it here.
    ///
    /// ```
    /// use proa_framework_axum::{
    ///     DiscoveryError, FrameworkBuildError, FrameworkBuilder, RobotsTxt,
    /// };
    /// use std::time::Duration;
    ///
    /// async fn generate_robots() -> Result<RobotsTxt, DiscoveryError> {
    ///     // Application code can await database or CMS queries here.
    ///     Ok(RobotsTxt::new()
    ///         .group("*")?.allow("/")?.disallow("/private/")?
    ///         .group_agents(["Applebot", "Bingbot"])?.disallow("/admin/")?
    ///         .crawl_delay(Duration::from_millis(1500)))
    /// }
    /// # let run = async {
    /// let app = FrameworkBuilder::new()
    ///     .with_robots(generate_robots().await?)
    ///     .try_build()?;
    /// # Ok::<(), FrameworkBuildError>(())
    /// # };
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run).unwrap();
    /// ```
    ///
    /// This configures the crawl-policy file, not page indexing metadata. Use
    /// `cx.head_mut().robots(proa_core::Robots { .. })` in a managed head hook
    /// for page-level `noindex`/preview directives. Crawlers must be allowed to
    /// fetch the page to read its HTML robots tag.
    pub fn with_robots(mut self, robots: RobotsTxt) -> Self {
        self.robots = Some(robots);
        self
    }

    /// Serve the linked RSJS modules under content-hashed names below
    /// `/_proa/immutable/rsjs/`, and link those names from every page.
    ///
    /// **ON by default.** Call this only to re-enable RSJS serving after
    /// [`without_rsjs_assets`](Self::without_rsjs_assets).
    pub fn with_rsjs_assets(mut self) -> Self {
        self.rsjs_assets = true;
        self
    }

    /// Disable automatic RSJS module serving and hashed URL linking.
    ///
    /// Use this only when an application serves its own copies of the RSJS
    /// runtime and island modules at their canonical paths (`/rsjs-runtime.js`
    /// and `/rsjs/island/<file>.js`).
    pub fn without_rsjs_assets(mut self) -> Self {
        self.rsjs_assets = false;
        self
    }

    /// Supply a catalog explicitly instead of loading the one from
    /// `PROA_PUBLIC_ASSETS` or beside the executable.
    /// This enables `cx.url("public/...")` in components.
    /// Handlers can also extract `axum::Extension<PublicAssets>`.
    /// Load it with the same `BasePath` used by this builder.
    /// The catalog owns routes under `/_proa/immutable` and `/_proa/mutable`.
    pub fn with_public_assets(mut self, assets: PublicAssets) -> Self {
        self.public_assets = Some(assets);
        self
    }

    /// Override the default 1 MiB request-body size limit. Returns the
    /// builder for chaining.
    ///
    /// ```rust,ignore
    /// FrameworkBuilder::new()
    ///     .with_body_limit(4 * 1024 * 1024) // 4 MiB
    ///     .build();
    /// ```
    pub fn with_body_limit(mut self, bytes: usize) -> Self {
        self.body_limit = Some(bytes);
        self
    }

    /// Enable or disable cross-origin protection (CSRF defense).
    ///
    /// **ON by default.** The built router rejects browser-issued
    /// cross-origin unsafe requests (POST, PUT, DELETE, ...) with 403
    /// based on the `Sec-Fetch-Site` header, falling back to comparing
    /// `Origin` against `Host` for older browsers. Safe methods and
    /// non-browser clients (no `Sec-Fetch-Site`, no `Origin`) always
    /// pass. See [`csrf::CrossOriginProtectionLayer`] for details.
    pub fn with_cross_origin_protection(mut self, enabled: bool) -> Self {
        self.cross_origin_protection = enabled;
        self
    }

    /// Trust an additional origin for cross-origin unsafe requests.
    ///
    /// `origin` is matched exactly against the `Origin` request header,
    /// so pass a serialized origin like `"https://app.example.com"`
    /// (scheme, host, optional port, no trailing slash).
    pub fn with_trusted_origin(mut self, origin: &str) -> Self {
        self.trusted_origins.push(origin.to_owned());
        self
    }

    /// Configure the security response headers applied to every
    /// response (frame options, HSTS, CSP). See
    /// [`SecurityHeadersConfig`] for the defaults.
    pub fn with_security_headers(mut self, config: SecurityHeadersConfig) -> Self {
        self.security_headers = config;
        self
    }

    /// Enable a strict, nonce-based `Content-Security-Policy`.
    ///
    /// **OFF by default**, because a strict policy has to match what the
    /// app's own markup loads. Turning it on mints a fresh 128-bit nonce per
    /// request, applies it to every Proa-emitted script tag (rsjs seed
    /// state and runtime tags, the streaming
    /// bootstrap, and out-of-order boundary swaps), and sends:
    ///
    /// ```text
    /// default-src 'self'; script-src 'nonce-…' 'strict-dynamic';
    /// style-src 'self' 'unsafe-inline'; object-src 'none';
    /// base-uri 'self'; frame-ancestors 'none'
    /// ```
    ///
    /// Note what this does *not* cover: raw `<script>` tags you write
    /// yourself still need an explicit `nonce` attribute (read the request
    /// nonce from `cx.csp_nonce()`), and inline event-handler attributes
    /// (`onclick="…"`) never run under a nonce policy.
    ///
    /// Use [`with_csp_policy`](Self::with_csp_policy) to adjust directives.
    pub fn with_strict_csp(mut self) -> Self {
        self.csp = Some(CspPolicy::strict());
        self
    }

    /// Enable a nonce-based CSP with a customized policy.
    ///
    /// ```rust,ignore
    /// FrameworkBuilder::new()
    ///     .with_csp_policy(
    ///         CspPolicy::strict()
    ///             .with_directive("img-src", "'self' data: https://cdn.example")
    ///             .report_only(true),
    ///     )
    ///     .build();
    /// ```
    ///
    /// `report_only(true)` sends `Content-Security-Policy-Report-Only`,
    /// which is the safe way to roll a strict policy out on a live app:
    /// violations are reported but nothing is blocked.
    pub fn with_csp_policy(mut self, policy: CspPolicy) -> Self {
        self.csp = Some(policy);
        self
    }

    /// Override the default 30 second request timeout
    /// ([`DEFAULT_REQUEST_TIMEOUT`]).
    ///
    /// The timeout bounds producing the response; streamed bodies keep
    /// flowing after the response head is out.
    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = Some(timeout);
        self
    }

    /// Disable the request timeout entirely. Prefer raising the timeout
    /// over removing it; without one, a stalled handler pins its
    /// resources until the client gives up.
    pub fn without_request_timeout(mut self) -> Self {
        self.request_timeout = None;
        self
    }

    /// Cap the number of in-flight requests across the whole router
    /// (off by default). Requests beyond `max` wait for a slot rather
    /// than being rejected, which keeps memory bounded under load
    /// spikes at the cost of added latency.
    pub fn with_concurrency_limit(mut self, max: usize) -> Self {
        self.concurrency_limit = Some(max);
        self
    }

    /// Opt in to `tower-http`'s `CatchPanicLayer` (off by default).
    ///
    /// When enabled, a panicking handler or middleware produces a plain
    /// `500 Internal Server Error` response instead of aborting the
    /// connection mid-stream. Panics are still logged; this only changes
    /// what the client observes. Left off by default so deployments that
    /// prefer crash-loud semantics (panic = bug = alert via connection
    /// reset) keep them.
    pub fn with_catch_panic(mut self, enabled: bool) -> Self {
        self.catch_panic = enabled;
        self
    }

    /// Configure the persistent executor used by local (`!Send`) renders,
    /// buffered or streamed.
    ///
    /// It defaults to one worker per CPU the process may use, like Tokio's
    /// own runtime. This is a joint server resource decision: deployments
    /// should account for these threads alongside Tokio's worker count.
    /// Stream admission and per-response transport limits bound streamed
    /// responses; bound buffered renders with
    /// [`with_concurrency_limit`](Self::with_concurrency_limit).
    pub fn with_local_stream_executor(mut self, config: LocalStreamExecutorConfig) -> Self {
        self.local_stream_executor = config;
        self
    }

    /// Serve application assets under `/static`. A configured base path also
    /// composes URL tokens in CSS and native URL operations in JS/MJS assets.
    /// Install compression outside this service so transformations see source bytes.
    pub fn with_static_service(mut self, service: Router) -> Self {
        self.static_router = Some(service);
        self
    }

    pub fn with_dynamic_routes(mut self, router: Router) -> Self {
        self.dynamic_router = Some(router);
        self
    }

    pub fn with_dynamic_routes_and_metadata(
        mut self,
        router: Router,
        metadata: Arc<HashMap<String, ComputedRouteMeta>>,
    ) -> Self {
        self.dynamic_router = Some(router);
        self.computed_metadata = Some(metadata);
        self
    }

    pub fn build(self) -> Router {
        self.try_build().expect("could not build framework router")
    }

    /// Build the router with its final base path and startup settings.
    ///
    /// Load and mount the public asset catalog unless one was supplied
    /// explicitly: the one `PROA_PUBLIC_ASSETS` names, or else the one
    /// `proa build` bundled beside this executable. Linked RSJS modules are
    /// also served under `/_proa/immutable/rsjs/` by default unless disabled
    /// with [`without_rsjs_assets`](Self::without_rsjs_assets). Invalid
    /// catalogs and discovery settings return an error. Axum's existing
    /// duplicate-route restrictions still apply.
    pub fn try_build(self) -> Result<Router, FrameworkBuildError> {
        let FrameworkBuilder {
            base_path,
            public_origin,
            head,
            sitemaps,
            robots,
            rsjs_assets,
            public_assets,
            static_router,
            dynamic_router,
            computed_metadata,
            body_limit,
            cross_origin_protection,
            trusted_origins,
            security_headers,
            csp,
            request_timeout,
            concurrency_limit,
            catch_panic,
            local_stream_executor,
        } = self;

        let body_limit_bytes = body_limit.unwrap_or(DEFAULT_BODY_LIMIT_BYTES);

        let mut app =
            discovery::discovery_routes(public_origin.as_deref(), &base_path, sitemaps, robots)?;
        let public_assets = match public_assets {
            Some(assets) => Some(assets),
            None => PublicAssets::from_env(&base_path)?,
        };
        let rsjs_assets = rsjs_assets
            .then(|| RsjsAssets::load(public_assets.as_ref()))
            .transpose()?;
        // Published files hosted on another origin have to be named wherever
        // an origin allowlist decides what a page may load.
        let asset_origin = public_assets
            .as_ref()
            .and_then(PublicAssets::asset_prefix)
            .and_then(AssetPrefix::origin)
            .map(str::to_owned);
        let csp = match (csp, &asset_origin) {
            (Some(policy), Some(origin)) => Some(policy.allow_asset_origin(origin)),
            (csp, _) => csp,
        };
        // The managed head resolves URLs against the mount. Files on an
        // asset host are complete as they are: another origin is allowed as a
        // resource origin, and a path on this origin is exempt from the mount.
        let asset_prefix = public_assets
            .as_ref()
            .and_then(PublicAssets::asset_prefix)
            .cloned();
        let head = match (head, asset_prefix) {
            (Some(mut head), Some(prefix)) => {
                if let Some(urls) = head.urls.take() {
                    let urls = Arc::unwrap_or_clone(urls);
                    let urls = match prefix.origin() {
                        Some(origin) => urls.allow_resource_origin(origin),
                        None => urls.allow_asset_path(prefix.as_str()),
                    }
                    .map_err(|_| {
                        PublicAssetError::AssetPrefix(InvalidAssetPrefix(
                            prefix.as_str().to_owned(),
                        ))
                    })?;
                    head.urls = Some(Arc::new(urls));
                }
                Some(head)
            }
            (head, _) => head,
        };
        if let Some(assets) = &rsjs_assets {
            app = app.merge(assets.router());
        }

        if let Some(static_router) = static_router {
            app = app.nest(
                "/static",
                base_path_assets(static_router, base_path.clone()),
            );
        }

        if let Some(dynamic_router) = dynamic_router {
            app = app.merge(dynamic_router);
        }

        let computed_metadata = computed_metadata.unwrap_or_else(|| Arc::new(HashMap::new()));
        let mut layer = RouteContextLayer::new(computed_metadata);
        if let Some(assets) = public_assets {
            app = assets.serve_root_files(app.merge(assets.router()));
            layer = layer.with_public_assets(assets);
        }
        if let Some(assets) = &rsjs_assets {
            layer = layer.with_rsjs_assets(assets);
        }
        let layer = layer
            .with_base_path(base_path)
            .with_local_stream_executor_config(local_stream_executor);
        let layer = if let Some(head) = head {
            layer.with_head(head)
        } else {
            layer
        };
        app = app.layer(layer);
        // Apply a global body-size limit so a single oversized POST cannot
        // tie up the worker indefinitely. Per-route overrides via
        // `DefaultBodyLimit::max(...)` on a nested router still apply.
        app = app.layer(DefaultBodyLimit::max(body_limit_bytes));
        // SECURITY: cross-origin protection (CSRF defense) is ON by
        // default; see the builder docs and `csrf` module.
        if cross_origin_protection {
            let mut csrf_layer = CrossOriginProtectionLayer::new();
            for origin in trusted_origins {
                csrf_layer = csrf_layer.with_trusted_origin(origin);
            }
            app = app.layer(csrf_layer);
        }
        // The timeout covers producing the response (routing, render),
        // not draining the body, so streaming SSR keeps working.
        if let Some(timeout) = request_timeout {
            app = app.layer(default_request_timeout_layer(timeout));
        }
        if let Some(max) = concurrency_limit {
            app = app.layer(GlobalConcurrencyLimitLayer::new(max));
        }
        if catch_panic {
            app = app.layer(CatchPanicLayer::new());
        }
        if let Some(policy) = &csp {
            // Both layers write `Content-Security-Policy` and neither
            // clobbers an existing header, so the inner one wins. Say so at
            // startup rather than letting a nonce-free policy silently
            // break hydration. A report-only policy writes a different
            // header, so it does not collide.
            if security_headers.content_security_policy.is_some() && !policy.is_report_only() {
                tracing::warn!(
                    "both with_security_headers(..with_content_security_policy(..)) and a \
                     nonce-based CSP are configured; the static policy is sent and the nonce \
                     directives are not. Keep only one."
                );
            }
            // A relaxed X-Frame-Options means the app expects to be framed,
            // which the CSP default of `frame-ancestors 'none'` would still
            // block in modern browsers. Report-only does not block anything.
            if security_headers.frame_options != FrameOptions::Deny
                && policy.frame_ancestors_is_default()
                && !policy.is_report_only()
            {
                tracing::warn!(
                    "X-Frame-Options is relaxed but the CSP still sends `frame-ancestors \
                     'none'`, which blocks framing anyway; set it with \
                     CspPolicy::with_directive(\"frame-ancestors\", ..)."
                );
            }
        }
        // Applied outside the CSRF, timeout, and panic layers so their
        // generated error responses also carry the security headers.
        app = app.layer(SecurityHeadersLayer::new(security_headers));
        // Outside everything else so every response (including timeout and
        // panic responses) carries the policy, and so the request nonce is
        // installed before `RouteContextLayer` reads it.
        if let Some(policy) = csp {
            app = app.layer(CspNonceLayer::new(policy));
        }
        Ok(app)
    }
}

// The root workspace currently resolves tower-http 0.6.6, where `new` is the
// only constructor. Downstream consumers may resolve 0.6.11, where it is
// deprecated in favor of `with_status_code`; keep the common source compatible
// with both until the root lockfile is upgraded.
#[allow(deprecated)]
fn default_request_timeout_layer(timeout: Duration) -> TimeoutLayer {
    TimeoutLayer::new(timeout)
}

/// Wrap a `ServeDir` for a filesystem mount with the framework's static
/// file hardening: `nosniff` so browsers never MIME-sniff a served file
/// into executable HTML/JS.
///
/// SECURITY: `tower-http`'s `ServeDir` rejects `..` path traversal but
/// FOLLOWS SYMLINKS inside the served directory, and tower-http 0.6.x
/// exposes no `follow_symlinks(false)` switch. Treat the served
/// directory as untrusted-content-free: never let untrusted writers
/// create files (or symlinks) under it, or a symlink pointing at, e.g.,
/// `/etc/passwd` would be served happily.
fn hardened_serve_dir(
    source_dir: std::path::PathBuf,
) -> tower_http::set_header::SetResponseHeader<ServeDir, HeaderValue> {
    SetResponseHeaderLayer::if_not_present(
        header::X_CONTENT_TYPE_OPTIONS,
        HeaderValue::from_static("nosniff"),
    )
    .layer(ServeDir::new(source_dir))
}

pub fn standalone_static_router(dir: &str) -> Router {
    // See `hardened_serve_dir` for the symlink and MIME-sniffing notes.
    // Axum 0.8 panics on `nest_service("/", ..)`; a fallback serves every path.
    Router::new().fallback_service(hardened_serve_dir(dir.into()))
}

pub use route::PageCache;