#![forbid(unsafe_code)]
pub mod bootstrap;
pub mod config;
pub mod csp;
pub mod csrf;
pub mod dev_reload;
pub mod external;
pub mod manifest;
pub mod process_manager;
pub mod proxy;
pub mod readiness;
pub mod route;
#[cfg(feature = "route-export")]
pub mod route_export;
pub mod security_headers;
pub mod server;
pub mod shard;
pub mod static_service;
pub use bootstrap::render_bootstrap_for_islands;
pub use config::{CodegenConfig, PathsConfig, ProaConfig, ServerConfig};
pub use csp::{CspNonceLayer, CspPolicy};
pub use csrf::CrossOriginProtectionLayer;
pub use dev_reload::{DevReloadLayer, RELOAD_PORT_ENV, RELOAD_TOKEN_ENV};
pub use external::{ExternalApp, ExternalAppStrategy};
pub use manifest::{
CssAsset, HydrationStrategyConfig, IslandEntry, IslandManifest, ManifestAssets, ProviderSpec,
};
pub use proa_core::CspNonce;
pub use readiness::{Readiness, DEFAULT_READINESS_TIMEOUT};
pub use route::{
css_asset_path, drive_dyn_render, drive_dyn_send_render, explicit_markdown,
explicit_markdown_async_with_loader, negotiate, negotiate_async_with_loader, render_css_link,
render_metadata_head, resolved_metadata, router_from_spec, CascadeOpenGraph, CascadeValue,
ComputedRouteMeta, DynRenderOutcome, DynSendRenderOutcome, DynWebRender, DynWebRenderSend,
Layout, LayoutRef, LocalStreamExecutorConfig, MarkdownAlternate, Metadata, MetadataRef,
OpenGraph, OpenGraphImage, OpenGraphMedia, PageCacheLayer, PageCacheService,
RepresentationResponse, ResolvedMetadata, ResolvedOpenGraphImage, ResolvedOpenGraphMedia,
Route, RouteContextLayer, RouteMode, RouteResponse, RouteSpec, StaticPathsFn,
};
pub use security_headers::{FrameOptions, SecurityHeadersConfig, SecurityHeadersLayer};
pub use server::{serve, serve_with_shutdown, ShutdownOutcome, DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT};
pub use shard::{ShardCache, ShardCacheConfig};
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, extract::Extension, 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;
pub const DEFAULT_BODY_LIMIT_BYTES: usize = 1024 * 1024;
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
pub struct FrameworkBuilder {
manifest: Arc<IslandManifest>,
config: ProaConfig,
static_router: Option<Router>,
dynamic_router: Option<Router>,
computed_metadata: Option<Arc<HashMap<String, ComputedRouteMeta>>>,
external_apps: Vec<ExternalApp>,
process_manager: process_manager::ProcessManager,
body_limit: Option<usize>,
cross_origin_protection: bool,
trusted_origins: Vec<String>,
security_headers: SecurityHeadersConfig,
csp: Option<CspPolicy>,
request_timeout: Option<Duration>,
concurrency_limit: Option<usize>,
catch_panic: bool,
local_stream_executor: LocalStreamExecutorConfig,
}
impl FrameworkBuilder {
pub fn new(manifest: IslandManifest) -> Self {
Self {
manifest: Arc::new(manifest),
config: ProaConfig::default(),
static_router: None,
dynamic_router: None,
computed_metadata: None,
external_apps: Vec::new(),
process_manager: process_manager::ProcessManager::new(),
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(),
}
}
pub fn with_body_limit(mut self, bytes: usize) -> Self {
self.body_limit = Some(bytes);
self
}
pub fn with_cross_origin_protection(mut self, enabled: bool) -> Self {
self.cross_origin_protection = enabled;
self
}
pub fn with_trusted_origin(mut self, origin: &str) -> Self {
self.trusted_origins.push(origin.to_owned());
self
}
pub fn with_security_headers(mut self, config: SecurityHeadersConfig) -> Self {
self.security_headers = config;
self
}
pub fn with_strict_csp(mut self) -> Self {
self.csp = Some(CspPolicy::strict());
self
}
pub fn with_csp_policy(mut self, policy: CspPolicy) -> Self {
self.csp = Some(policy);
self
}
pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = Some(timeout);
self
}
pub fn without_request_timeout(mut self) -> Self {
self.request_timeout = None;
self
}
pub fn with_concurrency_limit(mut self, max: usize) -> Self {
self.concurrency_limit = Some(max);
self
}
pub fn with_catch_panic(mut self, enabled: bool) -> Self {
self.catch_panic = enabled;
self
}
pub fn with_local_stream_executor(mut self, config: LocalStreamExecutorConfig) -> Self {
self.local_stream_executor = config;
self
}
pub fn with_config(mut self, config: ProaConfig) -> Self {
self.config = config;
self
}
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 with_external_app(mut self, external_app: ExternalApp) -> Self {
self.external_apps.push(external_app);
self
}
pub fn config(&self) -> &ProaConfig {
&self.config
}
pub fn build(self) -> Router {
let FrameworkBuilder {
manifest,
config,
static_router,
dynamic_router,
computed_metadata,
external_apps,
process_manager,
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 = Router::new();
for external_app in external_apps {
app = mount_external_app(
app,
external_app,
&config,
&process_manager,
body_limit_bytes,
);
}
if let Some(static_router) = static_router {
app = app.nest("/static", static_router);
}
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 layer = RouteContextLayer::new(manifest.clone(), computed_metadata)
.with_local_stream_executor_config(local_stream_executor);
app = app.layer(layer);
app = app.layer(DefaultBodyLimit::max(body_limit_bytes));
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);
}
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 {
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."
);
}
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\", ..)."
);
}
}
app = app.layer(SecurityHeadersLayer::new(security_headers));
if let Some(policy) = csp {
app = app.layer(CspNonceLayer::new(policy));
}
app.layer(Extension(manifest))
}
}
#[allow(deprecated)]
fn default_request_timeout_layer(timeout: Duration) -> TimeoutLayer {
TimeoutLayer::new(timeout)
}
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))
}
fn mount_external_app(
router: Router,
external_app: ExternalApp,
_config: &ProaConfig,
process_manager: &process_manager::ProcessManager,
body_limit_bytes: usize,
) -> Router {
use external::ExternalAppStrategy;
let mount_path = external_app.mount_path;
let is_dev = cfg!(debug_assertions);
match external_app.strategy {
ExternalAppStrategy::Static {
source_dir,
spa_fallback,
} => {
if spa_fallback {
tracing::warn!("SPA fallback for {} not yet fully implemented", mount_path);
}
let service = hardened_serve_dir(source_dir);
router.nest_service(&mount_path, service)
}
ExternalAppStrategy::Csr {
source_dir,
dev_upstream,
} => {
if is_dev && dev_upstream.is_some() {
tracing::warn!(
"Dev proxy for CSR app at {} not yet implemented, serving from {}",
mount_path,
source_dir.display()
);
}
let service = hardened_serve_dir(source_dir);
router.nest_service(&mount_path, service)
}
ExternalAppStrategy::Ssr {
upstream,
dev_command,
health_check,
strip_prefix,
} => {
tracing::info!(
"Mounting SSR app at {} → {} (strip_prefix: {})",
mount_path,
upstream,
strip_prefix
);
if is_dev {
if let Some(cmd) = dev_command {
tracing::info!("Spawning dev server for {}: {}", mount_path, cmd);
if let Err(e) = process_manager.spawn(mount_path.clone(), cmd) {
tracing::error!("Failed to spawn dev server for {}: {}", mount_path, e);
tracing::warn!(
"Continuing without dev server - make sure upstream {} is running",
upstream
);
}
if let Some(health_url) = health_check {
tracing::info!("Waiting for dev server at {} to be ready...", health_url);
tracing::warn!("Health check synchronization not yet implemented - continuing without wait");
}
}
}
let proxy_config = std::sync::Arc::new(
crate::proxy::ProxyConfig::new(upstream.clone(), strip_prefix, mount_path.clone())
.with_max_request_body_bytes(body_limit_bytes),
);
let proxy_router = axum::Router::new()
.fallback(crate::proxy::proxy_handler)
.with_state(proxy_config);
router.nest(&mount_path, proxy_router)
}
}
}
pub fn standalone_static_router(dir: &str) -> Router {
Router::new().nest_service("/", hardened_serve_dir(dir.into()))
}
pub use route::PageCache;