Skip to main content

renox_core/
app.rs

1use std::collections::HashMap;
2use std::future::Future;
3use std::net::SocketAddr;
4use std::sync::Arc;
5use std::time::Duration;
6
7use anyhow::anyhow;
8use axum::Router;
9use axum::handler::HandlerWithoutStateExt;
10use axum::middleware::{from_fn, from_fn_with_state};
11use tokio::net::TcpListener;
12use tokio::sync::watch;
13use tower_http::services::ServeDir;
14use tower_http::trace::TraceLayer;
15use tracing_subscriber::EnvFilter;
16
17use crate::auth::{Gate, LoginThrottle, User};
18use crate::crypto::parse_key;
19use crate::db::{Db, Migration, MigrationStatus, Migrator};
20use crate::events::Event;
21use crate::mail::Mailer;
22use crate::queue::{Handlers, Job, Queue, Worker};
23use crate::routing::RouteInfo;
24use crate::schedule::Schedule;
25use crate::timezone::Zone;
26use crate::{
27    AppState, Config, Environment, Error, Module, Registry, Result, RouteTable, Views, assets,
28    auth, csrf, session, view,
29};
30
31/// How long `serve` waits for running jobs after a shutdown signal.
32const SHUTDOWN_GRACE: Duration = Duration::from_secs(30);
33
34const USAGE: &str = "\
35Usage: <app> [command]
36
37Commands:
38  serve                     Start the web server, queue workers and scheduler (default)
39  migrate                   Run pending migrations
40  migrate:rollback [--step N]
41                            Undo the last N batches of migrations (default 1)
42  migrate:fresh [--seed]    Drop all tables, run every migration, optionally seed
43  migrate:status            List migrations and whether they have run
44  db:check                  Compare the registered models with the tables the migrations build
45  db:diff [name] [--yes]    Write a migration for what changed in the registered models
46  db:seed                   Run the seeders
47  queue:work [--queue a,b] [--workers N] [--once]
48                            Run queued jobs (until stopped, or --once for what's there)
49  queue:failed              List failed jobs
50  queue:retry <id|all>      Put failed jobs back on the queue
51  queue:flush               Delete failed jobs
52  queue:forget <id>         Delete one failed job
53  queue:prune-failed [--hours N]
54                            Delete failed jobs older than N hours (default 168)
55  queue:prune-batches [--hours N]
56                            Delete batches finished more than N hours ago (default 24)
57  webhook:failed            List webhook calls whose processing failed
58  webhook:retry <id>        Process a stored webhook call again
59  webhook:endpoints         List the outbound webhook endpoints
60  webhook:deliveries [--endpoint N] [--failed]
61                            List outbound webhook deliveries, newest first
62  webhook:redeliver <id>    Send a stored outbound delivery again
63  webhook:prune-deliveries [--days N]
64                            Delete deliveries older than N days (default 30)
65  ui:publish [--force]      Copy the UI kit (renox/ui.html and its CSS) into the app to change it
66  sequence:list             List the numbering series (`Sequence`) and their last numbers
67  cache:prune               Delete expired rows of the database cache store
68  session:prune             Delete expired sessions (SESSION_DRIVER=database)
69  idempotency:prune [--days N]
70                            Delete offline-form keys older than N days (default 7)
71  import:prune [--days N]   Delete the records of imports whose undo window ended N days ago (default 0)
72  schedule:list             List scheduled tasks and when they run next
73  schedule:run <task>       Run one scheduled task now
74  schedule:work             Run scheduled tasks (when SCHEDULER=false for serve)
75  route:list                List every route with its name, module and guards
76  view:check                Compile every template; check route names and typed views
77  state:diagram [Model]    Print a state machine as a Mermaid diagram (no name: list them)
78  view:data [--out P]       Write .vscode/renox-components.json for editor autocomplete
79  db:shell                  Run SQL against the database (`.tables`, `.quit`)
80  down [--secret S] [--retry N]
81                            Maintenance mode: answer 503 (visit /S to bypass it)
82  up                        Leave maintenance mode
83  help                      Show this message";
84
85/// The application builder.
86///
87/// ```no_run
88/// # use renox::prelude::*;
89/// # use serde::{Deserialize, Serialize};
90/// # struct Products;
91/// # impl Module for Products { fn name(&self) -> &'static str { "products" } }
92/// # #[derive(Serialize, Deserialize)] struct SendReceipt;
93/// # impl Job for SendReceipt { const NAME: &'static str = "send-receipt"; async fn handle(self, _: JobContext) -> Result { Ok(()) } }
94/// # async fn cleanup(_: AppState) -> Result { Ok(()) }
95/// # async fn seed(_: AppState) -> Result { Ok(()) }
96/// fn main() -> renox::Result {
97///     App::new()
98///         .migrations(renox::migrations!())
99///         .module(Products)
100///         .job::<SendReceipt>()
101///         .schedule(|s| { s.daily_at("02:00", "cleanup", cleanup); })
102///         .seeder(seed)
103///         .run()
104/// }
105/// ```
106///
107/// The built binary is also the app's command line, like Laravel's artisan:
108/// `my-app migrate`, `my-app queue:work`, `my-app help`.
109pub struct App {
110    config: Option<Config>,
111    modules: Vec<Box<dyn Module>>,
112    migrations: Vec<Migration>,
113    gates: HashMap<String, Gate>,
114    async_gates: HashMap<String, crate::auth::AsyncGate>,
115    gate_before: Option<crate::auth::GateBefore>,
116    registry: Registry,
117    embedded: Option<crate::Embedded>,
118    csp: crate::security::Csp,
119    permissions_policy: crate::security::PermissionsPolicy,
120    provided: HashMap<std::any::TypeId, Arc<dyn std::any::Any + Send + Sync>>,
121    layers: Vec<AppLayer>,
122    limiters: HashMap<String, crate::rate_limit::LimitRule>,
123    detect_locale: bool,
124    rtl_locales: Option<Vec<String>>,
125    disks: Vec<(String, DiskSettings)>,
126    uploads: crate::upload::Pipeline,
127    mailers: Vec<(String, MailerSettings)>,
128    mailer_limits: HashMap<String, crate::queue::Limit>,
129    xsrf_cookie: bool,
130    settings_seed: Option<std::path::PathBuf>,
131    theme: Option<crate::theme::Theme>,
132    theme_chooser: Option<crate::theme::ThemeFn>,
133    pwa: Option<crate::pwa::Pwa>,
134    pwa_chooser: Option<crate::pwa::PwaFn>,
135}
136
137/// How `App::mailer` gets a mailer's settings once the configuration is loaded.
138type MailerSettings = Box<dyn Fn(&Config) -> Result<crate::mail::MailConfig> + Send + Sync>;
139
140/// How `App::disk` gets a disk's settings once the configuration is loaded.
141type DiskSettings = Box<dyn Fn(&Config) -> Result<crate::storage::StorageConfig> + Send + Sync>;
142
143/// A layer from `App::layer`, applied to the app's routes at boot.
144/// Applied to the app's router and to each `Routes::domain` router.
145type AppLayer = Box<dyn Fn(Router<AppState>) -> Router<AppState> + Send + Sync>;
146
147impl App {
148    /// Creates an application that loads its configuration from `.env` on start.
149    pub fn new() -> Self {
150        Self {
151            config: None,
152            modules: Vec::new(),
153            migrations: Vec::new(),
154            gates: HashMap::new(),
155            async_gates: HashMap::new(),
156            gate_before: None,
157            registry: Registry::default(),
158            embedded: None,
159            csp: crate::security::Csp::default(),
160            permissions_policy: crate::security::PermissionsPolicy::default(),
161            provided: HashMap::new(),
162            layers: Vec::new(),
163            limiters: HashMap::new(),
164            detect_locale: false,
165            rtl_locales: None,
166            disks: Vec::new(),
167            uploads: crate::upload::Pipeline::new(),
168            mailers: Vec::new(),
169            mailer_limits: HashMap::new(),
170            xsrf_cookie: false,
171            settings_seed: None,
172            theme: None,
173            theme_chooser: None,
174            pwa: None,
175            pwa_chooser: None,
176        }
177    }
178
179    /// Picks a visitor's language from their browser (`Accept-Language`)
180    /// when they haven't chosen one: the first of their languages this app
181    /// has texts for (the built-in `en` and `id`, or a
182    /// `resources/lang/<locale>.json`), else `APP_LOCALE`. A language set
183    /// with `i18n::remember_locale` still wins. Responses then carry
184    /// `Vary: Accept-Language`, so caches keep the languages apart.
185    ///
186    /// ```
187    /// # use renox::prelude::*;
188    /// # let _ =
189    /// App::new().detect_locale()
190    /// # ;
191    /// ```
192    pub fn detect_locale(mut self) -> Self {
193        self.detect_locale = true;
194        self
195    }
196
197    /// Replaces the languages written right to left (by default Arabic,
198    /// Hebrew, Persian, Urdu, Pashto, Yiddish, Divehi and Central Kurdish)
199    /// with `locales`, matched by base language (`ar` covers `ar-AE`).
200    /// `AppState::direction` then answers from this list.
201    ///
202    /// ```
203    /// # use renox::prelude::*;
204    /// # let _ =
205    /// App::new().rtl_locales(&["ar", "he"])
206    /// # ;
207    /// ```
208    pub fn rtl_locales(mut self, locales: &[&str]) -> Self {
209        self.rtl_locales = Some(locales.iter().map(|l| (*l).to_owned()).collect());
210        self
211    }
212
213    /// Wraps every route of the app's modules in a tower layer, e.g. a
214    /// middleware function (framework routes such as `/health` and
215    /// `public/` files aren't wrapped). It runs after Renox has loaded the
216    /// session and the user, so it can use `AuthUser` or `Session`:
217    ///
218    /// ```
219    /// # use renox::prelude::*;
220    /// use renox::axum::extract::Request;
221    /// use renox::axum::middleware::{Next, from_fn};
222    ///
223    /// async fn stamp(user: Option<AuthUser>, req: Request, next: Next) -> Response {
224    ///     let mut res = next.run(req).await;
225    ///     let who = if user.is_some() { "member" } else { "guest" };
226    ///     res.headers_mut().insert("x-visitor", who.parse().unwrap());
227    ///     res
228    /// }
229    ///
230    /// # let _ =
231    /// App::new().layer(from_fn(stamp))
232    /// # ;
233    /// ```
234    ///
235    /// Layers run in the order added: the first one sees the request first.
236    pub fn layer<L>(mut self, layer: L) -> Self
237    where
238        L: tower::Layer<axum::routing::Route> + Clone + Send + Sync + 'static,
239        L::Service: tower::Service<axum::extract::Request> + Clone + Send + Sync + 'static,
240        <L::Service as tower::Service<axum::extract::Request>>::Response:
241            axum::response::IntoResponse + 'static,
242        <L::Service as tower::Service<axum::extract::Request>>::Error:
243            Into<std::convert::Infallible> + 'static,
244        <L::Service as tower::Service<axum::extract::Request>>::Future: Send + 'static,
245    {
246        self.layers
247            .push(Box::new(move |router| router.layer(layer.clone())));
248        self
249    }
250
251    /// Allows other sites in the Content-Security-Policy, e.g.
252    /// `.csp(|csp| { csp.allow("script-src", "https://www.googletagmanager.com"); })`.
253    pub fn csp(mut self, allow: impl FnOnce(&mut crate::security::Csp)) -> Self {
254        allow(&mut self.csp);
255        self
256    }
257
258    /// Allows browser features in the `Permissions-Policy`, which switches off
259    /// the ones a typical app never uses (camera, microphone, geolocation,
260    /// payment, USB…): `.permissions_policy(|p| { p.allow("geolocation", "self"); })`.
261    /// A feature can be allowed for `self`, for an origin
262    /// (`"https://pay.example.com"`) or for everyone (`"*"`). `PERMISSIONS_POLICY`
263    /// in `.env` sets the base: `default`, `off` or a full header value.
264    ///
265    /// ```
266    /// # use renox::prelude::*;
267    /// # let _ =
268    /// App::new().permissions_policy(|p| {
269    ///     p.allow("camera", "self");
270    /// })
271    /// # ;
272    /// ```
273    pub fn permissions_policy(
274        mut self,
275        allow: impl FnOnce(&mut crate::security::PermissionsPolicy),
276    ) -> Self {
277        allow(&mut self.permissions_policy);
278        self
279    }
280
281    /// Views, translations and public files compiled into the binary:
282    /// `.embed(renox::embedded!())`. They're used when `APP_DEBUG` is off;
283    /// while debugging, files are read from disk so edits show up at once.
284    pub fn embed(mut self, embedded: crate::Embedded) -> Self {
285        self.embedded = Some(embedded);
286        self
287    }
288
289    /// Uses the given configuration instead of loading it from the environment.
290    pub fn with_config(config: Config) -> Self {
291        Self {
292            config: Some(config),
293            ..Self::new()
294        }
295    }
296
297    /// Replaces the configuration, e.g. in tests.
298    pub fn config(mut self, config: Config) -> Self {
299        self.config = Some(config);
300        self
301    }
302
303    /// Adds a module: its routes, migrations and registrations.
304    pub fn module(mut self, module: impl Module) -> Self {
305        self.modules.push(Box::new(module));
306        self
307    }
308
309    /// Registers app-level migrations, usually `renox::migrations!()`.
310    pub fn migrations(mut self, migrations: &[Migration]) -> Self {
311        self.migrations.extend_from_slice(migrations);
312        self
313    }
314
315    /// Registers a seeder for `db:seed`. Seeders run in registration order
316    /// (the app's, then each module's from `Registry::seeder`, in the order
317    /// the modules were added), in the app's context (model hooks and `renox::context::app()` see
318    /// it), and get the app's state: `state.db`, its config, storage…
319    ///
320    /// ```
321    /// # use renox::prelude::*;
322    /// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64 }
323    /// # impl Factory for Product { fn definition() -> Self { Product::default() } }
324    /// # let _ =
325    /// App::new().seeder(|state| async move {
326    ///     Product::factory().count(50).create(&state.db).await?;
327    ///     Ok(())
328    /// })
329    /// # ;
330    /// ```
331    pub fn seeder<F, Fut>(mut self, seeder: F) -> Self
332    where
333        F: Fn(AppState) -> Fut + Send + Sync + 'static,
334        Fut: Future<Output = Result> + Send + 'static,
335    {
336        self.registry.seeder(seeder);
337        self
338    }
339
340    /// Defines a gate: an ability that depends only on the user.
341    ///
342    /// ```
343    /// # use renox::prelude::*;
344    /// # let _ =
345    /// App::new().gate("admin", |user| user.email.ends_with("@shop.example"))
346    /// // in a handler: auth.gate("admin")?;   in a template: {% if can('admin') %}
347    /// # ;
348    /// ```
349    pub fn gate(
350        mut self,
351        name: &str,
352        check: impl Fn(&User) -> bool + Send + Sync + 'static,
353    ) -> Self {
354        self.gates.insert(name.to_owned(), Arc::new(check));
355        self
356    }
357
358    /// A gate that may query the database, e.g. whether the user belongs to
359    /// a team. Check it in handlers with `auth.gate_async(name).await?`;
360    /// templates can't wait for it (`can()` denies it), so pass its answer in
361    /// the view's context.
362    ///
363    /// ```
364    /// # use renox::prelude::*;
365    /// # let _ =
366    /// App::new().gate_async("billing", |user, state| async move {
367    ///     let n: i64 = renox::db::sql("SELECT COUNT(*) FROM team_admins WHERE user_id = ?")
368    ///         .bind(user.id)
369    ///         .scalar(&state.db)
370    ///         .await?;
371    ///     Ok(n > 0)
372    /// })
373    /// // in a handler: auth.gate_async("billing").await?;
374    /// # ;
375    /// ```
376    /// Asked before every gate, permission and policy check: `Some(true)`
377    /// allows, `Some(false)` denies, `None` goes on to the check itself.
378    /// Typically lets super-admins do everything.
379    ///
380    /// ```
381    /// # use renox::prelude::*;
382    /// # let _ =
383    /// App::new().gate_before(|user, _ability| {
384    ///     (user.get::<String>("role").as_deref() == Some("owner")).then_some(true)
385    /// })
386    /// # ;
387    /// ```
388    pub fn gate_before(
389        mut self,
390        check: impl Fn(&User, &str) -> Option<bool> + Send + Sync + 'static,
391    ) -> Self {
392        self.gate_before = Some(Arc::new(check));
393        self
394    }
395
396    /// Defines the gate `name` with a check that can await, e.g. to query
397    /// the database. `can(name)` and `require_gate` ask it like any gate.
398    pub fn gate_async<F, Fut>(mut self, name: &str, check: F) -> Self
399    where
400        F: Fn(User, AppState) -> Fut + Send + Sync + 'static,
401        Fut: Future<Output = Result<bool>> + Send + 'static,
402    {
403        self.async_gates.insert(
404            name.to_owned(),
405            Arc::new(move |user, state| Box::pin(check(user, state))),
406        );
407        self
408    }
409
410    /// Receives `W`'s webhooks: see `renox::webhook`. Also add the route
411    /// with `Routes::webhook::<W>(path)`.
412    pub fn webhook<W: crate::webhook::Webhook>(mut self) -> Self {
413        self.registry.webhook::<W>();
414        self
415    }
416
417    /// Registers a model for `db:check`, which compares its fields with the
418    /// table. Registering it twice keeps one.
419    ///
420    /// ```
421    /// # use renox::prelude::*;
422    /// # #[derive(Model, serde::Serialize, Default)] struct Product { id: i64 }
423    /// let app = App::new().model::<Product>();
424    /// ```
425    pub fn model<M: crate::db::Model>(mut self) -> Self {
426        self.registry.model::<M>();
427        self
428    }
429
430    /// Registers `M`'s state machine by name, so `rnx state:diagram Order` and
431    /// the admin panel can find it, and the model for `db:check`.
432    pub fn state_machine<M: crate::state_machine::StateMachine>(mut self) -> Self {
433        self.registry.model::<M>();
434        crate::state_machine::register::<M>();
435        self
436    }
437
438    /// Registers a page struct for `view:check`, which then reports the variables its
439    /// template uses that the struct lacks; see [`crate::ViewData`]. Registering it twice
440    /// keeps one.
441    ///
442    /// ```
443    /// # use renox::prelude::*;
444    /// #[derive(serde::Serialize, ViewData)]
445    /// #[view(template = "suppliers/index.html")]
446    /// struct SupplierList { suppliers: Vec<String> }
447    ///
448    /// let app = App::new().view_data::<SupplierList>();
449    /// ```
450    pub fn view_data<T: crate::ViewData>(mut self) -> Self {
451        self.registry.view_data::<T>();
452        self
453    }
454
455    /// Registers the live component `C` (see `renox::live_component`).
456    pub fn live_component<C: crate::live_component::LiveComponent>(mut self) -> Self {
457        self.registry.live_component::<C>();
458        self
459    }
460
461    /// Lets queue workers run jobs of type `J`.
462    pub fn job<J: Job>(mut self) -> Self {
463        self.registry.job::<J>();
464        self
465    }
466
467    /// Makes `E` a webhook event named `name`; see
468    /// [`Registry::webhook_event`].
469    pub fn webhook_event<E: Event>(
470        mut self,
471        name: &str,
472        map: impl Fn(&E) -> serde_json::Value + Send + Sync + 'static,
473    ) -> Self {
474        self.registry.webhook_event(name, map);
475        self
476    }
477
478    /// Runs `listener` whenever an `E` is emitted with `state.emit(..)`.
479    pub fn listen<E, F, Fut>(mut self, listener: F) -> Self
480    where
481        E: Event,
482        F: Fn(E, AppState) -> Fut + Send + Sync + 'static,
483        Fut: Future<Output = Result> + Send + 'static,
484    {
485        self.registry.listen(listener);
486        self
487    }
488
489    /// Declares a group of settings kept in the database; see
490    /// [`crate::settings`] and [`Registry::settings`]. Needs
491    /// `App::module(Settings)`.
492    pub fn settings<T: crate::settings::SettingsGroup>(mut self) -> Self {
493        self.registry.settings::<T>();
494        self
495    }
496
497    /// Declares a group of settings like [`App::settings`] and gives every
498    /// view its values as `settings.<key>` (`settings.company.name`); see
499    /// [`Registry::settings_in_views`].
500    pub fn settings_in_views<T: crate::settings::SettingsGroup>(mut self) -> Self {
501        self.registry.settings_in_views::<T>();
502        self
503    }
504
505    /// Seeds declared settings groups from a JSON file of groups
506    /// (`{"company": {"name": "Acme"}}`) the first time each is read: a
507    /// deploy tool drops the file, and the app starts with those values.
508    /// Values already in the table win, and a missing file seeds nothing.
509    /// The seeded values are validated like any save.
510    pub fn settings_from(mut self, path: impl Into<std::path::PathBuf>) -> Self {
511        self.settings_seed = Some(path.into());
512        self
513    }
514
515    /// Adds a command the app binary runs: `my-app <name> [args]`, e.g. to
516    /// create the first admin or run an import. See [`crate::command`].
517    pub fn command<F, Fut>(mut self, name: &str, about: &str, run: F) -> Self
518    where
519        F: Fn(crate::command::Args, AppState) -> Fut + Send + Sync + 'static,
520        Fut: Future<Output = Result> + Send + 'static,
521    {
522        self.registry.command(name, about, run);
523        self
524    }
525
526    /// A command whose arguments are declared with clap; see
527    /// [`AppCommand`](crate::command::AppCommand).
528    pub fn typed_command<T: crate::command::AppCommand>(mut self) -> Self {
529        self.registry.typed_command::<T>();
530        self
531    }
532
533    /// A named rate limit for `Routes::throttle_by(name)`, whose `rule`
534    /// picks the limit for each request (by user, role, IP, API key…); see
535    /// [`crate::rate_limit::Limit`].
536    pub fn rate_limiter(
537        mut self,
538        name: &str,
539        rule: impl Fn(&crate::rate_limit::LimitRequest) -> crate::rate_limit::Limit
540        + Send
541        + Sync
542        + 'static,
543    ) -> Self {
544        self.limiters
545            .insert(name.to_owned(), std::sync::Arc::new(rule));
546        self
547    }
548
549    /// Sends every error that needs a person (a 500, a job that failed for
550    /// good, a failed scheduled task) to `reporter`, e.g. an error tracker;
551    /// see [`crate::report`].
552    pub fn report<F, Fut>(mut self, reporter: F) -> Self
553    where
554        F: Fn(crate::report::ErrorReport, AppState) -> Fut + Send + Sync + 'static,
555        Fut: Future<Output = ()> + Send + 'static,
556    {
557        self.registry.report(reporter);
558        self
559    }
560
561    /// Adds a notification channel (WhatsApp, SMS, Slack…); see
562    /// [`Registry::channel`].
563    pub fn channel<F, Fut>(mut self, name: &str, send: F) -> Self
564    where
565        F: Fn(crate::auth::Recipient, serde_json::Value, AppState) -> Fut + Send + Sync + 'static,
566        Fut: Future<Output = Result> + Send + 'static,
567    {
568        self.registry.channel(name, send);
569        self
570    }
571
572    /// Caps how fast the app's own queued deliveries to the channel `name`
573    /// go out; see [`Registry::channel_rate_limit`]. It is a separate call
574    /// (not chained on `channel`), so it works in any order.
575    ///
576    /// ```
577    /// # use renox::prelude::*;
578    /// # use std::time::Duration;
579    /// # let _ =
580    /// App::new()
581    ///     .channel("sms", |_to, _message, _state| async { Ok(()) })
582    ///     .channel_rate_limit("sms", 20, Duration::from_secs(1))
583    /// # ;
584    /// ```
585    pub fn channel_rate_limit(mut self, name: &str, max: u32, per: std::time::Duration) -> Self {
586        self.registry.channel_rate_limit(name, max, per);
587        self
588    }
589
590    /// Caps how fast queued mail (`queue_mail`, `queue_mail_via`, queued
591    /// notifications) goes out through the mailer `name`: at most `max` per
592    /// `per`, shared by every worker. `"default"` is the app's default
593    /// mailer. A mail over the limit waits for the next window without
594    /// using up an attempt. An unknown mailer is an error when the app boots.
595    ///
596    /// ```
597    /// # use renox::prelude::*;
598    /// use renox::mail::MailConfig;
599    /// # use std::time::Duration;
600    /// # let _ =
601    /// App::new()
602    ///     .mailer("bulk", |config| MailConfig::from_env(config, "BULK"))
603    ///     .mailer_rate_limit("bulk", 100, Duration::from_secs(60))
604    /// # ;
605    /// ```
606    pub fn mailer_rate_limit(mut self, name: &str, max: u32, per: std::time::Duration) -> Self {
607        self.mailer_limits
608            .insert(name.to_owned(), crate::queue::Limit::new(max, per));
609        self
610    }
611
612    /// Also sends the CSRF token as an `XSRF-TOKEN` cookie that scripts can
613    /// read, and accepts it back in an `X-XSRF-TOKEN` header (Laravel's
614    /// behaviour), for a JavaScript client on the same site: axios sends
615    /// it by itself. Forms and htmx don't need it; they send `_token` or
616    /// `X-CSRF-Token`.
617    pub fn xsrf_cookie(mut self) -> Self {
618        self.xsrf_cookie = true;
619        self
620    }
621
622    /// Adds a mailer named `name`, e.g. a provider for newsletters or a
623    /// second SMTP account, used with `state.mailer_named(name)` or, by
624    /// listing it in `MAIL_FAILOVER`, when the default mailer fails.
625    /// `settings` runs once the configuration is loaded;
626    /// [`MailConfig::from_env`] reads `<PREFIX>_MAILER`, `_HOST`, …
627    ///
628    /// ```
629    /// # use renox::prelude::*;
630    /// use renox::mail::MailConfig;
631    ///
632    /// # let _ =
633    /// // BACKUP_HOST=smtp.other-provider.com, BACKUP_USERNAME=…; MAIL_FAILOVER=backup
634    /// App::new().mailer("backup", |config| MailConfig::from_env(config, "BACKUP"))
635    /// # ;
636    /// ```
637    ///
638    /// [`MailConfig::from_env`]: crate::mail::MailConfig::from_env
639    pub fn mailer(
640        mut self,
641        name: &str,
642        settings: impl Fn(&Config) -> Result<crate::mail::MailConfig> + Send + Sync + 'static,
643    ) -> Self {
644        self.mailers.push((name.to_owned(), Box::new(settings)));
645        self
646    }
647
648    /// Adds a storage disk named `name` (letters, digits, `-`, `_`), e.g.
649    /// backups on another bucket, read with `state.disk_named(name)`. `settings`
650    /// runs once the configuration is loaded; [`StorageConfig::from_env`]
651    /// reads `<PREFIX>_DISK`, `<PREFIX>_BUCKET`, … A local disk keeps its
652    /// files in `STORAGE_PATH/<name>` unless its settings say otherwise.
653    ///
654    /// ```
655    /// # use renox::prelude::*;
656    /// use renox::storage::StorageConfig;
657    ///
658    /// # let _ =
659    /// App::new()
660    ///     .disk("backups", |config| StorageConfig::from_env(config, "BACKUPS"))
661    ///     .disk("exports", |_| Ok(StorageConfig::default())) // local: storage/exports
662    /// # ;
663    /// ```
664    ///
665    /// [`StorageConfig::from_env`]: crate::storage::StorageConfig::from_env
666    pub fn disk(
667        mut self,
668        name: &str,
669        settings: impl Fn(&Config) -> Result<crate::storage::StorageConfig> + Send + Sync + 'static,
670    ) -> Self {
671        self.disks.push((name.to_owned(), Box::new(settings)));
672        self
673    }
674
675    /// The steps every uploaded file passes after the form's rules and
676    /// before the handler sees it: a malware scan, image processing, your own
677    /// [`UploadStep`](crate::upload::UploadStep)s. See [`crate::upload`].
678    ///
679    /// ```
680    /// # use renox::prelude::*;
681    /// use renox::upload::{ClamAv, Pipeline};
682    ///
683    /// # let _ =
684    /// App::new().uploads(Pipeline::new().step(ClamAv::tcp("127.0.0.1:3310")))
685    /// # ;
686    /// ```
687    pub fn uploads(mut self, pipeline: crate::upload::Pipeline) -> Self {
688        self.uploads = pipeline;
689        self
690    }
691
692    /// Makes `value` available everywhere the app runs: `Provided<T>` in
693    /// handlers, `state.provided::<T>()` in jobs, listeners, commands and
694    /// scheduled tasks. One value per type; a second one replaces the first,
695    /// and it wins over a module's ([`Registry::provide`]). See
696    /// [`crate::Provided`].
697    pub fn provide<T: Send + Sync + 'static>(mut self, value: T) -> Self {
698        self.provided
699            .insert(std::any::TypeId::of::<T>(), Arc::new(value));
700        self
701    }
702
703    /// Gives the app one brand: its accent tokens are served as a hashed,
704    /// cacheable stylesheet that `<rx-theme/>` links after `<rx-ui/>`.
705    ///
706    /// ```
707    /// # use renox::prelude::*;
708    /// use renox::theme::{Brand, Theme};
709    /// let theme = Theme::from_brand(&Brand::new("#0F766E")).unwrap();
710    /// # let _ =
711    /// App::new().theme(theme)
712    /// # ;
713    /// ```
714    pub fn theme(mut self, theme: crate::theme::Theme) -> Self {
715        self.theme = Some(theme);
716        self
717    }
718
719    /// Makes the app installable on phones: serves `/manifest.webmanifest`,
720    /// the service worker `/sw.js`, the offline page `/_renox/offline` and
721    /// the icons, all outside sessions (no cookie is set). A
722    /// `public/manifest.webmanifest` or `public/sw.js` replaces the
723    /// generated one. Booting fails when an icon file is missing or the
724    /// offline view doesn't render.
725    ///
726    /// ```
727    /// use renox::prelude::*;
728    /// use renox::pwa::Pwa;
729    /// # let _ =
730    /// App::new().pwa(Pwa::new("Bikeshop").icons("public/icons"))
731    /// # ;
732    /// ```
733    pub fn pwa(mut self, pwa: crate::pwa::Pwa) -> Self {
734        self.pwa = Some(pwa);
735        self
736    }
737
738    /// Picks the brand per request, e.g. by host. Return `Ok(None)` to use
739    /// the app's [`theme`](App::theme) (or the kit's look when there is none);
740    /// an `Err` is logged and falls back the same way. It runs for every
741    /// rendered page, so build each `Theme` once and hand out clones rather
742    /// than calling `Theme::from_brand` per request.
743    ///
744    /// ```
745    /// # use renox::prelude::*;
746    /// use renox::theme::{Brand, Theme, ThemeRequest};
747    /// let north = Theme::from_brand(&Brand::new("#0F766E")).unwrap();
748    /// # let _ =
749    /// App::new().theme_for(move |req: ThemeRequest| {
750    ///     let north = north.clone();
751    ///     async move { Ok((req.host == "north.example.com").then_some(north)) }
752    /// })
753    /// # ;
754    /// ```
755    pub fn theme_for<F, Fut>(mut self, choose: F) -> Self
756    where
757        F: Fn(crate::theme::ThemeRequest) -> Fut + Send + Sync + 'static,
758        Fut: Future<Output = Result<Option<crate::theme::Theme>>> + Send + 'static,
759    {
760        self.theme_chooser = Some(crate::theme::theme_fn(choose));
761        self
762    }
763
764    /// Brands the installable app per request, e.g. by host: the manifest
765    /// (name, short name, theme colour, icons), the offline page and the
766    /// service worker (whose version includes the brand) follow the
767    /// [`PwaBrand`](crate::pwa::PwaBrand) the closure returns, and the
768    /// responses send `Vary: Host`. Return `Ok(None)` to use the static
769    /// [`Pwa`](crate::pwa::Pwa); an `Err` is logged and falls back the same
770    /// way. Needs [`App::pwa`] (booting fails without it). Brand icons are
771    /// read and checked on first use; invalid ones are logged and the static
772    /// icons stay. The closure runs for every manifest, worker and offline
773    /// request, so keep it cheap.
774    ///
775    /// ```
776    /// # use renox::prelude::*;
777    /// use renox::pwa::{Pwa, PwaBrand, PwaRequest};
778    /// # let _ =
779    /// App::new()
780    ///     .pwa(Pwa::new("Bikeshop").icons("public/icons"))
781    ///     .pwa_for(|req: PwaRequest| async move {
782    ///         Ok((req.host() == "north.example.com").then(|| PwaBrand::new("North Bikes")))
783    ///     })
784    /// # ;
785    /// ```
786    pub fn pwa_for<F, Fut>(mut self, resolve: F) -> Self
787    where
788        F: Fn(crate::pwa::PwaRequest) -> Fut + Send + Sync + 'static,
789        Fut: Future<Output = Result<Option<crate::pwa::PwaBrand>>> + Send + 'static,
790    {
791        self.pwa_chooser = Some(crate::pwa::pwa_fn(resolve));
792        self
793    }
794
795    /// Gives every view a value computed per request; see [`Registry::share`].
796    pub fn share<F, Fut, T>(mut self, key: &str, compute: F) -> Self
797    where
798        F: Fn(crate::view::ViewContext) -> Fut + Send + Sync + 'static,
799        Fut: Future<Output = Result<T>> + Send + 'static,
800        T: serde::Serialize,
801    {
802        self.registry.share(key, compute);
803        self
804    }
805
806    /// Adds `link` to the navigation menu `menu`; see [`Registry::nav`].
807    pub fn nav(mut self, menu: &str, link: crate::nav::NavLink) -> Self {
808        self.registry.nav(menu, link);
809        self
810    }
811
812    /// Registers a key for signed requests; see [`Registry::signing_key`].
813    pub fn signing_key(mut self, key_id: &str, secret: &str) -> Self {
814        self.registry.signing_key(key_id, secret);
815        self
816    }
817
818    /// Hides the link with `key` from the menu `menu`; see [`Registry::nav_hide`].
819    pub fn nav_hide(mut self, menu: &str, key: &str) -> Self {
820        self.registry.nav_hide(menu, key);
821        self
822    }
823
824    /// Adds template functions, filters or globals; see [`Registry::templates`].
825    pub fn templates(
826        mut self,
827        hook: impl Fn(&mut minijinja::Environment<'static>) + Send + Sync + 'static,
828    ) -> Self {
829        self.registry.templates(hook);
830        self
831    }
832
833    /// Defines scheduled tasks.
834    pub fn schedule(mut self, define: impl FnOnce(&mut Schedule)) -> Self {
835        define(self.registry.schedule());
836        self
837    }
838
839    /// Connects to the database and builds the router, without serving.
840    pub async fn boot(mut self) -> Result<Kernel> {
841        let config = match self.config {
842            Some(config) => config,
843            None => Config::load()?,
844        };
845
846        self.registry.job::<crate::mail::SendMail>();
847        self.registry.job::<crate::mail::SendMailVia>();
848        self.registry
849            .job::<crate::auth::notifications::SendToChannel>();
850        self.registry
851            .job::<crate::auth::passwordless::SendLoginSecret>();
852        self.registry.job::<crate::webhook::ProcessWebhook>();
853        self.registry
854            .job::<crate::webhook::outbound::DeliverWebhook>();
855        #[cfg(feature = "server-events")]
856        self.registry.job::<crate::analytics::ServerEvent>();
857        let mut migrations = crate::queue::MIGRATIONS.to_vec();
858        migrations.push(crate::cache::MIGRATION);
859        migrations.push(crate::session::MIGRATION);
860        migrations.push(crate::grid::MIGRATION);
861        migrations.push(crate::import::MIGRATION);
862        migrations.extend(crate::webhook::MIGRATIONS);
863        migrations.push(crate::db::SEQUENCE_MIGRATION);
864        migrations.push(crate::state_machine::MIGRATION);
865        migrations.push(crate::custom_fields::MIGRATION);
866        migrations.push(crate::idempotency::MIGRATION);
867        migrations.extend(self.migrations);
868        for module in &self.modules {
869            migrations.extend_from_slice(module.migrations());
870            self.registry.contributions.set_module(module.name());
871            module.register(&mut self.registry);
872        }
873        let Registry {
874            jobs,
875            listeners,
876            mut schedule,
877            duplicate_job,
878            webhooks,
879            webhook_events,
880            live_components,
881            duplicate_live,
882            commands,
883            templates,
884            components,
885            mut shares,
886            channels,
887            channel_limits,
888            reporters,
889            permissions,
890            second_factor,
891            duplicate_second_factor,
892            mut account_sections,
893            auth,
894            assets: static_assets,
895            provided: mut module_provided,
896            seeders,
897            models,
898            view_data,
899            settings_groups,
900            settings_module,
901            nav_links,
902            nav_hidden,
903            signing_keys,
904            contributions,
905        } = self.registry;
906        if !settings_groups.is_empty() && !settings_module {
907            return Err(anyhow!(
908                "settings groups are declared (`App::settings`), but the `Settings` module isn't \
909                 on: add `.module(renox::settings::Settings)`"
910            )
911            .into());
912        }
913        let mut seen = std::collections::HashSet::new();
914        for group in &settings_groups {
915            if !seen.insert(group.key) {
916                return Err(anyhow!("two settings groups have the key `{}`", group.key).into());
917            }
918        }
919        let settings_seed = match &self.settings_seed {
920            Some(path) => crate::settings::read_seed(path)?,
921            None => None,
922        };
923        if settings_groups.iter().any(|group| group.shared) {
924            shares.push((
925                "settings".to_owned(),
926                crate::view::share_fn(|ctx: crate::view::ViewContext| async move {
927                    ctx.state.settings_for_views().await
928                }),
929            ));
930        }
931        // The app's own `App::provide` values win over the modules'.
932        module_provided.extend(self.provided);
933        check_assets(&static_assets)?;
934        let static_assets: Arc<[crate::registry::StaticAsset]> = static_assets.into();
935        if let Some(name) = duplicate_job {
936            return Err(anyhow!("job `{name}` is registered twice").into());
937        }
938        if let Some(name) = duplicate_live {
939            return Err(anyhow!("live component `{name}` is registered twice").into());
940        }
941        if duplicate_second_factor {
942            return Err(
943                anyhow!("two modules set a second login step (`Registry::second_factor`)").into(),
944            );
945        }
946        let nav = crate::nav::Nav::build(nav_links, nav_hidden)?;
947        check_commands(&commands)?;
948        schedule.check()?;
949        let zone: Zone = config.timezone;
950
951        let migrator = Migrator::new(migrations)?;
952        let key = match &config.key {
953            Some(key) => parse_key(key)?,
954            None => parse_key(&crate::generate_key())?,
955        };
956        // `Encrypted` model fields are sealed and opened with APP_KEY.
957        let db = crate::db::connect(&config).await?.with_key(key.clone());
958
959        let mut router = Router::new();
960        let mut fallback: Option<axum::routing::MethodRouter<AppState>> = None;
961        // One router per `Routes::domain` pattern, with its own fallback.
962        let mut domains: Vec<(
963            crate::domain::DomainPattern,
964            Router<AppState>,
965            Option<axum::routing::MethodRouter<AppState>>,
966        )> = Vec::new();
967        let mut routes = RouteTable::default();
968        let mut listing: Vec<RouteInfo> = Vec::new();
969        // Complete before any `routes_with` runs: every `register` is done.
970        let contributions = Arc::new(contributions);
971        for module in &self.modules {
972            tracing::debug!(module = module.name(), "registering module");
973            let parts = module.routes_with(&contributions).into_parts();
974            check_clashes(&listing, &parts.listing, None, module.name())?;
975            router = merge_routes(router, parts.router, module.name())?;
976            for (name, path) in parts.names {
977                routes.insert(name, path)?;
978            }
979            listing.extend(parts.listing.into_iter().map(|info| RouteInfo {
980                module: module.name().to_owned(),
981                ..info
982            }));
983            if let Some(handler) = parts.fallback {
984                if fallback.is_some() {
985                    return Err(anyhow!(
986                        "two modules set a fallback route (`{}` is the second)",
987                        module.name()
988                    )
989                    .into());
990                }
991                fallback = Some(handler);
992            }
993            for (text, domain_routes) in parts.domains {
994                let pattern = crate::domain::DomainPattern::parse(&text)?;
995                let inner = domain_routes.into_parts();
996                if !inner.domains.is_empty() {
997                    return Err(anyhow!(
998                        "Routes::domain(\"{text}\", …) inside another domain (module `{}`)",
999                        module.name()
1000                    )
1001                    .into());
1002                }
1003                check_clashes(
1004                    &listing,
1005                    &inner.listing,
1006                    Some(pattern.as_str()),
1007                    module.name(),
1008                )?;
1009                let at = match domains.iter().position(|(p, _, _)| *p == pattern) {
1010                    Some(at) => at,
1011                    None => {
1012                        domains.push((pattern.clone(), Router::new(), None));
1013                        domains.len() - 1
1014                    }
1015                };
1016                let (_, domain_router, domain_fallback) = &mut domains[at];
1017                *domain_router =
1018                    merge_routes(std::mem::take(domain_router), inner.router, module.name())?;
1019                if let Some(handler) = inner.fallback {
1020                    if domain_fallback.is_some() {
1021                        return Err(anyhow!(
1022                            "two fallbacks for the domain `{text}` (module `{}`)",
1023                            module.name()
1024                        )
1025                        .into());
1026                    }
1027                    *domain_fallback = Some(handler);
1028                }
1029                for (name, path) in inner.names {
1030                    routes.set_domain(&name, pattern.as_str());
1031                    routes.insert(name, path)?;
1032                }
1033                listing.extend(inner.listing.into_iter().map(|info| RouteInfo {
1034                    module: module.name().to_owned(),
1035                    domain: Some(pattern.as_str().to_owned()),
1036                    ..info
1037                }));
1038            }
1039        }
1040        // The app's own layers; the first one added ends up outermost.
1041        for layer in self.layers.iter().rev() {
1042            router = layer(router);
1043            for (_, domain_router, _) in &mut domains {
1044                *domain_router = layer(std::mem::take(domain_router));
1045            }
1046        }
1047        listing.extend(framework_routes(
1048            &config,
1049            self.pwa.is_some(),
1050            self.pwa_chooser.is_some(),
1051        ));
1052        listing.sort_by(|a, b| (&a.path, &a.method).cmp(&(&b.path, &b.method)));
1053        // Keys of `.offline()` routes expire by themselves: prune them daily
1054        // wherever the scheduler runs (unless the app scheduled it itself).
1055        if config.scheduler
1056            && listing
1057                .iter()
1058                .any(|info| info.middleware.iter().any(|m| m == "offline"))
1059            && !schedule.has("idempotency:prune")
1060        {
1061            schedule.daily_at("03:30", "idempotency:prune", |state| async move {
1062                crate::idempotency::prune_retained(&state, None).await?;
1063                Ok(())
1064            });
1065        }
1066        // The current route's name follows the request's method (#299).
1067        for info in &listing {
1068            if let Some(name) = &info.name {
1069                routes.set_method(name, &info.method);
1070            }
1071        }
1072        // `throttle_by("name")` needs `App::rate_limiter("name", …)`.
1073        for route in &listing {
1074            for mark in &route.middleware {
1075                if let Some(name) = mark.strip_prefix("throttle:")
1076                    && !name.contains('/')
1077                    && !self.limiters.contains_key(name)
1078                {
1079                    return Err(anyhow!(
1080                        "{} {} uses throttle_by(\"{name}\"), but there's no App::rate_limiter(\"{name}\", …)",
1081                        route.method,
1082                        route.path
1083                    )
1084                    .into());
1085                }
1086            }
1087        }
1088        for route in &listing {
1089            for provider in route
1090                .middleware
1091                .iter()
1092                .filter_map(|m| m.strip_prefix("webhook:"))
1093            {
1094                if !webhooks.contains_key(provider) {
1095                    return Err(anyhow!(
1096                        "the route {} receives `{provider}` webhooks, but they're not registered: \
1097                         add `app.webhook::<…>()` in the module's `register`",
1098                        route.path
1099                    )
1100                    .into());
1101                }
1102            }
1103        }
1104        let routes = Arc::new(routes);
1105
1106        let storage = crate::storage::Storage::from_config(&config)?.with_key(key.clone());
1107        let mut disks = HashMap::new();
1108        for (name, settings) in &self.disks {
1109            let valid = !name.is_empty()
1110                && name
1111                    .chars()
1112                    .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
1113            if !valid {
1114                return Err(anyhow!(
1115                    "disk name `{name}`: use letters, digits, `-` and `_` (App::disk)"
1116                )
1117                .into());
1118            }
1119            let disk = crate::storage::Storage::named(&config, name, &settings(&config)?)?
1120                .with_key(key.clone());
1121            if disks.insert(name.clone(), disk).is_some() {
1122                return Err(anyhow!("two disks are named `{name}` (App::disk)").into());
1123            }
1124        }
1125        // Release builds serve what was compiled in; debug builds read the disk.
1126        let embedded = self.embedded.filter(|_| !config.debug);
1127        // Rate limits and login locks shared by every server (CACHE_STORE=database).
1128        let shared_counters =
1129            (config.cache_store == crate::CacheStore::Database).then(|| db.clone());
1130        let versions = Arc::new(crate::embedded::AssetVersions::new(
1131            &config.public_path,
1132            embedded.map(|e| e.public),
1133        ));
1134        let views = Views::new(
1135            &config,
1136            routes.clone(),
1137            storage.clone(),
1138            embedded.map(|e| e.views),
1139            Arc::new(templates),
1140            Arc::new(components.iter().map(|c| c.contract()).collect()),
1141            zone,
1142            versions,
1143        )
1144        .with_typed(
1145            view_data,
1146            shares.iter().map(|(key, _)| key.clone()).collect(),
1147        );
1148        let mut security =
1149            crate::security::Security::new(&config, &self.csp, &self.permissions_policy, &listing)?;
1150        security.xsrf_cookie = self.xsrf_cookie;
1151        let security = Arc::new(security);
1152        let mut mailers = HashMap::new();
1153        for (name, settings) in &self.mailers {
1154            let mailer = Mailer::open(&settings(&config)?, &config)?;
1155            if mailers.insert(name.clone(), mailer).is_some() {
1156                return Err(anyhow!("two mailers are named `{name}` (App::mailer)").into());
1157            }
1158        }
1159        for name in self.mailer_limits.keys() {
1160            if name != "default" && !mailers.contains_key(name) {
1161                return Err(anyhow!(
1162                    "App::mailer_rate_limit names `{name}`, but no mailer has that name: add it with App::mailer"
1163                )
1164                .into());
1165            }
1166        }
1167        for name in channel_limits.keys() {
1168            if !channels.contains_key(name) {
1169                return Err(anyhow!(
1170                    "App::channel_rate_limit names `{name}`, but no channel has that name: add it with App::channel"
1171                )
1172                .into());
1173            }
1174        }
1175        let mut failover = Vec::new();
1176        for name in &config.mail.failover {
1177            let mailer = mailers.get(name).ok_or_else(|| {
1178                anyhow!("MAIL_FAILOVER names `{name}`, but no mailer has that name: add it with App::mailer")
1179            })?;
1180            failover.push((name.clone(), mailer.clone()));
1181        }
1182        let mailer = Mailer::from_config(&config)?.with_failover(failover);
1183        let state = AppState::new(crate::state::AppStateInner {
1184            security,
1185            webhooks: Arc::new(webhooks),
1186            webhook_events: Arc::new(webhook_events),
1187            live_components: Arc::new(live_components),
1188            mailer,
1189            mailers: Arc::new(mailers),
1190            themes: crate::theme::ThemeRegistry::new(
1191                self.theme.as_ref(),
1192                self.theme_chooser.clone(),
1193            ),
1194            pwa: self.pwa.clone().map(Arc::new),
1195            channel_limits: Arc::new(channel_limits),
1196            mailer_limits: Arc::new(self.mailer_limits),
1197            queue: Queue::new(db.clone(), key.clone()),
1198            cache: crate::cache::Cache::new(config.cache_store, db.clone())?,
1199            storage,
1200            disks: Arc::new(disks),
1201            uploads: self.uploads.clone(),
1202            http: crate::http::Http::default(),
1203            fakes: Arc::default(),
1204            settings_store: Arc::new(crate::settings::Store::new(settings_groups, settings_seed)),
1205            translator: Arc::new(match embedded {
1206                Some(files) => crate::i18n::Translator::embedded(files.lang)?,
1207                None => crate::i18n::Translator::load(&config.lang_path, config.debug)?,
1208            }),
1209            // Tests read database sessions synchronously (`TestApp::session_get`).
1210            session_mirror: (config.session_driver == crate::SessionDriver::Database
1211                && config.env == Environment::Testing)
1212                .then(Default::default),
1213            live: (config.debug && config.env == Environment::Local).then(|| {
1214                crate::live::Live::start(vec![
1215                    config.views_path.clone(),
1216                    config.public_path.clone(),
1217                    config.lang_path.clone(),
1218                ])
1219            }),
1220            notification_hub: Arc::new(crate::auth::notifications::Hub::new()),
1221            listeners: Arc::new(listeners),
1222            inspector: (config.debug && config.env == Environment::Local)
1223                .then(|| Arc::new(crate::inspector::Inspector::default())),
1224            config: Arc::new(config),
1225            routes,
1226            views,
1227            db,
1228            key,
1229            gates: Arc::new(crate::auth::Access {
1230                gates: self.gates,
1231                before: self.gate_before,
1232                permissions,
1233            }),
1234            async_gates: Arc::new(self.async_gates),
1235            shares: Arc::new(shares),
1236            channels: Arc::new(channels),
1237            reporters: Arc::new(reporters),
1238            second_factor: second_factor.map(Arc::new),
1239            nav: Arc::new(nav),
1240            signing_keys: Arc::new(signing_keys),
1241            contributions,
1242            account_sections: {
1243                account_sections.sort_by_key(|section| section.order);
1244                Arc::new(account_sections)
1245            },
1246            auth,
1247            limiters: Arc::new(
1248                self.limiters
1249                    .into_iter()
1250                    .map(|(name, rule)| (name, crate::rate_limit::NamedLimiter::new(rule)))
1251                    .collect(),
1252            ),
1253            provided: Arc::new(module_provided),
1254            throttle: Arc::new(LoginThrottle::new(shared_counters.clone())),
1255            detect_locale: self.detect_locale,
1256            rtl_locales: self.rtl_locales.map(Arc::new),
1257        });
1258        if let Some(second) = &state.second_factor
1259            && state.url(&second.challenge, &[]).is_err()
1260        {
1261            return Err(anyhow!(
1262                "the second login step's challenge route `{}` doesn't exist",
1263                second.challenge
1264            )
1265            .into());
1266        }
1267
1268        let public = embedded.map(|e| e.public);
1269        let pwa = match self.pwa.take() {
1270            Some(pwa) => {
1271                let precache = assets::precache_urls();
1272                let assets = pwa
1273                    .assets_with(
1274                        |view| state.views.render(view, serde_json::json!({})),
1275                        &precache,
1276                        "",
1277                        public,
1278                    )
1279                    .map_err(|e| anyhow!("{e:#}"))?;
1280                let resolver = self
1281                    .pwa_chooser
1282                    .take()
1283                    .map(|choose| Arc::new(crate::pwa::PwaResolver::new(choose, precache)));
1284                Some((Arc::new(pwa), Arc::new(assets), resolver))
1285            }
1286            None if self.pwa_chooser.is_some() => {
1287                return Err(anyhow!("App::pwa_for needs App::pwa").into());
1288            }
1289            None => None,
1290        };
1291        let pwa = pwa.as_ref();
1292        let default = build_router(router, state.clone(), public, fallback, &static_assets, pwa);
1293        let router = if domains.is_empty() {
1294            default
1295        } else {
1296            let hosts = domains
1297                .into_iter()
1298                .map(|(pattern, router, fallback)| {
1299                    (
1300                        pattern,
1301                        build_router(router, state.clone(), public, fallback, &static_assets, pwa),
1302                    )
1303                })
1304                .collect();
1305            crate::domain::dispatch(hosts, default)
1306        };
1307        Ok(Kernel {
1308            listing,
1309            router,
1310            state,
1311            migrator,
1312            seeders,
1313            models,
1314            handlers: Arc::new(jobs),
1315            schedule,
1316            zone,
1317            commands,
1318        })
1319    }
1320
1321    /// Builds the router without starting a server, e.g. for tests.
1322    pub async fn into_router(self) -> Result<Router> {
1323        Ok(self.boot().await?.router)
1324    }
1325
1326    /// Runs the command given on the command line (`serve` by default) on a
1327    /// new Tokio runtime.
1328    pub fn run(self) -> Result {
1329        let args: Vec<String> = std::env::args().skip(1).collect();
1330        tokio::runtime::Builder::new_multi_thread()
1331            .enable_all()
1332            .build()?
1333            .block_on(self.run_command(&args))
1334    }
1335
1336    /// Runs one command as the app binary would, e.g. from a test or a
1337    /// program that drives the app: `["migrate:status"]`, `["down",
1338    /// "--secret", "abc"]`, or `[]` for `serve`. Output goes to stdout.
1339    ///
1340    /// ```no_run
1341    /// # use renox::prelude::*;
1342    /// # async fn demo() -> Result {
1343    /// App::new().run_args(["migrate"]).await?;
1344    /// # Ok(()) }
1345    /// ```
1346    pub async fn run_args(self, args: impl IntoIterator<Item = impl Into<String>>) -> Result {
1347        let args: Vec<String> = args.into_iter().map(Into::into).collect();
1348        // The command future is large (one arm per command), and a debug build
1349        // copies it: on the heap it cannot overflow a test's or a small thread's
1350        // stack (Windows, 1 MiB main stack).
1351        Box::pin(self.run_command(&args)).await
1352    }
1353
1354    /// Starts the server on the current Tokio runtime.
1355    pub async fn serve(self) -> Result {
1356        Box::pin(self.run_command(&[])).await
1357    }
1358
1359    async fn run_command(self, args: &[String]) -> Result {
1360        let command = args.first().map(String::as_str).unwrap_or("serve");
1361        if matches!(command, "help" | "--help" | "-h") {
1362            // Modules add their commands in `register`, which boot runs.
1363            let mut modules = Registry::default();
1364            for module in &self.modules {
1365                module.register(&mut modules);
1366            }
1367            let mut commands = self.registry.commands.clone();
1368            commands.extend(modules.commands);
1369            println!("{USAGE}{}", app_commands_help(&commands));
1370            return Ok(());
1371        }
1372
1373        let config = match self.config.clone() {
1374            Some(config) => config,
1375            None => Config::load()?,
1376        };
1377        let long_running = matches!(command, "serve" | "queue:work" | "schedule:work");
1378        init_tracing(&config, long_running);
1379        if command == "serve" && config.key.is_none() && config.env != Environment::Testing {
1380            tracing::warn!(
1381                "APP_KEY is not set; using a temporary key, so sessions end on restart. \
1382                 Run `rnx key:generate`."
1383            );
1384        }
1385        let kernel = App {
1386            config: Some(config),
1387            ..self
1388        }
1389        .boot()
1390        .await?;
1391
1392        match command {
1393            "serve" => kernel.serve().await?,
1394            "migrate" => print_done("Migrated", &kernel.migrate().await?),
1395            "migrate:rollback" => {
1396                let steps = flag_value(args, "--step")?.unwrap_or(1);
1397                print_done("Rolled back", &kernel.rollback(steps).await?);
1398            }
1399            "migrate:fresh" => {
1400                println!("Dropped all tables.");
1401                print_done("Migrated", &kernel.fresh().await?);
1402                if args.iter().any(|a| a == "--seed") {
1403                    kernel.seed().await?;
1404                    println!("Seeded.");
1405                }
1406            }
1407            "db:diff" if !kernel.commands.iter().any(|c| c.name == "db:diff") => {
1408                crate::db::auto_migration::run(&kernel, &args[1..]).await?
1409            }
1410            "db:check" if !kernel.commands.iter().any(|c| c.name == "db:check") => {
1411                kernel.db_check().await?
1412            }
1413            "view:check" if !kernel.commands.iter().any(|c| c.name == "view:check") => {
1414                let problems = kernel.state.views.check(&kernel.state.routes);
1415                for problem in &problems {
1416                    println!("{problem}");
1417                }
1418                let checked = kernel.state.views.names().len();
1419                println!("Checked {checked} templates: {} problems.", problems.len());
1420                if !problems.is_empty() {
1421                    return Err(anyhow!("{} template problem(s)", problems.len()).into());
1422                }
1423            }
1424            "state:diagram" if !kernel.commands.iter().any(|c| c.name == "state:diagram") => {
1425                match args.get(1) {
1426                    Some(name) => match crate::state_machine::machine_info(name) {
1427                        Some(info) => println!("{}", info.mermaid.trim_end()),
1428                        None => {
1429                            return Err(anyhow!(
1430                                "no state machine called `{name}` (register it with App::state_machine); known: {}",
1431                                crate::state_machine::machine_names().join(", ")
1432                            )
1433                            .into());
1434                        }
1435                    },
1436                    None => {
1437                        for name in crate::state_machine::machine_names() {
1438                            println!("{name}");
1439                        }
1440                    }
1441                }
1442            }
1443            "view:data" if !kernel.commands.iter().any(|c| c.name == "view:data") => {
1444                let path = std::path::Path::new(
1445                    flag_text(args, "--out").unwrap_or(".vscode/renox-components.json"),
1446                );
1447                if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
1448                    std::fs::create_dir_all(dir)?;
1449                }
1450                let mut text = serde_json::to_string_pretty(&kernel.state.views.custom_data())
1451                    .map_err(|e| anyhow!(e))?;
1452                text.push('\n');
1453                std::fs::write(path, text)?;
1454                println!("Wrote {}.", path.display());
1455            }
1456            "migrate:status" => {
1457                for m in kernel.migration_status().await? {
1458                    let note = if m.missing {
1459                        "  (applied, but its file is gone)"
1460                    } else if m.changed {
1461                        "  (edited after it ran; the edit won't run)"
1462                    } else {
1463                        ""
1464                    };
1465                    match m.batch {
1466                        Some(batch) => println!("  ran (batch {batch})  {}{note}", m.name),
1467                        None => println!("  pending          {}", m.name),
1468                    }
1469                }
1470            }
1471            "db:seed" => {
1472                kernel.seed().await?;
1473                println!("Seeded.");
1474            }
1475            "queue:work" => {
1476                let queues: Vec<String> = flag_text(args, "--queue")
1477                    .map(|q| q.split(',').map(|s| s.trim().to_owned()).collect())
1478                    .unwrap_or_default();
1479                let worker = kernel.worker(queues);
1480                if args.iter().any(|a| a == "--once") {
1481                    println!("Ran {} job(s).", worker.drain().await?);
1482                } else {
1483                    let workers = flag_value(args, "--workers")?.unwrap_or(1) as usize;
1484                    let (stop, stopped) = watch::channel(false);
1485                    let running = tokio::spawn(worker.run(workers, stopped));
1486                    shutdown_signal().await;
1487                    let _ = stop.send(true);
1488                    let _ = running.await;
1489                }
1490            }
1491            "webhook:failed" => {
1492                let failed = crate::webhook::WebhookCall::failed(&kernel.state.db).await?;
1493                if failed.is_empty() {
1494                    println!("No failed webhook calls.");
1495                }
1496                for call in failed {
1497                    println!(
1498                        "  #{} {} {}: {}",
1499                        call.id,
1500                        call.provider,
1501                        call.event_id,
1502                        call.error
1503                            .unwrap_or_default()
1504                            .lines()
1505                            .next()
1506                            .unwrap_or_default()
1507                    );
1508                }
1509            }
1510            "webhook:retry" => {
1511                let id: i64 = args
1512                    .get(1)
1513                    .and_then(|id| id.parse().ok())
1514                    .ok_or_else(|| anyhow!("usage: webhook:retry <id>"))?;
1515                if crate::webhook::retry(&kernel.state, id).await? {
1516                    println!("Webhook call #{id} queued again.");
1517                } else {
1518                    return Err(anyhow!("there is no webhook call #{id}").into());
1519                }
1520            }
1521            "webhook:endpoints" => {
1522                let endpoints = crate::webhook::outbound::Endpoint::list(&kernel.state.db).await?;
1523                if endpoints.is_empty() {
1524                    println!("No webhook endpoints.");
1525                }
1526                for e in endpoints {
1527                    let state = if e.enabled {
1528                        "enabled".to_owned()
1529                    } else {
1530                        format!("disabled: {}", e.disabled_reason.unwrap_or_default())
1531                    };
1532                    let events = if e.events.is_empty() {
1533                        "all events".to_owned()
1534                    } else {
1535                        e.events.join(",")
1536                    };
1537                    println!(
1538                        "  #{} {} ({state}) {events} failures={}",
1539                        e.id, e.url, e.consecutive_failures
1540                    );
1541                }
1542            }
1543            "webhook:deliveries" => {
1544                let endpoint = flag_value(args, "--endpoint")?.map(i64::from);
1545                let failed = args.iter().any(|a| a == "--failed");
1546                let deliveries = crate::webhook::outbound::Delivery::list(
1547                    &kernel.state.db,
1548                    endpoint,
1549                    failed,
1550                    100,
1551                )
1552                .await?;
1553                if deliveries.is_empty() {
1554                    println!("No webhook deliveries.");
1555                }
1556                for d in deliveries {
1557                    let code = d
1558                        .response_status
1559                        .map(|c| format!(" {c}"))
1560                        .unwrap_or_default();
1561                    let error = d.error.map(|e| format!(": {e}")).unwrap_or_default();
1562                    println!(
1563                        "  #{} endpoint #{} {} {} attempt {}{code}{error}",
1564                        d.id, d.endpoint_id, d.event_type, d.status, d.attempt
1565                    );
1566                }
1567            }
1568            "webhook:redeliver" => {
1569                let id: i64 = args
1570                    .get(1)
1571                    .and_then(|id| id.parse().ok())
1572                    .ok_or_else(|| anyhow!("usage: webhook:redeliver <id>"))?;
1573                if crate::webhook::outbound::Delivery::redeliver(&kernel.state, id).await? {
1574                    println!("Webhook delivery #{id} queued again.");
1575                } else {
1576                    return Err(anyhow!("there is no webhook delivery #{id}").into());
1577                }
1578            }
1579            "webhook:prune-deliveries" => {
1580                let days = flag_value(args, "--days")?.unwrap_or(30);
1581                let age = Duration::from_secs(u64::from(days) * 86_400);
1582                println!(
1583                    "Deleted {} webhook delivery record(s) older than {days} day(s).",
1584                    crate::webhook::outbound::Delivery::prune(&kernel.state.db, age).await?
1585                );
1586            }
1587            "queue:failed" => {
1588                let failed = kernel.state.queue.failed().await?;
1589                if failed.is_empty() {
1590                    println!("No failed jobs.");
1591                }
1592                for job in failed {
1593                    println!("  #{} {} ({}): {}", job.id, job.job, job.queue, job.error);
1594                }
1595            }
1596            "queue:retry" => {
1597                let id = match args.get(1).map(String::as_str) {
1598                    Some("all") => None,
1599                    Some(id) => Some(
1600                        id.parse()
1601                            .map_err(|_| anyhow!("expected a job id or `all`"))?,
1602                    ),
1603                    None => return Err(anyhow!("usage: queue:retry <id|all>").into()),
1604                };
1605                let queued = match id {
1606                    Some(id) => u64::from(kernel.state.queue.retry(id).await?),
1607                    None => kernel.state.queue.retry_all().await?,
1608                };
1609                println!("Queued {queued} job(s) again.");
1610            }
1611            "queue:forget" => {
1612                let id: i64 = args
1613                    .get(1)
1614                    .and_then(|id| id.parse().ok())
1615                    .ok_or_else(|| anyhow!("usage: queue:forget <id>"))?;
1616                if kernel.state.queue.forget_failed(id).await? {
1617                    println!("Deleted failed job {id}.");
1618                } else {
1619                    return Err(anyhow!("no failed job {id}").into());
1620                }
1621            }
1622            "queue:prune-failed" => {
1623                let hours = flag_value(args, "--hours")?.unwrap_or(168);
1624                let age = Duration::from_secs(u64::from(hours) * 3600);
1625                println!(
1626                    "Deleted {} failed job(s) older than {hours} hour(s).",
1627                    kernel.state.queue.prune_failed(age).await?
1628                );
1629            }
1630            "queue:prune-batches" => {
1631                let hours = flag_value(args, "--hours")?.unwrap_or(24);
1632                let age = Duration::from_secs(u64::from(hours) * 3600);
1633                println!(
1634                    "Deleted {} batch(es) finished more than {hours} hour(s) ago.",
1635                    kernel.state.queue.prune_batches(age).await?
1636                );
1637            }
1638            "queue:flush" => println!(
1639                "Deleted {} failed job(s).",
1640                kernel.state.queue.flush_failed().await?
1641            ),
1642            "ui:publish" => {
1643                let force = args.iter().any(|a| a == "--force");
1644                crate::assets::publish_ui(&kernel.state.config, force)?;
1645            }
1646            "session:prune" => println!(
1647                "Deleted {} expired session(s).",
1648                crate::Session::prune_expired(&kernel.state.db).await?
1649            ),
1650            "sequence:list" => {
1651                let rows = crate::db::Sequence::list(&kernel.state.db).await?;
1652                if rows.is_empty() {
1653                    println!("No numbering series.");
1654                }
1655                for row in rows {
1656                    println!(
1657                        "  {}  scope={:?} period={:?}  last={}",
1658                        row.series, row.scope, row.period, row.last
1659                    );
1660                }
1661            }
1662            "cache:prune" => println!(
1663                "Deleted {} expired cache row(s).",
1664                kernel.state.cache.prune().await?
1665            ),
1666            "idempotency:prune" => {
1667                let days = flag_value(args, "--days")?;
1668                println!(
1669                    "Deleted {} idempotency key(s) past retention.",
1670                    crate::idempotency::prune_retained(&kernel.state, days).await?
1671                );
1672            }
1673            "import:prune" => {
1674                let days = flag_value(args, "--days")?.unwrap_or(0);
1675                let age = Duration::from_secs(u64::from(days) * 86_400);
1676                println!(
1677                    "Deleted {} import record(s) whose undo window ended more than {days} day(s) ago.",
1678                    crate::import::prune(&kernel.state, age).await?
1679                );
1680            }
1681            "schedule:list" => {
1682                if kernel.schedule.is_empty() {
1683                    println!("No scheduled tasks.");
1684                }
1685                for run in kernel.schedule.upcoming(kernel.zone) {
1686                    let when = match run.at {
1687                        Some(at) => run
1688                            .zone
1689                            .local(at.timestamp())
1690                            .format("%Y-%m-%d %H:%M")
1691                            .to_string(),
1692                        None => "never".to_owned(),
1693                    };
1694                    println!("  {when:<16}  {:<18}  {}", run.zone, run.name);
1695                }
1696            }
1697            "schedule:run" => {
1698                let Some(name) = args.get(1).filter(|a| !a.starts_with('-')) else {
1699                    return Err(anyhow!("usage: schedule:run <task>").into());
1700                };
1701                kernel.run_scheduled(name).await?;
1702                println!("Ran `{name}`.");
1703            }
1704            "schedule:work" => {
1705                let (stop, stopped) = watch::channel(false);
1706                let running = tokio::spawn(kernel.schedule.clone().run(
1707                    kernel.state.clone(),
1708                    kernel.zone,
1709                    stopped,
1710                ));
1711                shutdown_signal().await;
1712                let _ = stop.send(true);
1713                let _ = running.await;
1714            }
1715            "route:list" => print_routes(kernel.routes()),
1716            "db:shell" => crate::shell::run(kernel.db()).await?,
1717            "down" => {
1718                let secret = flag_text(args, "--secret").map(str::to_owned);
1719                let retry = flag_value(args, "--retry")?.map(u64::from);
1720                let mut options = crate::maintenance::DownOptions::new();
1721                if let Some(secret) = &secret {
1722                    options = options.secret(secret.clone());
1723                }
1724                if let Some(retry) = retry {
1725                    options = options.retry(retry);
1726                }
1727                crate::maintenance::down(&kernel.state.config.storage_path, options)?;
1728                match secret {
1729                    Some(secret) => println!("The app is down. Visit /{secret} to bypass it."),
1730                    None => println!("The app is down."),
1731                }
1732            }
1733            "up" => match crate::maintenance::up(&kernel.state.config.storage_path)? {
1734                true => println!("The app is up."),
1735                false => println!("The app was not down."),
1736            },
1737            other if kernel.commands.iter().any(|c| c.name == other) => {
1738                kernel.call(other, args[1..].iter().cloned()).await?;
1739            }
1740            other => {
1741                return Err(anyhow!(
1742                    "unknown command `{other}`\n\n{USAGE}{}",
1743                    app_commands_help(&kernel.commands)
1744                )
1745                .into());
1746            }
1747        }
1748        Ok(())
1749    }
1750}
1751
1752/// The listening socket systemd passes with socket activation
1753/// (`LISTEN_FDS`, a `.socket` unit): it stays open while the service
1754/// restarts, so connections wait in its queue instead of being refused.
1755fn inherited_listener() -> Result<Option<TcpListener>> {
1756    let mut fds = listenfd::ListenFd::from_env();
1757    let Some(listener) = fds
1758        .take_tcp_listener(0)
1759        .map_err(|err| anyhow!("the socket systemd passed isn't a TCP listener: {err}"))?
1760    else {
1761        return Ok(None);
1762    };
1763    listener
1764        .set_nonblocking(true)
1765        .map_err(anyhow::Error::from)?;
1766    Ok(Some(
1767        TcpListener::from_std(listener).map_err(anyhow::Error::from)?,
1768    ))
1769}
1770
1771/// Built-in commands; an app command can't take one of these names.
1772///
1773/// The list is the 1.0 set and stays as it is through 1.x (docs/stability.md):
1774/// refusing a name an app already uses would stop that app from booting. A
1775/// command added in 1.x must let an app command of the same name run in its
1776/// place instead of joining this list.
1777const BUILT_IN_COMMANDS: &[&str] = &[
1778    "serve",
1779    "migrate",
1780    "migrate:rollback",
1781    "migrate:fresh",
1782    "migrate:status",
1783    "db:seed",
1784    "queue:work",
1785    "queue:failed",
1786    "queue:retry",
1787    "queue:flush",
1788    "queue:forget",
1789    "queue:prune-failed",
1790    "queue:prune-batches",
1791    "webhook:failed",
1792    "webhook:retry",
1793    "webhook:endpoints",
1794    "webhook:deliveries",
1795    "webhook:redeliver",
1796    "webhook:prune-deliveries",
1797    "sequence:list",
1798    "cache:prune",
1799    "session:prune",
1800    "idempotency:prune",
1801    "import:prune",
1802    "ui:publish",
1803    "schedule:list",
1804    "schedule:run",
1805    "schedule:work",
1806    "route:list",
1807    "db:shell",
1808    "down",
1809    "up",
1810    "help",
1811];
1812
1813fn check_commands(commands: &[crate::command::Command]) -> Result {
1814    let mut seen = std::collections::HashSet::new();
1815    for command in commands {
1816        let name = command.name.as_str();
1817        if name.is_empty() || name.starts_with('-') || name.contains(char::is_whitespace) {
1818            return Err(anyhow!("`{name}` is not a valid command name").into());
1819        }
1820        if BUILT_IN_COMMANDS.contains(&name) {
1821            return Err(anyhow!("the command `{name}` is built in; choose another name").into());
1822        }
1823        if !seen.insert(name) {
1824            return Err(anyhow!("the command `{name}` is registered twice").into());
1825        }
1826    }
1827    Ok(())
1828}
1829
1830fn app_commands_help(commands: &[crate::command::Command]) -> String {
1831    if commands.is_empty() {
1832        return String::new();
1833    }
1834    let mut out = String::from("\n\nApp commands:\n");
1835    for command in commands {
1836        out.push_str(&format!("  {:<26}{}\n", command.name, command.about));
1837    }
1838    out.trim_end().to_owned()
1839}
1840
1841impl Default for App {
1842    fn default() -> Self {
1843        Self::new()
1844    }
1845}
1846
1847/// A booted application: its router, database, queue and maintenance commands.
1848pub struct Kernel {
1849    router: Router,
1850    listing: Vec<RouteInfo>,
1851    state: AppState,
1852    migrator: Migrator,
1853    seeders: Vec<crate::registry::Seeder>,
1854    models: Vec<crate::db::schema::ModelInfo>,
1855    handlers: Handlers,
1856    schedule: Schedule,
1857    zone: Zone,
1858    commands: Vec<crate::command::Command>,
1859}
1860
1861impl Kernel {
1862    /// A scratch database with every migration run (reused by #371).
1863    pub(crate) async fn scratch_db(&self) -> Result<Db> {
1864        let db = crate::db::connect_scratch(&self.state.config).await?;
1865        self.migrator.run(&db).await?;
1866        Ok(db)
1867    }
1868
1869    /// `db:check`: compares the models with what the migrations build.
1870    async fn db_check(&self) -> Result {
1871        let db = self.scratch_db().await?;
1872        let reports = crate::db::schema_check::check(&db, &self.models).await;
1873        crate::db::drop_scratch(&db).await;
1874        let (text, problems) = crate::db::schema_check::render(&reports?);
1875        print!("{text}");
1876        if problems > 0 {
1877            return Err(anyhow::anyhow!("{problems} problem(s) in the models").into());
1878        }
1879        Ok(())
1880    }
1881
1882    /// The models registered with `App::model`, once each.
1883    pub(crate) fn models(&self) -> &[crate::db::schema::ModelInfo] {
1884        &self.models
1885    }
1886
1887    /// Runs the app command `name` (see [`App::command`]), e.g. from a test.
1888    pub async fn call(
1889        &self,
1890        name: &str,
1891        args: impl IntoIterator<Item = impl Into<String>>,
1892    ) -> Result {
1893        let command = self
1894            .commands
1895            .iter()
1896            .find(|c| c.name == name)
1897            .ok_or_else(|| anyhow!("unknown command `{name}`"))?;
1898        let run = (command.run)(self.state.clone(), crate::command::Args::new(args));
1899        crate::context::scope_app(self.state.clone(), run).await
1900    }
1901
1902    /// Runs the scheduled task `name` now, with its hooks (what
1903    /// `schedule:run` does). In a test, `TestApp::run_scheduled` does the same
1904    /// at the time `TestApp::travel` moved the clock to.
1905    pub async fn run_scheduled(&self, name: &str) -> Result {
1906        self.schedule.run_now(self.state.clone(), name).await
1907    }
1908
1909    /// The assembled router, e.g. to drive with `tower::ServiceExt::oneshot`.
1910    pub fn router(&self) -> Router {
1911        self.router.clone()
1912    }
1913
1914    /// Every route, sorted by path, as `route:list` prints them.
1915    pub fn routes(&self) -> &[RouteInfo] {
1916        &self.listing
1917    }
1918
1919    /// What handlers get as `State<AppState>`.
1920    pub fn state(&self) -> &AppState {
1921        &self.state
1922    }
1923
1924    /// The database connection pool.
1925    pub fn db(&self) -> &Db {
1926        &self.state.db
1927    }
1928
1929    /// The mailer; with `MAIL_MAILER=memory`, `mailer().sent()` lists what was sent.
1930    pub fn mailer(&self) -> &Mailer {
1931        &self.state.mailer
1932    }
1933
1934    /// A worker for the given queues (all queues when empty).
1935    pub fn worker(&self, queues: Vec<String>) -> Worker {
1936        Worker::new(self.state.clone(), self.handlers.clone(), queues)
1937    }
1938
1939    /// Runs every job that is available now, e.g. in tests; returns how many ran.
1940    pub async fn run_jobs(&self) -> Result<usize> {
1941        self.worker(Vec::new()).drain().await
1942    }
1943
1944    /// Serves HTTP with queue workers and the scheduler in the same process,
1945    /// until Ctrl-C or SIGTERM; then lets running jobs finish.
1946    pub async fn serve(self) -> Result {
1947        let config = self.state.config.clone();
1948        let listener = match inherited_listener()? {
1949            Some(listener) => {
1950                tracing::info!("using the socket systemd passed (socket activation)");
1951                listener
1952            }
1953            None => TcpListener::bind(config.addr()).await?,
1954        };
1955        tracing::info!(
1956            "{} listening on http://{}",
1957            config.name,
1958            listener.local_addr()?
1959        );
1960
1961        let (stop, stopped) = watch::channel(false);
1962        let mut background = Vec::new();
1963        if config.queue_workers > 0 {
1964            tracing::info!(workers = config.queue_workers, "queue workers started");
1965            let worker = self.worker(Vec::new());
1966            background.push(tokio::spawn(
1967                worker.run(config.queue_workers, stopped.clone()),
1968            ));
1969        }
1970        if config.scheduler && !self.schedule.is_empty() {
1971            tracing::info!("scheduler started");
1972            background.push(tokio::spawn(self.schedule.clone().run(
1973                self.state.clone(),
1974                self.zone,
1975                stopped,
1976            )));
1977        }
1978
1979        let service = self
1980            .router
1981            .into_make_service_with_connect_info::<SocketAddr>();
1982        let live = self.state.live.clone();
1983        let notification_hub = self.state.notification_hub.clone();
1984        axum::serve(listener, service)
1985            .with_graceful_shutdown(async move {
1986                shutdown_signal().await;
1987                // Open live-reload and notification streams would otherwise
1988                // hold the shutdown.
1989                if let Some(live) = live {
1990                    live.stop();
1991                }
1992                notification_hub.stop();
1993            })
1994            .await?;
1995
1996        let _ = stop.send(true);
1997        let finished = async {
1998            for task in background {
1999                let _ = task.await;
2000            }
2001        };
2002        if tokio::time::timeout(SHUTDOWN_GRACE, finished)
2003            .await
2004            .is_err()
2005        {
2006            tracing::warn!("background work was still running after {SHUTDOWN_GRACE:?}");
2007        }
2008        tracing::info!("{} stopped", config.name);
2009        Ok(())
2010    }
2011
2012    /// Runs pending migrations; returns their names.
2013    pub async fn migrate(&self) -> Result<Vec<String>> {
2014        let done = self.migrator.run(self.db()).await?;
2015        Ok(done.into_iter().map(str::to_owned).collect())
2016    }
2017
2018    /// Undoes the last `batches` batches of migrations; returns their names.
2019    pub async fn rollback(&self, batches: u32) -> Result<Vec<String>> {
2020        Ok(self.migrator.rollback(self.db(), batches).await?)
2021    }
2022
2023    /// Drops every table and runs all migrations.
2024    pub async fn fresh(&self) -> Result<Vec<String>> {
2025        let done = self.migrator.fresh(self.db()).await?;
2026        Ok(done.into_iter().map(str::to_owned).collect())
2027    }
2028
2029    /// Every migration and whether it has run, as `migrate:status` prints them.
2030    pub async fn migration_status(&self) -> Result<Vec<MigrationStatus>> {
2031        Ok(self.migrator.status(self.db()).await?)
2032    }
2033
2034    /// Runs every seeder in registration order.
2035    pub async fn seed(&self) -> Result {
2036        for seeder in &self.seeders {
2037            // In the app's context, so a seeder can reach `renox::context::app()`
2038            // (config, `encrypt`, the cache) and model hooks see it too.
2039            crate::context::scope_app(self.state.clone(), seeder(self.state.clone())).await?;
2040        }
2041        Ok(())
2042    }
2043}
2044
2045/// Routes Renox adds itself.
2046fn framework_routes(config: &Config, pwa: bool, pwa_for: bool) -> Vec<RouteInfo> {
2047    let route = |method: &str, path: &str| RouteInfo {
2048        method: method.to_owned(),
2049        path: path.to_owned(),
2050        name: None,
2051        module: "renox".to_owned(),
2052        middleware: Vec::new(),
2053        domain: None,
2054    };
2055    let mut routes = vec![
2056        route("GET", "/health"),
2057        route("GET", "/robots.txt"),
2058        route("GET", "/favicon.ico"),
2059        route("GET", "/_renox/{asset}"),
2060        route("GET", "/_renox/theme/{hash}.css"),
2061        route("GET", "/_renox/files/{*key}"),
2062        route("POST", "/_renox/grid/{grid}/prefs"),
2063        route("DELETE", "/_renox/grid/{grid}/prefs"),
2064        route("POST", "/_renox/live/{component}/{action}"),
2065        route("GET", "/_renox/csrf"),
2066        route("GET", "/storage/{*path}"),
2067    ];
2068    if pwa {
2069        routes.push(route("GET", "/manifest.webmanifest"));
2070        routes.push(route("GET", "/sw.js"));
2071        routes.push(route("GET", crate::pwa::OFFLINE_ROUTE));
2072        routes.push(route("GET", "/_renox/pwa/icons/{file}"));
2073        if pwa_for {
2074            routes.push(route("GET", "/_renox/pwa/icons/{hash}/{file}"));
2075        }
2076    }
2077    if config.debug {
2078        routes.push(route("GET", "/_renox/mail"));
2079        routes.push(route("GET", "/_renox/mail/{id}"));
2080    }
2081    if config.debug && config.env == Environment::Local {
2082        routes.push(route("GET", "/_renox/live"));
2083    }
2084    routes
2085}
2086
2087fn print_routes(routes: &[RouteInfo]) {
2088    print!("{}", route_table(routes));
2089}
2090
2091/// `route:list`'s table.
2092fn route_table(routes: &[RouteInfo]) -> String {
2093    use std::fmt::Write as _;
2094    let mut out = String::new();
2095    let with_domains = routes.iter().any(|r| r.domain.is_some());
2096    let rows: Vec<Vec<String>> = routes
2097        .iter()
2098        .map(|r| {
2099            let mut row = vec![
2100                r.method.clone(),
2101                r.path.clone(),
2102                r.name.clone().unwrap_or_default(),
2103                r.module.clone(),
2104                r.middleware
2105                    .iter()
2106                    .map(|guard| {
2107                        if is_role_guard(guard) {
2108                            format!("{guard}*")
2109                        } else {
2110                            guard.clone()
2111                        }
2112                    })
2113                    .collect::<Vec<_>>()
2114                    .join(", "),
2115            ];
2116            if with_domains {
2117                row.insert(0, r.domain.clone().unwrap_or_default());
2118            }
2119            row
2120        })
2121        .collect();
2122    let mut header: Vec<String> = ["METHOD", "PATH", "NAME", "MODULE", "MIDDLEWARE"]
2123        .map(str::to_owned)
2124        .to_vec();
2125    if with_domains {
2126        header.insert(0, "DOMAIN".into());
2127    }
2128    let mut widths: Vec<usize> = header.iter().map(String::len).collect();
2129    for row in &rows {
2130        for (width, cell) in widths.iter_mut().zip(row) {
2131            *width = (*width).max(cell.chars().count());
2132        }
2133    }
2134    for row in std::iter::once(&header).chain(&rows) {
2135        let line: Vec<String> = row
2136            .iter()
2137            .zip(&widths)
2138            .map(|(cell, width)| format!("{cell:<width$}", width = *width))
2139            .collect();
2140        let _ = writeln!(out, "{}", line.join("  ").trim_end());
2141    }
2142    if routes
2143        .iter()
2144        .flat_map(|r| &r.middleware)
2145        .any(|g| is_role_guard(g))
2146    {
2147        out.push_str(
2148            "\n* role and permission guards count the user's global roles plus the roles \
2149             given in the request's active scope (permissions::set_scope).\n",
2150        );
2151    }
2152    out
2153}
2154
2155/// A `role:` or `permission:` guard, which counts scoped roles too.
2156fn is_role_guard(guard: &str) -> bool {
2157    guard.starts_with("role:") || guard.starts_with("permission:")
2158}
2159
2160fn print_done(verb: &str, names: &[String]) {
2161    if names.is_empty() {
2162        println!("Nothing to do.");
2163    }
2164    for name in names {
2165        println!("{verb}: {name}");
2166    }
2167}
2168
2169fn flag_text<'a>(args: &'a [String], flag: &str) -> Option<&'a str> {
2170    let i = args.iter().position(|a| a == flag)?;
2171    args.get(i + 1).map(String::as_str)
2172}
2173
2174fn flag_value(args: &[String], flag: &str) -> Result<Option<u32>> {
2175    if !args.iter().any(|a| a == flag) {
2176        return Ok(None);
2177    }
2178    match flag_text(args, flag).and_then(|v| v.parse().ok()) {
2179        Some(value) => Ok(Some(value)),
2180        None => Err(anyhow!("{flag} needs a number").into()),
2181    }
2182}
2183
2184/// Turns a handler that panics or runs past `REQUEST_TIMEOUT` into a 500
2185/// with the error page, instead of a dropped connection or a hung client.
2186async fn guard(
2187    limit: Option<Duration>,
2188    req: axum::extract::Request,
2189    next: axum::middleware::Next,
2190) -> axum::response::Response {
2191    use axum::response::IntoResponse;
2192    let run = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(next.run(req)));
2193    let outcome = match limit {
2194        Some(limit) => match tokio::time::timeout(limit, run).await {
2195            Ok(outcome) => outcome,
2196            Err(_) => {
2197                return Error::Internal(anyhow!(
2198                    "the request took longer than REQUEST_TIMEOUT ({}s)",
2199                    limit.as_secs()
2200                ))
2201                .into_response();
2202            }
2203        },
2204        None => run.await,
2205    };
2206    outcome.unwrap_or_else(|panic| {
2207        let message = crate::error::panic_message(&*panic);
2208        Error::Internal(anyhow!("the handler panicked: {message}")).into_response()
2209    })
2210}
2211
2212/// How much longer than `REQUEST_TIMEOUT` the outer limit (`backstop`) waits,
2213/// so a slow handler still gets the inner one's error page.
2214const BACKSTOP_GRACE: Duration = Duration::from_secs(1);
2215
2216/// `REQUEST_TIMEOUT` around the session, i18n, auth, CSRF and view layers:
2217/// `guard` only covers the handler, so a hang before it (database sessions
2218/// on a database that stopped answering) would otherwise go unbounded.
2219/// Answers a plain 500 a little after the handler's own limit.
2220async fn backstop(
2221    limit: Option<Duration>,
2222    req: axum::extract::Request,
2223    next: axum::middleware::Next,
2224) -> axum::response::Response {
2225    use axum::response::IntoResponse;
2226    let Some(limit) = limit else {
2227        return next.run(req).await;
2228    };
2229    match tokio::time::timeout(limit + BACKSTOP_GRACE, next.run(req)).await {
2230        Ok(res) => res,
2231        Err(_) => Error::Internal(anyhow!(
2232            "the request took longer than REQUEST_TIMEOUT ({}s) before reaching its handler",
2233            limit.as_secs()
2234        ))
2235        .into_response(),
2236    }
2237}
2238
2239/// Adds a module's routes; what axum refuses to merge is a boot error.
2240fn merge_routes(
2241    router: Router<AppState>,
2242    other: Router<AppState>,
2243    module: &str,
2244) -> Result<Router<AppState>> {
2245    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| router.merge(other))).map_err(
2246        |panic| {
2247            let message = crate::error::panic_message(&*panic);
2248            anyhow!("the routes of the `{module}` module clash: {message}").into()
2249        },
2250    )
2251}
2252
2253/// A route of `module` that another module defines already (on the same
2254/// domain, or both without one).
2255fn check_clashes(
2256    listing: &[RouteInfo],
2257    new: &[RouteInfo],
2258    domain: Option<&str>,
2259    module: &str,
2260) -> Result {
2261    for info in new {
2262        let clash = listing.iter().find(|other| {
2263            other.domain.as_deref() == domain
2264                && other.path == info.path
2265                && (other.method == info.method || other.method == "*" || info.method == "*")
2266        });
2267        if let Some(other) = clash {
2268            let on = domain.map(|d| format!(" on {d}")).unwrap_or_default();
2269            return Err(anyhow!(
2270                "{} {}{on} is defined by both the `{}` and the `{module}` module",
2271                info.method,
2272                info.path,
2273                other.module,
2274            )
2275            .into());
2276        }
2277    }
2278    Ok(())
2279}
2280
2281/// `Registry::asset` paths: each starts with `/` and is used once.
2282fn check_assets(assets: &[crate::registry::StaticAsset]) -> Result<()> {
2283    let mut seen = std::collections::HashSet::new();
2284    for asset in assets {
2285        if !asset.path.starts_with('/') || asset.path.contains(['{', '}']) {
2286            return Err(anyhow!(
2287                "Registry::asset(\"{}\", …): the path must start with `/` and have no `{{…}}` parameters",
2288                asset.path
2289            )
2290            .into());
2291        }
2292        if !seen.insert(asset.path) {
2293            return Err(anyhow!(
2294                "two modules serve a file at `{}` (Registry::asset)",
2295                asset.path
2296            )
2297            .into());
2298        }
2299    }
2300    Ok(())
2301}
2302
2303fn build_router(
2304    router: Router<AppState>,
2305    state: AppState,
2306    embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2307    fallback: Option<axum::routing::MethodRouter<AppState>>,
2308    static_assets: &[crate::registry::StaticAsset],
2309    pwa: Option<&crate::pwa::PwaParts>,
2310) -> Router {
2311    // No route and no public file: the app's fallback (`Routes::fallback`), else a 404.
2312    let fallback = fallback.map(|handler| handler.with_state(state.clone()));
2313    let not_found = move |req: axum::extract::Request| {
2314        let fallback = fallback.clone();
2315        async move {
2316            match fallback {
2317                Some(handler) => match tower::ServiceExt::oneshot(handler, req).await {
2318                    Ok(res) => res,
2319                    Err(never) => match never {},
2320                },
2321                None => axum::response::IntoResponse::into_response(Error::NotFound),
2322            }
2323        }
2324    };
2325    let router = router
2326        .merge(crate::storage::router())
2327        .merge(crate::grid::router())
2328        .merge(csrf::router())
2329        .merge(crate::live_component::route::router());
2330    let router = if state.config.debug {
2331        router
2332            .merge(crate::mail::preview_router())
2333            .merge(crate::inspector::router())
2334    } else {
2335        router
2336    };
2337    let public = state.config.public_path.clone();
2338    let router = if let Some(files) = embedded_public {
2339        let files = crate::embedded::public_map(files);
2340        let not_found = not_found.clone();
2341        router.fallback(move |req: axum::extract::Request| {
2342            let (files, not_found) = (files.clone(), not_found.clone());
2343            async move {
2344                let res = crate::embedded::serve(&files, req.uri());
2345                if res.status() == axum::http::StatusCode::NOT_FOUND {
2346                    not_found(req).await
2347                } else {
2348                    res
2349                }
2350            }
2351        })
2352    } else if public.is_dir() {
2353        // `fallback`, not `not_found_service`: the latter makes every answer
2354        // a 404, and an app's fallback may redirect or answer 200.
2355        let files = ServeDir::new(public).fallback(not_found.clone().into_service());
2356        router.fallback(move |req: axum::extract::Request| {
2357            let files = files.clone();
2358            async move {
2359                // A name no file system accepts (over 255 bytes) can't be a
2360                // file here; asking the OS would be a "name too long" 500.
2361                if req
2362                    .uri()
2363                    .path()
2364                    .split('/')
2365                    .any(|segment| segment.len() > 255)
2366                {
2367                    return axum::response::IntoResponse::into_response(Error::NotFound);
2368                }
2369                let versioned = crate::embedded::is_versioned(req.uri());
2370                match tower::ServiceExt::oneshot(files, req).await {
2371                    Ok(res) => {
2372                        let mut res = axum::response::IntoResponse::into_response(res);
2373                        if versioned && res.status().is_success() {
2374                            res.headers_mut().insert(
2375                                axum::http::header::CACHE_CONTROL,
2376                                axum::http::HeaderValue::from_static(
2377                                    "public, max-age=31536000, immutable",
2378                                ),
2379                            );
2380                        }
2381                        res
2382                    }
2383                    Err(never) => match never {},
2384                }
2385            }
2386        })
2387    } else {
2388        router.fallback(not_found)
2389    };
2390
2391    let request_timeout = state.config.request_timeout;
2392    let router: Router = router
2393        .layer(from_fn(
2394            move |req: axum::extract::Request, next: axum::middleware::Next| {
2395                guard(request_timeout, req, next)
2396            },
2397        ))
2398        .layer(from_fn_with_state(
2399            state.clone(),
2400            crate::maintenance::middleware,
2401        ))
2402        .layer(from_fn_with_state(state.clone(), view::middleware))
2403        .layer(from_fn(csrf::middleware))
2404        .layer(from_fn_with_state(state.clone(), auth::middleware))
2405        .layer(from_fn_with_state(state.clone(), crate::i18n::middleware))
2406        .layer(from_fn_with_state(state.clone(), session::middleware))
2407        // Each request's own `renox::context`, around everything the app runs.
2408        .layer(from_fn_with_state(
2409            state.clone(),
2410            crate::context::middleware,
2411        ))
2412        .layer(from_fn(
2413            move |req: axum::extract::Request, next: axum::middleware::Next| {
2414                backstop(request_timeout, req, next)
2415            },
2416        ))
2417        // `/_renox/debug`: around it all, so the session's and user's SQL count.
2418        .layer(from_fn_with_state(
2419            state.clone(),
2420            crate::inspector::middleware,
2421        ))
2422        .merge(assets::router())
2423        .merge(assets::module_router(static_assets))
2424        .merge(crate::health::router())
2425        .merge(robots(&state, embedded_public))
2426        .merge(pwa_routes(&state, embedded_public, pwa))
2427        .merge(favicon(&state, embedded_public))
2428        .merge(crate::live::router())
2429        .merge(public_files(&state))
2430        .layer(axum::extract::DefaultBodyLimit::max(
2431            state.config.upload_max_size,
2432        ))
2433        .layer(
2434            TraceLayer::new_for_http().make_span_with(|req: &axum::extract::Request| {
2435                let ip = crate::ClientIp::of(req).map(|ip| ip.to_string());
2436                let id = req
2437                    .headers()
2438                    .get(crate::request_id::HEADER)
2439                    .and_then(|v| v.to_str().ok())
2440                    .unwrap_or_default();
2441                tracing::info_span!(
2442                    "request",
2443                    id = %id,
2444                    method = %req.method(),
2445                    uri = %req.uri(),
2446                    ip = ip.as_deref().unwrap_or("unknown"),
2447                )
2448            }),
2449        )
2450        .layer(from_fn(crate::request_id::middleware))
2451        .with_state(state.clone());
2452    // Method spoofing must change the method before the router matches it.
2453    let limit = state.config.upload_max_size;
2454    let spoofing = from_fn(
2455        move |req: axum::extract::Request, next: axum::middleware::Next| {
2456            crate::method::middleware(req, next, limit)
2457        },
2458    );
2459    // Security headers outermost, so every response gets them, including
2460    // the method-spoofing layer's own 413.
2461    Router::new()
2462        .fallback_service(tower::Layer::layer(&spoofing, router))
2463        .layer(from_fn_with_state(state, crate::security::middleware))
2464}
2465
2466/// Whether the app ships `name` in `public/` (on disk, or embedded).
2467fn has_public_file(
2468    state: &AppState,
2469    embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2470    name: &str,
2471) -> bool {
2472    match embedded_public {
2473        Some(files) => files.iter().any(|(path, _)| *path == name),
2474        None => state.config.public_path.join(name).is_file(),
2475    }
2476}
2477
2478/// The generated `/robots.txt`, unless the app ships its own in `public/`.
2479fn robots(
2480    state: &AppState,
2481    embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2482) -> Router<AppState> {
2483    if has_public_file(state, embedded_public, "robots.txt") {
2484        Router::new()
2485    } else {
2486        crate::seo::robots_router(state)
2487    }
2488}
2489
2490/// The PWA routes, outside sessions. An app's own `public/manifest.webmanifest`
2491/// or `public/sw.js` replaces the generated one.
2492fn pwa_routes(
2493    state: &AppState,
2494    embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2495    pwa: Option<&crate::pwa::PwaParts>,
2496) -> Router<AppState> {
2497    let Some((pwa, assets, resolver)) = pwa else {
2498        return Router::new();
2499    };
2500    if let Some(resolver) = resolver {
2501        return resolver.clone().router(
2502            pwa.clone(),
2503            assets.clone(),
2504            !has_public_file(state, embedded_public, "manifest.webmanifest"),
2505            !has_public_file(state, embedded_public, "sw.js"),
2506        );
2507    }
2508    let mut router = assets
2509        .clone()
2510        .router(!has_public_file(state, embedded_public, "sw.js"));
2511    if !has_public_file(state, embedded_public, "manifest.webmanifest") {
2512        router = router.merge(pwa.clone().manifest_router());
2513    }
2514    router
2515}
2516
2517/// `/favicon.ico` answers 204 (no icon, cached for a day) unless the app
2518/// ships one in `public/`: browsers ask for it on every site, and a 404
2519/// would run the whole stack, render the error page and log it each time.
2520fn favicon(
2521    state: &AppState,
2522    embedded_public: Option<&'static [(&'static str, &'static [u8])]>,
2523) -> Router<AppState> {
2524    if has_public_file(state, embedded_public, "favicon.ico") {
2525        return Router::new();
2526    }
2527    Router::new().route(
2528        "/favicon.ico",
2529        axum::routing::get(|| async {
2530            (
2531                axum::http::StatusCode::NO_CONTENT,
2532                [(axum::http::header::CACHE_CONTROL, "public, max-age=86400")],
2533            )
2534        }),
2535    )
2536}
2537
2538/// Public files of the local disk at `/storage/...`, outside sessions.
2539fn public_files(state: &AppState) -> Router<AppState> {
2540    match state.storage.public_root() {
2541        Some(root) => Router::new()
2542            .nest_service("/storage", ServeDir::new(root))
2543            .layer(axum::middleware::map_response(user_file_headers)),
2544        None => Router::new(),
2545    }
2546}
2547
2548/// Uploaded files are other people's content served from the app's origin:
2549/// a sandbox CSP keeps any HTML or SVG among them from running scripts,
2550/// `nosniff` stops browsers guessing a type, and documents are downloaded
2551/// instead of displayed.
2552pub(crate) async fn user_file_headers(
2553    mut res: axum::response::Response,
2554) -> axum::response::Response {
2555    use axum::http::HeaderValue;
2556    use axum::http::header::{
2557        CONTENT_DISPOSITION, CONTENT_SECURITY_POLICY, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS,
2558    };
2559
2560    let content_type = res
2561        .headers()
2562        .get(CONTENT_TYPE)
2563        .and_then(|v| v.to_str().ok())
2564        .unwrap_or_default()
2565        .to_ascii_lowercase();
2566    let headers = res.headers_mut();
2567    headers.insert(
2568        CONTENT_SECURITY_POLICY,
2569        HeaderValue::from_static(
2570            "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox",
2571        ),
2572    );
2573    headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
2574    let document = ["html", "xml", "javascript", "ecmascript"]
2575        .iter()
2576        .any(|kind| content_type.contains(kind))
2577        && !content_type.contains("svg");
2578    if document {
2579        headers.insert(CONTENT_DISPOSITION, HeaderValue::from_static("attachment"));
2580    }
2581    res
2582}
2583
2584/// Long-running commands log at info; others only log warnings and errors.
2585fn init_tracing(config: &Config, long_running: bool) {
2586    let default = match (long_running, config.debug) {
2587        (true, true) => "info,renox=debug",
2588        (true, false) => "info",
2589        (false, _) => "warn",
2590    };
2591    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default));
2592    // LOG_FILE appends to a file (rotate it with logrotate, or leave logs to
2593    // journald/Docker on stdout); LOG_FORMAT=json writes one JSON object per
2594    // line, with the request span's fields (id, method, uri, ip).
2595    let file = config.log_file.as_ref().and_then(|path| {
2596        match std::fs::OpenOptions::new()
2597            .create(true)
2598            .append(true)
2599            .open(path)
2600        {
2601            Ok(file) => Some(std::sync::Mutex::new(file)),
2602            Err(err) => {
2603                eprintln!("LOG_FILE {}: {err}; logging to stdout", path.display());
2604                None
2605            }
2606        }
2607    });
2608    let json = config.log_format == crate::LogFormat::Json;
2609    let builder = tracing_subscriber::fmt().with_env_filter(filter);
2610    let _ = match (json, file) {
2611        (true, Some(file)) => builder
2612            .json()
2613            .with_current_span(true)
2614            .with_span_list(false)
2615            .with_writer(file)
2616            .try_init(),
2617        (true, None) => builder
2618            .json()
2619            .with_current_span(true)
2620            .with_span_list(false)
2621            .try_init(),
2622        (false, Some(file)) => builder.with_ansi(false).with_writer(file).try_init(),
2623        (false, None) => builder.try_init(),
2624    };
2625}
2626
2627async fn shutdown_signal() {
2628    let ctrl_c = async {
2629        let _ = tokio::signal::ctrl_c().await;
2630    };
2631
2632    #[cfg(unix)]
2633    let terminate = async {
2634        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
2635            Ok(mut signal) => {
2636                signal.recv().await;
2637            }
2638            Err(_) => std::future::pending().await,
2639        }
2640    };
2641    #[cfg(not(unix))]
2642    let terminate = std::future::pending::<()>();
2643
2644    tokio::select! {
2645        _ = ctrl_c => {},
2646        _ = terminate => {},
2647    }
2648    tracing::info!("shutdown signal received");
2649}
2650
2651#[cfg(test)]
2652mod tests {
2653    use super::*;
2654
2655    fn route(path: &str, middleware: &[&str]) -> RouteInfo {
2656        RouteInfo {
2657            method: "GET".into(),
2658            path: path.into(),
2659            name: None,
2660            module: "app".into(),
2661            middleware: middleware.iter().map(|m| (*m).to_owned()).collect(),
2662            domain: None,
2663        }
2664    }
2665
2666    #[test]
2667    fn route_list_says_role_guards_count_the_active_scope() {
2668        let plain = route_table(&[route("/", &["auth"])]);
2669        assert!(!plain.contains('*'), "{plain}");
2670        let table = route_table(&[
2671            route("/orders", &["auth", "permission:orders.view"]),
2672            route("/drafts", &["role:editor"]),
2673            route("/admin", &["gate:admin"]),
2674        ]);
2675        assert!(table.contains("auth, permission:orders.view*"), "{table}");
2676        assert!(table.contains("role:editor*"), "{table}");
2677        assert!(table.contains("gate:admin\n"), "{table}");
2678        assert!(
2679            table.contains("active scope (permissions::set_scope)"),
2680            "{table}"
2681        );
2682    }
2683
2684    struct Note;
2685    impl crate::db::FromRow for Note {
2686        fn from_row(_: &crate::db::Row) -> Result<Self, crate::db::DbError> {
2687            Ok(Note)
2688        }
2689    }
2690    impl crate::db::Model for Note {
2691        const TABLE: &'static str = "notes";
2692        const COLUMNS: &'static [&'static str] = &["id"];
2693        type Key = i64;
2694        fn id(&self) -> i64 {
2695            0
2696        }
2697        fn set_id(&mut self, _: i64) {}
2698        fn values(&self) -> Vec<crate::db::DbValue> {
2699            Vec::new()
2700        }
2701    }
2702
2703    struct Registers;
2704    impl Module for Registers {
2705        fn name(&self) -> &'static str {
2706            "registers"
2707        }
2708        fn register(&self, app: &mut Registry) {
2709            app.model::<crate::auth::User>();
2710        }
2711    }
2712
2713    #[tokio::test]
2714    async fn models_are_kept_once_from_the_app_and_modules() {
2715        let boot = |app: App| async move { app.config(Config::default()).boot().await.unwrap() };
2716        let one = boot(
2717            App::new()
2718                .model::<crate::auth::User>()
2719                .model::<crate::auth::User>()
2720                .module(Registers),
2721        )
2722        .await;
2723        assert_eq!(one.models().len(), 1);
2724        assert_eq!(one.models()[0].table, "users");
2725        let two = boot(
2726            App::new()
2727                .model::<crate::auth::User>()
2728                .model::<Note>()
2729                .module(Registers),
2730        )
2731        .await;
2732        assert_eq!(two.models().len(), 2);
2733    }
2734}