Skip to main content

rustango_cms/admin/
mod.rs

1//! R-CMS admin section.
2//!
3//! Mounts at `/cms-admin/` (distinct from rustango's `/__admin/` —
4//! the framework admin's POST handlers do raw `insert_returning`
5//! against the DB, bypassing our `Page::create_root` /
6//! `Page::create_child` paths and producing malformed rows with
7//! empty `path`, `depth = 0`, and no type-whitelist enforcement).
8//!
9//! This module owns the page-tree-aware CRUD surface. [`router`] is
10//! unauthenticated on its own: wrap it in [`with_login_required`], which
11//! redirects anonymous visitors to the login URL and requires the
12//! `cms_admin.access` codename (or superuser) of signed-in users.
13//!
14//! ## Wiring
15//!
16//! ```ignore
17//! use std::sync::Arc;
18//! use tera::Tera;
19//!
20//! let mut tera = Tera::new("templates/**/*.html")?;
21//! rustango_cms::admin::register_templates(&mut tera)?;
22//! let tera = Arc::new(tera);
23//!
24//! let cms_admin = rustango_cms::admin::with_login_required(
25//!     rustango_cms::admin::router(tera.clone()),
26//!     "/login",
27//! );
28//! let router = Router::new()
29//!     .merge(cms_admin)
30//!     .merge(rustango_cms::router(tera));
31//! ```
32
33use std::sync::Arc;
34
35use axum::http::StatusCode;
36use axum::response::{IntoResponse, Response};
37use axum::routing::{get, post};
38use axum::Router;
39use serde::Deserialize;
40use tera::Tera;
41
42use crate::page::PageStatus;
43use crate::tree_ops::TreeError;
44
45pub mod admin_page;
46
47/// Fill a template context with the admin chrome — sidebar, branding,
48/// locale, the signed-in user.
49///
50/// Re-exported for host applications implementing
51/// [`admin_page::AdminPageHandler`]: a custom page that extends
52/// `rcms_admin/_base.html` cannot render without it, and reproducing it
53/// by hand means roughly two dozen variables that drift silently on the
54/// next release.
55pub use handlers::add_chrome;
56pub use handlers::issue_password_reset_link;
57
58pub mod chooser;
59mod handlers;
60mod i18n;
61pub(crate) mod members;
62pub use members::{authenticate_member, MemberLoginError};
63/// Merge host-supplied UI-catalog entries into the shared admin translator
64/// so a consumer's own template chrome localizes through the same
65/// `translate` binding without clobbering the admin catalog.
66pub use i18n::extend_ui_catalog;
67pub mod model_admin;
68pub mod pagination;
69pub mod report;
70pub mod resources;
71mod route_perms;
72pub(crate) mod notifications;
73pub(crate) mod sites;
74pub(crate) mod template_editor;
75/// Permission codename gating the per-tenant template editor. Re-exported
76/// so seeding and the handler cannot drift apart on the string.
77pub use template_editor::CODENAME as TEMPLATE_EDIT_CODENAME;
78/// Permission gating notification destinations — see
79/// [`notifications::CODENAME`].
80pub use notifications::CODENAME as NOTIFICATION_MANAGE_CODENAME;
81/// Permission gating hostname → root-page mappings — see
82/// [`sites::CODENAME`].
83pub use sites::CODENAME as SITE_MANAGE_CODENAME;
84/// Whether a template is a sensible choice for a page type. Shared so the
85/// admin picker and the MCP tool cannot drift on the rule.
86pub(crate) use template_editor::offerable as template_offerable;
87pub use handlers::ListQuery;
88// #587 — the crate's MCP tools reuse the admin write/read paths.
89pub(crate) use handlers::{
90    allowed_children_for, allowed_root_types, apply_page_edit, dedup_slug_under_parent,
91    media_picker_payload, slugify, store_media, upsert_page_translations, MediaPickerQuery,
92    PageEditActor, PageEditOutcome, PageEditRefusal,
93};
94
95/// Admin-handler state — the Tera instance the handlers render
96/// against, plus an optional page-cache invalidator. When the
97/// host registers an invalidator, admin saves and deletes fire
98/// purges on the affected URLs so editors don't have to wait for the
99/// public-side TTL to elapse.
100#[derive(Clone)]
101pub(crate) struct AdminState {
102    pub(crate) tera: Arc<Tera>,
103    /// HMAC secret used to sign password-reset URLs. Loaded once at
104    /// boot via [`rustango::session::SessionSecret::from_env_or_disk`]
105    /// so reset links stay valid across server restarts. Keep
106    /// `Arc<Vec<u8>>` (not `&[u8]`) so the state is `Clone` for
107    /// axum's per-request state cloning.
108    pub(crate) signing_secret: Arc<Vec<u8>>,
109    /// Page-cache invalidator. Defaults to
110    /// [`cache_invalidate::Noop`] — the public layer's TTL is the
111    /// only invalidation signal. Hosts that wire a real cache into
112    /// the public router pass a matching [`crate::cache_invalidate::BoxedCacheInvalidator`]
113    /// via [`router_with_invalidator`] so admin saves purge those
114    /// keys immediately.
115    pub(crate) cache_invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
116    /// Workflow notification mailer. Defaults to `None` — no
117    /// email is sent. Hosts wire a real backend
118    /// (`rustango::email::ConsoleMailer`, an SMTP one, an SES one)
119    /// via [`router_with_mailer`].
120    pub(crate) mailer: Option<Arc<dyn rustango::email::Mailer>>,
121    /// `From:` address stamped onto every workflow notification.
122    /// Set via [`router_with_mailer`]; ignored when `mailer` is
123    /// `None`.
124    pub(crate) mailer_from: Arc<String>,
125}
126
127/// Build the admin router. Mount with `Router::merge` in the host
128/// app's main router.
129///
130/// **Auth note:** the returned router is *unprotected* — every host
131/// app should layer [`with_login_required`] on top (or equivalent
132/// reverse-proxy basic auth).
133///
134/// Password-reset links are signed with a key derived from the CMS
135/// signing secret ([`crate::signing::secret`]), so they stay valid across
136/// restarts and replicas.
137pub fn router(tera: Arc<Tera>) -> Router {
138    let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
139    crate::perf::instrument(router_with_state(AdminState {
140        tera,
141        signing_secret: Arc::new(secret),
142        cache_invalidator: crate::cache_invalidate::noop(),
143        mailer: None,
144        mailer_from: Arc::new(String::new()),
145    }))
146}
147
148/// Like [`router`] but takes a page-cache invalidator. Hosts
149/// using the public router's `CachePageLayer` should wire the same
150/// cache backend into a [`crate::cache_invalidate::BoxedCacheInvalidator`]
151/// so admin saves purge the matching cache keys immediately.
152pub fn router_with_invalidator(
153    tera: Arc<Tera>,
154    invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
155) -> Router {
156    let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
157    // Queued purge jobs a worker drains without this router fall back to it (#732).
158    crate::task_queue::set_default_invalidator(Arc::clone(&invalidator));
159    router_with_state(AdminState {
160        tera,
161        signing_secret: Arc::new(secret),
162        cache_invalidator: invalidator,
163        mailer: None,
164        mailer_from: Arc::new(String::new()),
165    })
166}
167
168/// Like [`router`] but takes both a cache invalidator AND a mailer.
169/// The mailer powers workflow notifications — submit /
170/// approve / reject / cancel each fire emails to the relevant
171/// parties. `from_addr` is the `From:` address stamped onto every
172/// notification.
173pub fn router_with_mailer(
174    tera: Arc<Tera>,
175    invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
176    mailer: Arc<dyn rustango::email::Mailer>,
177    from_addr: impl Into<String>,
178) -> Router {
179    let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
180    // Queued purge jobs a worker drains without this router fall back to it (#732).
181    crate::task_queue::set_default_invalidator(Arc::clone(&invalidator));
182    router_with_state(AdminState {
183        tera,
184        signing_secret: Arc::new(secret),
185        cache_invalidator: invalidator,
186        mailer: Some(mailer),
187        mailer_from: Arc::new(from_addr.into()),
188    })
189}
190
191/// Companion to [`router`] — routes that must remain reachable
192/// *without* authentication (password reset). Host apps merge this
193/// alongside the protected admin router so anonymous visitors can
194/// hit `/cms-admin/password-reset*` even when the rest of
195/// `/cms-admin/*` is gated by [`with_login_required`].
196///
197/// Typical wiring:
198///
199/// ```ignore
200/// let admin = rustango_cms::admin::public_router(tera.clone())
201///     .merge(rustango_cms::admin::with_login_required(
202///         rustango_cms::admin::router(tera.clone()),
203///         "/login",
204///     ));
205/// ```
206pub fn public_router(tera: Arc<Tera>) -> Router {
207    public_router_inner(tera, None, String::new())
208}
209
210/// Like [`public_router`], with the mailer that sends password-reset
211/// emails. Without it `/cms-admin/password-reset` accepts the
212/// request but can't send anything. Pass the same mailer and `From:`
213/// address as [`router_with_mailer`].
214pub fn public_router_with_mailer(
215    tera: Arc<Tera>,
216    mailer: Arc<dyn rustango::email::Mailer>,
217    from_addr: impl Into<String>,
218) -> Router {
219    public_router_inner(tera, Some(mailer), from_addr.into())
220}
221
222fn public_router_inner(
223    tera: Arc<Tera>,
224    mailer: Option<Arc<dyn rustango::email::Mailer>>,
225    mailer_from: String,
226) -> Router {
227    let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
228    let state = AdminState {
229        tera,
230        signing_secret: Arc::new(secret),
231        cache_invalidator: crate::cache_invalidate::noop(),
232        mailer,
233        mailer_from: Arc::new(mailer_from),
234    };
235    Router::new()
236        .route(
237            "/cms-admin/password-reset",
238            get(handlers::password_reset_request_form)
239                .post(handlers::password_reset_request_submit),
240        )
241        .route(
242            "/cms-admin/password-reset/confirm",
243            get(handlers::password_reset_confirm_form)
244                .post(handlers::password_reset_confirm_submit),
245        )
246        // CMS-branded login GET — host apps merge this BEFORE the
247        // framework's login router so this route wins on conflict.
248        // The framework's POST `/login` (auth + cookie set) still
249        // handles submits since we only override GET.
250        .route("/login", get(handlers::cms_login_form))
251        // Public members-area auth (#members) — self-service password
252        // sign-up + sign-in, minting the member session cookie. SSO /
253        // social sign-in for members is the framework's
254        // `member_sso_router`, mounted by the host at `/members/auth`.
255        // These are public (no `with_login_required`) but their POSTs
256        // ride the host's CSRF layer like every other admin form.
257        .route(
258            "/members/login",
259            get(members::member_login_form).post(members::member_login_submit),
260        )
261        .route(
262            "/members/signup",
263            get(members::member_signup_form).post(members::member_signup_submit),
264        )
265        .route("/members/logout", post(members::member_logout))
266        // #199 — uploaded branding assets, served pre-auth so the login +
267        // password-reset screens can show the tenant logo/favicon (the
268        // authenticated sidebar uses the same URLs). Anonymous-OK: these are
269        // public brand images, no auth-sensitive content.
270        .route(
271            "/__cms-branding/logo",
272            get(handlers::settings_branding_serve_logo),
273        )
274        .route(
275            "/__cms-branding/favicon",
276            get(handlers::settings_branding_serve_favicon),
277        )
278        // #35 — `cms_admin.access` deny page. Lives in public_router
279        // so the `with_cms_admin_access` middleware can redirect to
280        // it without the gate then bouncing the redirect back.
281        .route("/cms-admin/no-access", get(handlers::no_access_page))
282        // Admin stylesheet — must be reachable pre-auth so the login
283        // + password-reset screens can load it. Host apps override by
284        // dropping `static/cms_admin/cms.css` in their project root.
285        .route("/cms-admin/static/cms.css", get(serve_cms_css))
286        // Static admin JS bundles — same pre-auth requirement as the
287        // stylesheet. The login + password-reset chrome reaches for
288        // `cms-ux.js` (confirm dialogs, toast hoist), so gating them
289        // behind `with_login_required` (#258) would 302-loop the
290        // login page on its own assets. Stream-editor + menu-builder
291        // bundles are only used on protected pages but co-locating
292        // them here keeps the routing block tight; they 200 either
293        // way since they have no auth-sensitive content.
294        // #615 — self-hosted typography + icon font. Pre-auth, like the
295        // stylesheet: the login chrome uses the same families.
296        .route("/cms-admin/static/fonts.css", get(serve_admin_fonts_css))
297        .route(
298            "/cms-admin/static/vendor/fonts/{file}",
299            get(serve_admin_font_file),
300        )
301        // The Rustango CMS badge + icon: the login screen, the sidebar mark
302        // and the favicon when a tenant hasn't uploaded its own. Pre-auth,
303        // like the stylesheet.
304        .route("/cms-admin/static/brand/{file}", get(serve_admin_brand_file))
305        .route("/cms-admin/static/cms-ux.js", get(serve_cms_ux_js))
306        .route(
307            "/cms-admin/static/stream_editor.js",
308            get(serve_stream_editor_js),
309        )
310        // Block-tree sidebar outline for the page editor (self-activating
311        // on pages with a stream root).
312        .route("/cms-admin/static/block_tree.js", get(serve_block_tree_js))
313        .route("/cms-admin/static/cms-preview.js", get(serve_cms_preview_js))
314        .route(
315            "/cms-admin/static/menu-builder.js",
316            get(serve_menu_builder_js),
317        )
318        // #533 FB-04 — visual Form Builder editor engine.
319        .route(
320            "/cms-admin/static/form_builder.js",
321            get(serve_form_builder_js),
322        )
323        .route(
324            "/cms-admin/static/page_type_builder.js",
325            get(serve_page_type_builder_js),
326        )
327        // #564 — conditional-rules runtime for builder body fields.
328        .route(
329            "/cms-admin/static/page_builder_rules.js",
330            get(serve_page_builder_rules_js),
331        )
332        // #208 — axe-core is self-hosted (553 KB minified). The
333        // preview iframe loads it via this URL on every reload so
334        // the editor's accessibility panel can surface client-side
335        // findings alongside the server-side heuristics (#116).
336        .route(
337            "/cms-admin/static/vendor/axe-core.min.js",
338            get(serve_axe_core_js),
339        )
340        // #208 — small companion glue script. Runs inside the
341        // preview iframe after axe-core loads, kicks off `axe.run()`,
342        // and `postMessage`s the violations back to the editor.
343        .route(
344            "/cms-admin/static/cms-axe-preview.js",
345            get(serve_cms_axe_preview_js),
346        )
347        // Preview navigation guard — injected into the preview iframe so
348        // link/form clicks don't navigate the contained render away.
349        .route(
350            "/cms-admin/static/cms-preview-guard.js",
351            get(serve_cms_preview_guard_js),
352        )
353        // #294 — self-hosted TipTap (MIT) richtext editor: the vendored
354        // engine bundle + the hand-authored toolbar/wiring glue.
355        .route(
356            "/cms-admin/static/template-editor.js",
357            get(serve_template_editor_js),
358        )
359        .route(
360            "/cms-admin/static/vendor/codemirror.bundle.js",
361            get(serve_codemirror_bundle_js),
362        )
363        .route(
364            "/cms-admin/static/vendor/tiptap.bundle.js",
365            get(serve_tiptap_bundle_js),
366        )
367        .route(
368            "/cms-admin/static/richtext-editor.js",
369            get(serve_richtext_editor_js),
370        )
371        // #710 — the notices the vendored assets' licences require.
372        .route(
373            "/cms-admin/static/vendor/THIRD-PARTY-NOTICES.txt",
374            get(serve_third_party_notices),
375        )
376        // #652 — login, reset and member screens render translated chrome too.
377        .route_layer(axum::middleware::from_fn(i18n::tenant_overrides_layer))
378        .with_state(state)
379}
380
381/// Licence notices for the third-party assets compiled into the admin.
382/// Embedded so they travel with every binary, as MIT and the
383/// SIL OFL require.
384async fn serve_third_party_notices() -> impl axum::response::IntoResponse {
385    (
386        [(
387            axum::http::header::CONTENT_TYPE,
388            axum::http::HeaderValue::from_static("text/plain; charset=utf-8"),
389        )],
390        include_str!("static/vendor/THIRD-PARTY-NOTICES.txt"),
391    )
392}
393
394/// Purpose label for the key that signs password-reset links (derived
395/// from [`crate::signing::secret`]).
396const PASSWORD_RESET_KEY_PURPOSE: &str = "rcms:password-reset";
397
398/// Layer [`rustango::auth_decorators::login_required`] on top of the
399/// supplied router. Every protected route 302s anonymous visitors to
400/// `login_url` with `?next=<original_url>` so the framework's login
401/// handler can resume them after auth.
402///
403/// A signed-in user also needs the `cms_admin.access` codename (or to be
404/// a superuser); anyone else is redirected to `/cms-admin/no-access`.
405/// Members sign up publicly and get an ordinary user row, so "has a
406/// session" must never mean "may use the admin".
407///
408/// Use as:
409///
410/// ```ignore
411/// let cms_admin = rustango_cms::admin::with_login_required(
412///     rustango_cms::admin::router(tera.clone()),
413///     "/login",
414/// );
415/// ```
416///
417/// Tri-dialect on every backend. Built on
418/// [`rustango::extractors::SessionUser`], which became tri-dialect
419/// in the framework — anonymous requests get 302'd to `login_url`
420/// with the original path preserved in `?next=` exactly like the
421/// framework's PG-only `auth_decorators::login_required` decorator.
422///
423/// An earlier non-PG arm was a silent no-op that
424/// left `/cms-admin/*` fully accessible without a session cookie on
425/// `default = ["sqlite"]` builds.
426pub fn with_login_required(router: Router, login_url: impl Into<String> + 'static) -> Router {
427    use axum::middleware::{from_fn, Next};
428    let login_url: Arc<str> = Arc::from(login_url.into());
429    router.layer(from_fn(
430        move |req: axum::http::Request<axum::body::Body>, next: Next| {
431            let login_url = login_url.clone();
432            async move {
433                use axum::extract::FromRequestParts as _;
434                let (mut parts, body) = req.into_parts();
435                let user = rustango::extractors::SessionUser::from_request_parts(&mut parts, &())
436                    .await
437                    .unwrap_or(rustango::extractors::SessionUser(None));
438                if let Some(user) = user.0 {
439                    // A session alone is not admin access (#671): members sign
440                    // up publicly and hold an ordinary user row, so the admin
441                    // also needs `cms_admin.access` — every seeded staff role
442                    // carries it, a self-registered member carries none.
443                    // Static assets stay open so the no-access page can style
444                    // itself; that page lives on `public_router`.
445                    let allowed = user.is_superuser
446                        || parts.uri.path().starts_with("/cms-admin/static/")
447                        || matches!(
448                            check_codename(&mut parts, "cms_admin.access").await,
449                            AccessResult::Allowed
450                        );
451                    if !allowed {
452                        use axum::response::IntoResponse as _;
453                        return axum::response::Redirect::to("/cms-admin/no-access").into_response();
454                    }
455                    let req = axum::http::Request::from_parts(parts, body);
456                    return next.run(req).await;
457                }
458                // Anonymous — bounce to login with `?next=` carrying the
459                // original URL. Reuses the framework's redirect helper so
460                // the response shape matches the PG-side decorator exactly.
461                let original = parts
462                    .uri
463                    .path_and_query()
464                    .map(|p| p.as_str().to_owned())
465                    .unwrap_or_else(|| "/".to_owned());
466                rustango::auth_decorators::redirect_to_login(&login_url, "next", &original)
467            }
468        },
469    ))
470}
471
472/// Gate the CMS-admin router on the `cms_admin.access` codename.
473///
474/// A logged-in tenant user is allowed through only when:
475/// 1. they're a superuser, OR
476/// 2. one of their roles grants the `cms_admin.access` codename.
477///
478/// Otherwise the request is redirected to `no_access_url` (defaults
479/// to `/cms-admin/no-access`) so the user gets a friendly "you're
480/// signed in but not allowed here" page instead of an empty 403.
481///
482/// **Tri-dialect.** Resolves the user via the framework's
483/// `SessionUser` extractor. Anonymous requests pass through unchanged —
484/// pair this with [`with_login_required`] above so that hits the login
485/// flow first.
486pub fn with_cms_admin_access(router: Router, no_access_url: impl Into<String>) -> Router {
487    with_codename_gate(router, "cms_admin.access", no_access_url)
488}
489
490/// Hard-gate `router` on an arbitrary permission codename —
491/// the generalized form of [`with_cms_admin_access`]. A non-superuser
492/// lacking `codename` is redirected to `no_access_url`; superusers pass;
493/// anonymous flows fall through to the layered `login_required` bounce.
494/// Static assets + the no-access page itself always pass so the redirect
495/// can't loop and the page can style itself.
496pub fn with_codename_gate(
497    router: Router,
498    codename: &'static str,
499    no_access_url: impl Into<String>,
500) -> Router {
501    use axum::middleware::{from_fn, Next};
502    use axum::response::{IntoResponse, Redirect};
503    let no_access_url: Arc<str> = Arc::from(no_access_url.into());
504    router.layer(from_fn(
505        move |req: axum::http::Request<axum::body::Body>, next: Next| {
506            let no_access_url = no_access_url.clone();
507            async move {
508                let path = req.uri().path();
509                if path == &*no_access_url || path.starts_with("/cms-admin/static/") {
510                    return next.run(req).await;
511                }
512                let (mut parts, body) = req.into_parts();
513                let outcome = check_codename(&mut parts, codename).await;
514                let req = axum::http::Request::from_parts(parts, body);
515                match outcome {
516                    AccessResult::Allowed | AccessResult::DeniedNoUser => next.run(req).await,
517                    AccessResult::Denied => Redirect::to(&no_access_url).into_response(),
518                }
519            }
520        },
521    ))
522}
523
524enum AccessResult {
525    Allowed,
526    Denied,
527    /// No session cookie / decode failed — let the layered
528    /// `login_required` middleware handle the bounce to /login.
529    DeniedNoUser,
530}
531
532/// Tri-dialect check that the request's user holds `codename`. Now that
533/// `SessionUser` is no longer PG-gated, we delegate
534/// the cookie decode + user fetch to the framework's `SessionUser`
535/// extractor instead of duplicating the logic here. The middleware
536/// resolves the user, then checks for `codename` via
537/// `permissions::user_codenames`. Superusers always pass.
538/// The in-handler form of the codename gate, for screens gated per
539/// handler rather than per router: `None` to proceed, otherwise
540/// where to send the user — anonymous to the login page, a signed-in user
541/// without `codename` to no-access, so they aren't bounced through a login
542/// form that wouldn't help. Superusers pass. One copy of the policy for
543/// the template editor, sites, notifications and the page-type builder.
544pub(crate) async fn codename_gate(
545    tenant: &rustango::extractors::Tenant,
546    user: Option<&rustango::tenancy::auth::User>,
547    codename: &str,
548) -> Option<axum::response::Response> {
549    use axum::response::{IntoResponse, Redirect};
550    let Some(user) = user else {
551        return Some(Redirect::to("/login").into_response());
552    };
553    if user.is_superuser {
554        return None;
555    }
556    let uid = user.id.get().copied().unwrap_or_default();
557    let codes = crate::permissions::user_codenames(tenant.pool(), uid)
558        .await
559        .unwrap_or_default();
560    if codes.contains(codename) {
561        None
562    } else {
563        Some(Redirect::to("/cms-admin/no-access").into_response())
564    }
565}
566
567async fn check_codename(parts: &mut axum::http::request::Parts, codename: &str) -> AccessResult {
568    let (user, pool) = match request_user_and_pool(parts).await {
569        Ok(Some(found)) => found,
570        Ok(None) => return AccessResult::DeniedNoUser,
571        Err(()) => return AccessResult::Denied,
572    };
573    if user.is_superuser {
574        return AccessResult::Allowed;
575    }
576    let uid = user.id.get().copied().unwrap_or_default();
577    let codenames = crate::permissions::user_codenames(&pool, uid)
578        .await
579        .unwrap_or_default();
580    if codenames.contains(codename) {
581        AccessResult::Allowed
582    } else {
583        AccessResult::Denied
584    }
585}
586
587/// The request's session user and their tenant's pool. `Ok(None)` when
588/// there is no session or no tenant — the layered `login_required`
589/// bounce handles that; `Err` when there is a user but their tenant's
590/// pool can't be had, which callers must treat as a denial.
591pub(crate) async fn request_user_and_pool(
592    parts: &mut axum::http::request::Parts,
593) -> Result<Option<(rustango::tenancy::auth::User, rustango::sql::Pool)>, ()> {
594    use axum::extract::FromRequestParts as _;
595    use rustango::tenancy::OrgResolver as _;
596    use std::sync::Arc;
597
598    let Some(ctx) = parts
599        .extensions
600        .get::<Arc<rustango::extractors::TenantContext>>()
601        .cloned()
602    else {
603        return Ok(None);
604    };
605    // SessionUser is `Infallible`, so `from_request_parts` always
606    // returns `Ok` — the `Result` here is only the awaitable shape.
607    let Ok(rustango::extractors::SessionUser(Some(user))) =
608        rustango::extractors::SessionUser::from_request_parts(parts, &()).await
609    else {
610        return Ok(None);
611    };
612    let Ok(Some(org)) = ctx.resolver.resolve(parts, &ctx.pools.registry_pool()).await else {
613        return Ok(None);
614    };
615    let pool = ctx.pools.scoped_pool_dyn(&org).await.map_err(|_| ())?;
616    Ok(Some((user, pool)))
617}
618
619fn router_with_state(state: AdminState) -> Router {
620    Router::new()
621        // Pages tab — tree CRUD.
622        .route("/cms-admin", get(redirect_root))
623        .route("/cms-admin/", get(redirect_root))
624        .route("/cms-admin/pages", get(handlers::page_list))
625        .route(
626            "/cms-admin/pages/new",
627            get(handlers::page_new_form).post(handlers::page_new_submit),
628        )
629        .route(
630            "/cms-admin/pages/{id}/edit",
631            get(handlers::page_edit_form).post(handlers::page_edit_submit),
632        )
633        .route(
634            "/cms-admin/pages/{id}/translate",
635            post(handlers::page_translate_submit),
636        )
637        .route(
638            "/cms-admin/pages/{id}/delete",
639            post(handlers::page_delete_submit),
640        )
641        .route(
642            "/cms-admin/pages/{id}/preview",
643            get(handlers::page_preview).post(handlers::page_preview_draft),
644        )
645        // #430 — mint a headless preview token for the decoupled frontend.
646        .route(
647            "/cms-admin/pages/{id}/preview-token",
648            get(handlers::page_preview_token),
649        )
650        // One-click revert to any past revision.
651        .route(
652            "/cms-admin/pages/{id}/revert/{rev_id}",
653            post(handlers::page_revert_submit),
654        )
655        // #74 — side-by-side revision diff.
656        .route(
657            "/cms-admin/pages/{id}/history/diff",
658            get(handlers::history_diff),
659        )
660        // #192 — per-page audit log CSV export.
661        .route("/cms-admin/pages/{id}/log.csv", get(handlers::page_log_csv))
662        // Per-page permissions (#18) — JSON POST replaces the
663        // grant set for a single page.
664        .route(
665            "/cms-admin/pages/{id}/permissions",
666            post(handlers::page_permissions_submit),
667        )
668        // Drag-reorder (`new_parent` form field).
669        .route(
670            "/cms-admin/pages/{id}/move",
671            post(handlers::page_move_submit),
672        )
673        // #29 V1 — duplicate a page as a draft sibling.
674        .route(
675            "/cms-admin/pages/{id}/clone",
676            post(handlers::page_clone_submit),
677        )
678        // #75 — create a live alias of this page as a sibling.
679        .route(
680            "/cms-admin/pages/{id}/alias",
681            post(handlers::page_alias_submit),
682        )
683        // #76 — set or clear the per-page view restriction.
684        .route(
685            "/cms-admin/pages/{id}/privacy",
686            post(handlers::page_privacy_submit),
687        )
688        // #65 — multi-select bulk dispatch (publish / unpublish /
689        // delete / move). Body shape: `action=<verb>&ids=<id>[&ids=…]`
690        // (Move adds `new_parent`).
691        .route("/cms-admin/pages/bulk", post(handlers::page_bulk_submit))
692        // #72 — editor lock force-release + heartbeat.
693        .route(
694            "/cms-admin/pages/{id}/unlock",
695            post(handlers::page_unlock_submit),
696        )
697        .route(
698            "/cms-admin/pages/{id}/lock-release",
699            post(handlers::page_lock_release),
700        )
701        .route(
702            "/cms-admin/pages/{id}/lock-heartbeat",
703            post(handlers::page_lock_heartbeat),
704        )
705        // #147 — draft autosave.
706        .route(
707            "/cms-admin/pages/{id}/autosave",
708            post(handlers::page_autosave_submit),
709        )
710        // #106 — concurrent-editor presence (JSON for the banner).
711        .route(
712            "/cms-admin/pages/{id}/sessions",
713            get(handlers::page_sessions_json),
714        )
715        // #115 — page subscriptions (notify-on-publish opt-in).
716        .route(
717            "/cms-admin/pages/{id}/subscribe",
718            post(handlers::page_subscribe_submit),
719        )
720        .route(
721            "/cms-admin/pages/{id}/unsubscribe",
722            post(handlers::page_unsubscribe_submit),
723        )
724        // #81 PR 1 — inline comments.
725        .route(
726            "/cms-admin/pages/{id}/comments/new",
727            post(handlers::comment_new_submit),
728        )
729        .route(
730            "/cms-admin/pages/{id}/comments/{comment_id}/reply",
731            post(handlers::comment_reply_submit),
732        )
733        .route(
734            "/cms-admin/pages/{id}/comments/{comment_id}/resolve",
735            post(handlers::comment_resolve_submit),
736        )
737        .route(
738            "/cms-admin/pages/{id}/comments/{comment_id}/reopen",
739            post(handlers::comment_reopen_submit),
740        )
741        // #73 PR 2 — per-page workflow actions.
742        .route(
743            "/cms-admin/pages/{id}/workflow/submit",
744            post(handlers::page_workflow_submit),
745        )
746        .route(
747            "/cms-admin/pages/{id}/workflow/approve",
748            post(handlers::page_workflow_approve),
749        )
750        .route(
751            "/cms-admin/pages/{id}/workflow/reject",
752            post(handlers::page_workflow_reject),
753        )
754        .route(
755            "/cms-admin/pages/{id}/workflow/cancel",
756            post(handlers::page_workflow_cancel),
757        )
758        // Library tab — reusable content blocks ("snippets").
759        .route("/cms-admin/library", get(handlers::library_list))
760        // Forms tab — dedicated list of form snippets with per-form
761        // submission counts (the generic library table can't surface
762        // those: `render_cell` is sync and pool-less).
763        .route("/cms-admin/forms", get(handlers::forms_list))
764        // #525 — persist the admin UI language choice.
765        .route("/cms-admin/set-language", post(handlers::admin_set_language))
766        // #533 FB-04 — dedicated visual Form Builder (forms are snippet-backed;
767        // the library Edit link bounces here).
768        .route(
769            "/cms-admin/forms/{id}/build",
770            get(handlers::form_build_form).post(handlers::form_build_submit),
771        )
772        // Sidebar preview for the builder — the same shared pane the page
773        // editor uses, rendering through the real public form renderer.
774        .route(
775            "/cms-admin/forms/{id}/preview",
776            get(handlers::form_preview).post(handlers::form_preview_draft),
777        )
778        // #548 FB-15 — publish the draft to the live form.
779        .route(
780            "/cms-admin/forms/{id}/publish",
781            post(handlers::form_publish_submit),
782        )
783        // #545 FB-12 — per-form submission history + CSV export.
784        .route(
785            "/cms-admin/forms/{id}/submissions",
786            get(handlers::form_submissions_list),
787        )
788        .route(
789            "/cms-admin/forms/{id}/submissions/export.csv",
790            get(handlers::form_submissions_csv),
791        )
792        // download a file uploaded through a submission.
793        .route(
794            "/cms-admin/forms/{id}/submissions/file/{key}",
795            get(handlers::form_submission_file),
796        )
797        .route(
798            "/cms-admin/library/new",
799            get(handlers::snippet_new_form).post(handlers::snippet_create_submit),
800        )
801        .route(
802            "/cms-admin/library/{id}/edit",
803            get(handlers::snippet_edit_form).post(handlers::snippet_edit_submit),
804        )
805        // #409 — per-field snippet translations for a non-default locale.
806        .route(
807            "/cms-admin/library/{id}/translate",
808            post(handlers::snippet_translate_submit),
809        )
810        // Bulk-action dispatch (#21 phase 2). The path param is the
811        // library type's `type_name` slug, not an id — bulk actions
812        // are per-type, not per-snippet.
813        .route(
814            "/cms-admin/library/{type_name}/bulk",
815            post(handlers::library_bulk_submit),
816        )
817        .route(
818            "/cms-admin/library/{id}/delete",
819            post(handlers::snippet_delete_submit),
820        )
821        // #123 — opt-in snippet revisions.
822        .route(
823            "/cms-admin/library/{id}/revert/{seq}",
824            post(handlers::snippet_revert_submit),
825        )
826        // #186 — bulk import snippets from CSV / TSV.
827        .route(
828            "/cms-admin/library/{type_name}/import",
829            get(handlers::snippet_import_form).post(handlers::snippet_import_submit),
830        )
831        // Media + Documents — single `cms_media` table, two filtered views.
832        .route("/cms-admin/media", get(handlers::media_list))
833        // Image detail / focal-point editor (#4).
834        .route(
835            "/cms-admin/media/{id}/edit",
836            get(handlers::media_edit_form).post(handlers::media_edit_submit),
837        )
838        // Hard crop — apply destructive OR clone-and-crop (#24).
839        .route(
840            "/cms-admin/media/{id}/crop",
841            post(handlers::media_crop_submit),
842        )
843        // Replace image bytes in place — keeps id, alt, focal point (#190).
844        .route(
845            "/cms-admin/media/{id}/replace",
846            post(handlers::media_replace_submit),
847        )
848        // Collection management (#5 V2).
849        .route(
850            "/cms-admin/media/collections",
851            get(handlers::collections_list),
852        )
853        .route(
854            "/cms-admin/media/collections/new",
855            post(handlers::collections_create),
856        )
857        .route(
858            "/cms-admin/media/collections/{id}/edit",
859            post(handlers::collections_edit),
860        )
861        .route(
862            "/cms-admin/media/collections/{id}/delete",
863            post(handlers::collections_delete),
864        )
865        .route(
866            "/cms-admin/media/bulk-move-collection",
867            post(handlers::media_bulk_move_collection),
868        )
869        // #557 — Categories / taxonomies: vocabulary index + per-vocabulary
870        // category tree CRUD.
871        .route("/cms-admin/taxonomies", get(handlers::taxonomies_index))
872        .route("/cms-admin/taxonomies/{slug}", get(handlers::category_tree))
873        .route(
874            "/cms-admin/taxonomies/{slug}/categories/new",
875            get(handlers::category_new_form).post(handlers::category_create),
876        )
877        .route(
878            "/cms-admin/taxonomies/{slug}/categories/{id}/edit",
879            get(handlers::category_edit_form).post(handlers::category_update),
880        )
881        .route(
882            "/cms-admin/taxonomies/{slug}/categories/{id}/delete",
883            post(handlers::category_delete),
884        )
885        // #862 — a category's per-locale name.
886        .route(
887            "/cms-admin/taxonomies/{slug}/categories/{id}/translate",
888            post(handlers::category_translate_submit),
889        )
890        // Per-collection permission editor (#19).
891        .route(
892            "/cms-admin/media/collections/{id}/permissions",
893            get(handlers::collection_permissions_form)
894                .post(handlers::collection_permissions_submit),
895        )
896        // #195 — collection view restriction (login / groups / password).
897        .route(
898            "/cms-admin/media/collections/{id}/privacy",
899            post(handlers::collection_privacy_submit),
900        )
901        // Unused-media report (#8) — reverse index over every page's
902        // extension JSON; lists media rows that no page references.
903        .route(
904            "/cms-admin/media/unused",
905            get(handlers::media_unused_report),
906        )
907        .route(
908            "/cms-admin/media/unused/delete",
909            post(handlers::media_unused_bulk_delete),
910        )
911        .route(
912            "/cms-admin/media/upload",
913            get(handlers::media_upload_form).post(handlers::media_upload_submit),
914        )
915        // #142 — staged-upload scratch storage. The per-route body-limit
916        // override lifts axum's 2 MiB default: photos dragged into the
917        // media picker (and the upload page) routinely exceed it.
918        .route(
919            "/cms-admin/media/upload-staged",
920            post(handlers::media_upload_staged)
921                .route_layer(axum::extract::DefaultBodyLimit::max(50 * 1024 * 1024)),
922        )
923        .route(
924            "/cms-admin/media/upload-staged/{id}/cancel",
925            post(handlers::media_upload_staged_cancel),
926        )
927        // #188 — bulk promote staged uploads to cms_media with metadata.
928        .route(
929            "/cms-admin/media/upload-staged/commit",
930            post(handlers::media_upload_staged_commit),
931        )
932        .route(
933            "/cms-admin/media/{id}/delete",
934            post(handlers::media_delete_submit),
935        )
936        .route("/cms-admin/documents", get(handlers::documents_list))
937        // #420 — generic model-admin index for `register_model_admin!`ed models.
938        .route("/cms-admin/model/{slug}", get(handlers::model_admin_list))
939        // #439 — extensible report framework: one chrome'd dispatcher
940        // for every `register_report!`ed report (`?format=csv` exports).
941        .route("/cms-admin/report/{slug}", get(handlers::report_view))
942        // #421 — generic chooser search endpoint for `register_chooser!`ed
943        // models. The shared chooser overlay (cms-ux.js) resolves an
944        // unregistered `data-chooser-kind` to this route.
945        .route(
946            "/cms-admin/__chooser/{slug}",
947            get(handlers::chooser_search_json),
948        )
949        // Media picker data endpoint — collection/kind filters, pagination,
950        // and server-signed rendition thumb URLs (richer than the generic
951        // `__chooser/media`, which stays registered for back-compat).
952        .route(
953            "/cms-admin/__media-picker",
954            get(handlers::media_picker_json),
955        )
956        // SSO providers — per-tenant OIDC/social login CRUD (admin-sso).
957        .route("/cms-admin/sso-providers", get(handlers::sso_provider_list))
958        .route(
959            "/cms-admin/sso-providers/new",
960            get(handlers::sso_provider_new_form).post(handlers::sso_provider_new_submit),
961        )
962        .route(
963            "/cms-admin/sso-providers/{id}/edit",
964            get(handlers::sso_provider_edit_form).post(handlers::sso_provider_edit_submit),
965        )
966        .route(
967            "/cms-admin/sso-providers/{id}/delete",
968            post(handlers::sso_provider_delete_submit),
969        )
970        // Locales — per-tenant locale registry.
971        .route("/cms-admin/locales", get(handlers::locale_list))
972        .route(
973            "/cms-admin/locales/new",
974            get(handlers::locale_new_form).post(handlers::locale_new_submit),
975        )
976        .route(
977            "/cms-admin/locales/{id}/edit",
978            get(handlers::locale_edit_form).post(handlers::locale_edit_submit),
979        )
980        .route(
981            "/cms-admin/locales/{id}/delete",
982            post(handlers::locale_delete_submit),
983        )
984        // Workflows — multi-step approval CRUD (#73 PR 1). Per-page-type
985        // assignment + page-editor UI lands with PR 2.
986        // #77 — global admin search (pages + snippets + media).
987        .route("/cms-admin/search", get(handlers::admin_search))
988        // #101 — aging-pages report.
989        // #108 — site settings.
990        .route(
991            "/cms-admin/site-settings",
992            get(handlers::site_settings_list),
993        )
994        .route(
995            "/cms-admin/site-settings/{scope}/edit",
996            get(handlers::site_setting_edit_form).post(handlers::site_setting_edit_submit),
997        )
998        .route(
999            "/cms-admin/site-settings/{scope}/delete",
1000            post(handlers::site_setting_delete_submit),
1001        )
1002        // Translate a typed setting's text fields.
1003        .route(
1004            "/cms-admin/site-settings/{scope}/translate",
1005            post(handlers::site_setting_translate_submit),
1006        )
1007        // Per-tenant template overrides. Superuser-only — see
1008        // `template_editor`'s module docs on why.
1009        .route("/cms-admin/templates", get(template_editor::list))
1010        .route(
1011            "/cms-admin/templates/edit",
1012            get(template_editor::edit_form).post(template_editor::save),
1013        )
1014        .route("/cms-admin/templates/new", post(template_editor::create))
1015        .route(
1016            "/cms-admin/templates/validate",
1017            post(template_editor::validate),
1018        )
1019        .route("/cms-admin/templates/delete", post(template_editor::delete))
1020        // Point a page type at a template. Same permission as the editor
1021        // — it is template routing, not content modelling.
1022        .route(
1023            "/cms-admin/page-types/{id}/template",
1024            get(template_editor::assign_form).post(template_editor::assign_save),
1025        )
1026        .route("/cms-admin/analytics", get(handlers::analytics_dashboard))
1027        .route(
1028            "/cms-admin/reports/aging",
1029            get(handlers::aging_pages_report),
1030        )
1031        .route(
1032            "/cms-admin/reports/aging.csv",
1033            get(handlers::aging_pages_csv),
1034        )
1035        .route(
1036            "/cms-admin/reports/locked-pages",
1037            get(handlers::locked_pages_report),
1038        )
1039        .route(
1040            "/cms-admin/reports/locked-pages.csv",
1041            get(handlers::locked_pages_csv),
1042        )
1043        .route(
1044            "/cms-admin/reports/workflows",
1045            get(handlers::workflows_report),
1046        )
1047        .route(
1048            "/cms-admin/reports/workflows.csv",
1049            get(handlers::workflows_report_csv),
1050        )
1051        // #122 — revision storage + manual prune.
1052        .route(
1053            "/cms-admin/reports/revisions",
1054            get(handlers::revisions_report),
1055        )
1056        .route(
1057            "/cms-admin/reports/revisions/prune",
1058            post(handlers::revisions_report_prune),
1059        )
1060        // #141 — scheduled-publish report.
1061        .route(
1062            "/cms-admin/reports/scheduled",
1063            get(handlers::scheduled_report),
1064        )
1065        .route(
1066            "/cms-admin/reports/scheduled.csv",
1067            get(handlers::scheduled_report_csv),
1068        )
1069        // #143 — search promotions + query log.
1070        .route(
1071            "/cms-admin/reports/search",
1072            get(handlers::search_promotions_report),
1073        )
1074        .route(
1075            "/cms-admin/reports/search/{id}/edit",
1076            get(handlers::search_promotion_edit_form).post(handlers::search_promotion_edit_submit),
1077        )
1078        .route("/cms-admin/workflows", get(handlers::workflows_list))
1079        .route(
1080            "/cms-admin/workflows/new",
1081            get(handlers::workflow_new_form).post(handlers::workflow_new_submit),
1082        )
1083        .route(
1084            "/cms-admin/workflows/{id}/edit",
1085            get(handlers::workflow_edit_form).post(handlers::workflow_edit_submit),
1086        )
1087        .route(
1088            "/cms-admin/workflows/{id}/delete",
1089            post(handlers::workflow_delete_submit),
1090        )
1091        .route(
1092            "/cms-admin/workflows/{id}/tasks/add",
1093            post(handlers::workflow_task_add),
1094        )
1095        .route(
1096            "/cms-admin/workflows/{id}/tasks/{task_id}/delete",
1097            post(handlers::workflow_task_delete),
1098        )
1099        // Redirects — editor-managed 301/302 maps. Backed by the
1100        // public router's fallthrough on slug-misses (see
1101        // crate::router) + the framework's `rustango::redirects`.
1102        // Notification destinations + the delivery log.
1103        .route("/cms-admin/notifications", get(notifications::list))
1104        .route("/cms-admin/notifications/new", post(notifications::create))
1105        .route(
1106            "/cms-admin/notifications/{id}/toggle",
1107            post(notifications::toggle),
1108        )
1109        .route(
1110            "/cms-admin/notifications/{id}/delete",
1111            post(notifications::delete),
1112        )
1113        .route(
1114            "/cms-admin/notifications/deliveries/{id}/retry",
1115            post(notifications::retry_delivery),
1116        )
1117        // Sites — hostname → root page, plus the registry rows that make
1118        // the hostname reach this tenant at all. Hostnames travel in the
1119        // form body, not the path: a dotted host in a path segment is one
1120        // proxy normalisation away from arriving mangled.
1121        .route("/cms-admin/sites", get(sites::list))
1122        .route("/cms-admin/sites/new", post(sites::add))
1123        .route("/cms-admin/sites/root", post(sites::set_root))
1124        .route("/cms-admin/sites/toggle", post(sites::toggle))
1125        .route("/cms-admin/sites/delete", post(sites::remove))
1126        .route("/cms-admin/redirects", get(handlers::redirect_list))
1127        .route(
1128            "/cms-admin/redirects/new",
1129            get(handlers::redirect_new_form).post(handlers::redirect_new_submit),
1130        )
1131        .route(
1132            "/cms-admin/redirects/{id}/edit",
1133            get(handlers::redirect_edit_form).post(handlers::redirect_edit_submit),
1134        )
1135        .route(
1136            "/cms-admin/redirects/{id}/delete",
1137            post(handlers::redirect_delete_submit),
1138        )
1139        // #553 — re-enable a rule auto-disabled by a page delete/unpublish.
1140        .route(
1141            "/cms-admin/redirects/{id}/enable",
1142            post(handlers::redirect_enable_submit),
1143        )
1144        // #145 — bulk import from CSV / TSV.
1145        .route(
1146            "/cms-admin/redirects/import",
1147            get(handlers::redirect_import_form).post(handlers::redirect_import_submit),
1148        )
1149        // #400 — bulk export to CSV (round-trippable by the importer).
1150        .route(
1151            "/cms-admin/redirects/export.csv",
1152            get(handlers::redirect_export_csv),
1153        )
1154        // Users + Roles — native CMS surface (#9).
1155        .route("/cms-admin/users", get(handlers::users_list))
1156        // #435 — bulk enable/disable selected users.
1157        .route("/cms-admin/users/bulk", post(handlers::users_bulk_submit))
1158        .route(
1159            "/cms-admin/users/new",
1160            get(handlers::users_new_form).post(handlers::users_create_submit),
1161        )
1162        .route(
1163            "/cms-admin/users/{id}/edit",
1164            get(handlers::users_edit_form).post(handlers::users_edit_submit),
1165        )
1166        .route(
1167            "/cms-admin/users/{id}/deactivate",
1168            post(handlers::users_deactivate_submit),
1169        )
1170        // #433 — sign-in and permission-change log, superuser-only.
1171        .route("/cms-admin/security-log", get(handlers::security_log_page))
1172        .route("/cms-admin/roles", get(handlers::roles_list))
1173        // #436 — tenant-wide read-only permission overview matrix.
1174        .route(
1175            "/cms-admin/permissions",
1176            get(handlers::permissions_overview),
1177        )
1178        .route(
1179            "/cms-admin/roles/new",
1180            get(handlers::roles_new_form).post(handlers::roles_create_submit),
1181        )
1182        .route(
1183            "/cms-admin/roles/{id}/edit",
1184            get(handlers::roles_edit_form).post(handlers::roles_edit_submit),
1185        )
1186        .route(
1187            "/cms-admin/roles/{id}/delete",
1188            post(handlers::roles_delete_submit),
1189        )
1190        // Navigation menus (#22).
1191        .route("/cms-admin/navigation", get(handlers::navigation_list))
1192        .route(
1193            "/cms-admin/navigation/new",
1194            post(handlers::navigation_create_submit),
1195        )
1196        .route(
1197            "/cms-admin/navigation/{id}/delete",
1198            post(handlers::navigation_delete_submit),
1199        )
1200        .route(
1201            "/cms-admin/navigation/{id}/clone",
1202            post(handlers::navigation_clone_submit),
1203        )
1204        .route(
1205            "/cms-admin/navigation/{id}/save-tree",
1206            post(handlers::navigation_save_tree_submit),
1207        )
1208        // #257 — Option B: seed the menu's items
1209        // from every `show_in_menus = true AND status = published` page.
1210        // Idempotent rebuild — drops + re-inserts so a fresh menu
1211        // can be hand-curated from the implicit tree.
1212        .route(
1213            "/cms-admin/navigation/{id}/seed-from-pages",
1214            post(handlers::navigation_seed_from_pages_submit),
1215        )
1216        .route(
1217            "/cms-admin/navigation/{id}/edit",
1218            get(handlers::navigation_edit_form),
1219        )
1220        .route(
1221            "/cms-admin/navigation/{id}/translate",
1222            post(handlers::navigation_translate_submit),
1223        )
1224        .route(
1225            "/cms-admin/navigation/{id}/items",
1226            post(handlers::navigation_item_create),
1227        )
1228        .route(
1229            "/cms-admin/navigation/{menu_id}/items/{id}/delete",
1230            post(handlers::navigation_item_delete),
1231        )
1232        // History — tenant-wide revision audit log (#17).
1233        .route("/cms-admin/history", get(handlers::history_page))
1234        // Page-types — registry + usage stats (#16).
1235        .route("/cms-admin/page-types", get(handlers::page_types_dashboard))
1236        // #559/#566 — create/delete UI page types (Developer-gated in-handler).
1237        .route(
1238            "/cms-admin/page-types/new",
1239            get(handlers::page_type_new_form).post(handlers::page_type_create),
1240        )
1241        .route(
1242            "/cms-admin/page-types/{id}/edit",
1243            get(handlers::page_type_edit_form).post(handlers::page_type_update),
1244        )
1245        .route(
1246            "/cms-admin/page-types/{id}/delete",
1247            post(handlers::page_type_delete),
1248        )
1249        // #559/#562 — page-type field builder (Developer-gated in-handler).
1250        .route(
1251            "/cms-admin/page-types/{id}/build",
1252            get(handlers::page_type_build_form).post(handlers::page_type_build_submit),
1253        )
1254        .route(
1255            "/cms-admin/page-types/{id}/build/publish",
1256            post(handlers::page_type_publish_submit),
1257        )
1258        // #863 — the choice options' labels in other languages.
1259        .route(
1260            "/cms-admin/page-types/{id}/translate",
1261            get(handlers::page_type_translate_form).post(handlers::page_type_translate_submit),
1262        )
1263        // #559/#563 — reusable components library (Developer-gated in-handler).
1264        .route("/cms-admin/components", get(handlers::components_index))
1265        .route(
1266            "/cms-admin/components/new",
1267            get(handlers::component_new_form).post(handlers::component_create),
1268        )
1269        .route(
1270            "/cms-admin/components/{id}/edit",
1271            get(handlers::component_edit_form).post(handlers::component_update),
1272        )
1273        .route(
1274            "/cms-admin/components/{id}/delete",
1275            post(handlers::component_delete),
1276        )
1277        // Settings — site-wide preferences.
1278        .route("/cms-admin/settings", get(handlers::settings_page))
1279        // #199 — per-tenant logo + favicon upload.
1280        .route(
1281            "/cms-admin/settings/branding",
1282            post(handlers::settings_branding_submit),
1283        )
1284        // NOTE: the public serve routes for the uploaded branding assets
1285        // (`/__cms-branding/logo|favicon`) live in `public_router` so the
1286        // pre-auth login + password-reset screens can show the tenant logo
1287        // (#199). Keeping them here would 302 anonymous requests to /login.
1288        .route(
1289            "/cms-admin/settings/theme",
1290            post(handlers::settings_theme_switch),
1291        )
1292        // Per-user account preferences (#27) — appearance, text size,
1293        // accessibility. localStorage-backed, no DB write.
1294        .route("/cms-admin/me", get(handlers::account_preferences))
1295        // JSON endpoint backing the PageChooser widget.
1296        .route(
1297            "/cms-admin/__page-chooser",
1298            get(handlers::page_chooser_json),
1299        )
1300        // JSON endpoints backing the Snippet + Document choosers.
1301        .route(
1302            "/cms-admin/__snippet-chooser",
1303            get(handlers::snippet_chooser_json),
1304        )
1305        .route(
1306            "/cms-admin/__document-chooser",
1307            get(handlers::document_chooser_json),
1308        )
1309        // #197 — per-user notification preferences. POST form from
1310        // /cms-admin/me; checkbox set per kind.
1311        .route(
1312            "/cms-admin/me/notifications",
1313            post(handlers::account_notifications_submit),
1314        )
1315        // #201 — profile (avatar upload + display name change).
1316        .route(
1317            "/cms-admin/me/profile",
1318            post(handlers::account_profile_submit),
1319        )
1320        // #526 — per-user admin UI language preference.
1321        .route(
1322            "/cms-admin/me/language",
1323            post(handlers::account_language_submit),
1324        )
1325        // #202 — email + password change.
1326        .route("/cms-admin/me/email", post(handlers::account_email_submit))
1327        .route(
1328            "/cms-admin/me/email/confirm",
1329            get(handlers::account_email_confirm),
1330        )
1331        .route(
1332            "/cms-admin/me/password",
1333            post(handlers::account_password_submit),
1334        )
1335        // #587 — self-service MCP keys (mint shows the token once; revoke
1336        // is immediate — the MCP endpoint re-checks liveness per request).
1337        .route(
1338            "/cms-admin/me/mcp-keys",
1339            post(handlers::account_mcp_key_create),
1340        )
1341        .route(
1342            "/cms-admin/me/mcp-keys/{id}/revoke",
1343            post(handlers::account_mcp_key_revoke),
1344        )
1345        // #587 — admin-managed MCP keys for another user (the "register an
1346        // agent user, give it a key" flow); capabilities stay bounded by
1347        // the TARGET user's entitlement.
1348        .route(
1349            "/cms-admin/users/{id}/mcp-keys",
1350            post(handlers::users_mcp_key_create),
1351        )
1352        .route(
1353            "/cms-admin/users/{id}/mcp-keys/{key_id}/revoke",
1354            post(handlers::users_mcp_key_revoke),
1355        )
1356        // Public-ish serve route for the avatar bytes. Anonymous-OK
1357        // because the sidebar avatar shows on every authed page (and
1358        // the brand glyph fallback handles the no-avatar case).
1359        .route(
1360            "/__cms-avatar/{user_id}",
1361            get(handlers::account_avatar_serve),
1362        )
1363        // #129 — styleguide / component gallery.
1364        .route("/cms-admin/styleguide", get(handlers::styleguide))
1365        // #144 — editor dashboard / home screen.
1366        .route("/cms-admin/dashboard", get(handlers::dashboard))
1367        // #139 — banner dismissibles (per-user persistent close).
1368        .route(
1369            "/cms-admin/dismissibles/{key}",
1370            post(handlers::dismissible_submit),
1371        )
1372        // Static JS bundles (`cms-ux.js`, `stream_editor.js`,
1373        // `menu-builder.js`) live on `public_router` — they need to
1374        // be reachable pre-auth so the login + password-reset pages
1375        // can fetch them. See `public_router` for the routes.
1376        // Logout — clears every framework session cookie + redirects
1377        // to /login. POST-only (state-changing); CSRF-protected by
1378        // the host's CsrfLayer like every other form POST.
1379        .route("/cms-admin/logout", post(handlers::cms_logout_submit))
1380        // Custom admin pages (#23) — dispatcher for every
1381        // `register_admin_page!`-registered handler. The slug path
1382        // param selects the handler at request time; unknown slugs
1383        // return 404.
1384        .route("/cms-admin/x/{slug}", get(handlers::admin_page_dispatch))
1385        // #672 — every matched route needs the role-matrix codename for
1386        // its section and verb, not just admin access.
1387        .route_layer(axum::middleware::from_fn(route_perms::gate))
1388        // #652 — the tenant's own translation overrides for this request.
1389        .route_layer(axum::middleware::from_fn(i18n::tenant_overrides_layer))
1390        // #689 — outermost, so a tenant provisioned after boot is seeded
1391        // (roles included) before the gate above reads them.
1392        .route_layer(axum::middleware::from_fn(crate::seed::lazy_seed_layer))
1393        .with_state(state)
1394}
1395
1396async fn redirect_root() -> axum::response::Redirect {
1397    // #144 — root now lands on the dashboard. Was /cms-admin/pages.
1398    axum::response::Redirect::permanent("/cms-admin/dashboard")
1399}
1400
1401/// A bundled admin asset, cached for a year as immutable. Only safe
1402/// because every URL that loads one carries `?v={{ cms_asset_version() }}`
1403/// (or, for a bundle loaded from script, the loader's own `?v=`), so a
1404/// new build is a new URL. The one place that policy is written.
1405fn immutable_asset<B: axum::response::IntoResponse>(
1406    content_type: &'static str,
1407    body: B,
1408) -> axum::response::Response {
1409    use axum::response::IntoResponse as _;
1410    (
1411        [
1412            (
1413                axum::http::header::CONTENT_TYPE,
1414                axum::http::HeaderValue::from_static(content_type),
1415            ),
1416            (
1417                axum::http::header::CACHE_CONTROL,
1418                axum::http::HeaderValue::from_static("public, max-age=31536000, immutable"),
1419            ),
1420        ],
1421        body,
1422    )
1423        .into_response()
1424}
1425
1426/// Serve the bundled stream-editor JS, cached as an [`immutable_asset`].
1427async fn serve_stream_editor_js() -> impl axum::response::IntoResponse {
1428    immutable_asset("text/javascript; charset=utf-8", include_str!("static/stream_editor.js"))
1429}
1430
1431/// Shared sidebar-preview driver. Any editor that includes
1432/// `_preview_pane.html` loads this; it reads its configuration from the
1433/// pane's data attributes, so it is content-agnostic.
1434async fn serve_cms_preview_js() -> impl axum::response::IntoResponse {
1435    immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-preview.js"))
1436}
1437
1438/// Block-tree sidebar outline (page editor).
1439async fn serve_block_tree_js() -> impl axum::response::IntoResponse {
1440    immutable_asset("text/javascript; charset=utf-8", include_str!("static/block_tree.js"))
1441}
1442
1443/// Bundled UX helper script. Hosts `rcmsConfirm` modal +
1444/// `rcmsToast` notification stack + the auto-wiring that intercepts
1445/// `data-confirm` forms / links and hoists server-rendered flash
1446/// banners into toasts. Cached for one day so the asset doesn't
1447/// re-fetch on every page.
1448async fn serve_cms_ux_js() -> impl axum::response::IntoResponse {
1449    immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-ux.js"))
1450}
1451
1452/// Bundled WP-style menu builder script. Hosts the
1453/// drag-and-drop tree + JSON save POST. Loaded only on
1454/// `/cms-admin/navigation/{id}/edit` via an inline `<script src>`.
1455async fn serve_menu_builder_js() -> impl axum::response::IntoResponse {
1456    immutable_asset("text/javascript; charset=utf-8", include_str!("static/menu-builder.js"))
1457}
1458
1459/// The visual Form Builder editor engine. Loaded only on
1460/// `/cms-admin/forms/{id}/build` via an inline `<script src>`.
1461async fn serve_form_builder_js() -> impl axum::response::IntoResponse {
1462    immutable_asset("text/javascript; charset=utf-8", include_str!("static/form_builder.js"))
1463}
1464
1465async fn serve_page_type_builder_js() -> impl axum::response::IntoResponse {
1466    immutable_asset("text/javascript; charset=utf-8", include_str!("static/page_type_builder.js"))
1467}
1468
1469async fn serve_page_builder_rules_js() -> impl axum::response::IntoResponse {
1470    immutable_asset("text/javascript; charset=utf-8", include_str!("static/page_builder_rules.js"))
1471}
1472
1473/// Bundled axe-core (553 KB minified). Self-hosted under
1474/// `/cms-admin/static/vendor/` to satisfy strict CSP setups that
1475/// disable third-party CDN script-src. Loaded into the preview
1476/// iframe by [`serve_cms_axe_preview_js`].
1477async fn serve_axe_core_js() -> impl axum::response::IntoResponse {
1478    immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/axe-core.min.js"))
1479}
1480
1481/// The small editor↔iframe glue that runs INSIDE the preview
1482/// frame: waits for axe-core to load, fires `axe.run()`, and posts
1483/// results back to the editor's parent window via `postMessage`.
1484/// Also listens for `cms-axe-scroll-to` messages so the editor can
1485/// scroll the offending element into view.
1486async fn serve_cms_axe_preview_js() -> impl axum::response::IntoResponse {
1487    immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-axe-preview.js"))
1488}
1489
1490/// Preview navigation guard — runs INSIDE the preview iframe alongside
1491/// the axe glue. Neutralizes link/form navigation so the preview stays a
1492/// contained render: same-document hash anchors scroll; every other link
1493/// or form submit is a no-op.
1494async fn serve_cms_preview_guard_js() -> impl axum::response::IntoResponse {
1495    immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-preview-guard.js"))
1496}
1497
1498/// Self-hosted admin typography. The admin used to pull Hanken
1499/// Grotesk, Literata and Material Symbols from `fonts.googleapis.com`.
1500/// Material Symbols is a LIGATURE icon font, so when that request failed —
1501/// offline, air-gapped, strict CSP, or an ad blocker — every icon in the
1502/// chrome rendered as its own name ("article", "error", "image"). It also
1503/// sent each editor's IP to a third party on every page load. Vendored
1504/// here and served from the admin's own static route, same rationale as
1505/// the TipTap bundle below.
1506///
1507/// Subsets: latin, latin-ext, cyrillic, cyrillic-ext — enough for the
1508/// shipped admin locales (de/fr/pl/uk). CJK was never covered by these
1509/// families and still falls back to the system face.
1510const ADMIN_FONT_FILES: &[(&str, &[u8])] = &[
1511    (
1512        "icons-00.woff2",
1513        include_bytes!("static/vendor/fonts/icons-00.woff2"),
1514    ),
1515    (
1516        "text-00.woff2",
1517        include_bytes!("static/vendor/fonts/text-00.woff2"),
1518    ),
1519    (
1520        "text-02.woff2",
1521        include_bytes!("static/vendor/fonts/text-02.woff2"),
1522    ),
1523    (
1524        "text-03.woff2",
1525        include_bytes!("static/vendor/fonts/text-03.woff2"),
1526    ),
1527    (
1528        "text-16.woff2",
1529        include_bytes!("static/vendor/fonts/text-16.woff2"),
1530    ),
1531    (
1532        "text-17.woff2",
1533        include_bytes!("static/vendor/fonts/text-17.woff2"),
1534    ),
1535    (
1536        "text-21.woff2",
1537        include_bytes!("static/vendor/fonts/text-21.woff2"),
1538    ),
1539    (
1540        "text-22.woff2",
1541        include_bytes!("static/vendor/fonts/text-22.woff2"),
1542    ),
1543];
1544
1545/// `@font-face` declarations pointing at the vendored files above.
1546/// Pre-auth like the stylesheet: the login screen uses the same chrome.
1547async fn serve_admin_fonts_css() -> impl axum::response::IntoResponse {
1548    immutable_asset("text/css; charset=utf-8", include_str!("static/vendor/fonts/fonts.css"))
1549}
1550
1551/// Serve one vendored `.woff2`. Unknown names 404 rather than falling
1552/// through to the page router, which would answer with a CMS 404 page.
1553async fn serve_admin_font_file(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
1554    match ADMIN_FONT_FILES.iter().find(|(name, _)| *name == file) {
1555        Some((_, bytes)) => immutable_asset("font/woff2", *bytes)
1556            .into_response(),
1557        None => (axum::http::StatusCode::NOT_FOUND, "unknown font").into_response(),
1558    }
1559}
1560
1561/// The default Rustango CMS brand images, light and dark: the full badge
1562/// (login screen), the RS icon (sidebar mark, favicon) and the favicon /
1563/// touch icon. `(file name, content type, bytes)`.
1564const ADMIN_BRAND_FILES: &[(&str, &str, &[u8])] = &[
1565    ("logo-light.png", "image/png", include_bytes!("static/brand/logo-light.png")),
1566    ("logo-dark.png", "image/png", include_bytes!("static/brand/logo-dark.png")),
1567    ("icon-light.png", "image/png", include_bytes!("static/brand/icon-light.png")),
1568    ("icon-dark.png", "image/png", include_bytes!("static/brand/icon-dark.png")),
1569    ("favicon.ico", "image/x-icon", include_bytes!("static/brand/favicon.ico")),
1570    ("apple-touch-icon.png", "image/png", include_bytes!("static/brand/apple-touch-icon.png")),
1571];
1572
1573async fn serve_admin_brand_file(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
1574    match ADMIN_BRAND_FILES.iter().find(|(name, _, _)| *name == file) {
1575        Some((_, content_type, bytes)) => immutable_asset(content_type, *bytes).into_response(),
1576        None => (axum::http::StatusCode::NOT_FOUND, "unknown brand file").into_response(),
1577    }
1578}
1579
1580/// Vendored TipTap (MIT) engine bundle exposing
1581/// `window.RcmsRichtext.create(...)`. Self-hosted under
1582/// `/cms-admin/static/vendor/` (CSP-friendly, offline-capable). Content
1583/// is content-addressed by the committed build, so cache hard.
1584async fn serve_tiptap_bundle_js() -> impl axum::response::IntoResponse {
1585    immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/tiptap.bundle.js"))
1586}
1587
1588/// The template editor's hand-authored glue: progressively enhances the
1589/// source `<textarea>` into CodeMirror, lazy-loading the vendored bundle
1590/// only on that page.
1591async fn serve_template_editor_js() -> impl axum::response::IntoResponse {
1592    immutable_asset("text/javascript; charset=utf-8", include_str!("static/template-editor.js"))
1593}
1594
1595/// Vendored CodeMirror 5 (MIT) + the `tera` mode. Served only for the
1596/// template editor, which injects it on demand — see
1597/// `static/vendor/codemirror.bundle.README.md`.
1598async fn serve_codemirror_bundle_js() -> impl axum::response::IntoResponse {
1599    immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/codemirror.bundle.js"))
1600}
1601
1602/// Hand-authored richtext glue: progressively enhances every
1603/// `<textarea data-widget-mode="richtext">` into a TipTap WYSIWYG with a
1604/// toolbar, syncing HTML back into the textarea for submit. Loads after
1605/// the engine bundle.
1606async fn serve_richtext_editor_js() -> impl axum::response::IntoResponse {
1607    immutable_asset("text/javascript; charset=utf-8", include_str!("static/richtext-editor.js"))
1608}
1609
1610/// Bundled admin stylesheet. Single source of truth for every
1611/// `/cms-admin/*` screen + the standalone auth flow. Built at compile
1612/// time via `include_str!` so the binary ships self-contained.
1613const BUNDLED_CMS_CSS: &str = include_str!("static/cms.css");
1614
1615/// Serve the admin stylesheet. Host apps can override the bundled
1616/// CSS by dropping a `static/cms_admin/cms.css` file in their project
1617/// root — the handler returns that file when present, otherwise the
1618/// compile-time bundled stylesheet.
1619///
1620/// Mounted by [`public_router`] (not the protected router) so the
1621/// login + password-reset screens can load it pre-auth.
1622async fn serve_cms_css() -> Response {
1623    let override_path = std::path::Path::new("static/cms_admin/cms.css");
1624    if override_path.exists() {
1625        match std::fs::read_to_string(override_path) {
1626            Ok(source) => {
1627                return (
1628                    [
1629                        (
1630                            axum::http::header::CONTENT_TYPE,
1631                            axum::http::HeaderValue::from_static("text/css; charset=utf-8"),
1632                        ),
1633                        // Safe to cache hard: `cms_asset_version()` folds this
1634                        // override file's mtime+len into the `?v=` token, so a
1635                        // dev edit mints a fresh URL — no stale copy can stick.
1636                        (
1637                            axum::http::header::CACHE_CONTROL,
1638                            axum::http::HeaderValue::from_static(
1639                                "public, max-age=31536000, immutable",
1640                            ),
1641                        ),
1642                    ],
1643                    source,
1644                )
1645                    .into_response();
1646            }
1647            Err(err) => {
1648                tracing::warn!(
1649                    target: "rustango_cms::admin",
1650                    error = %err,
1651                    path = %override_path.display(),
1652                    "failed to read cms.css override; falling back to bundled stylesheet",
1653                );
1654            }
1655        }
1656    }
1657    immutable_asset("text/css; charset=utf-8", BUNDLED_CMS_CSS)
1658        .into_response()
1659}
1660
1661/// Cache-bust token for the bundled admin assets loaded by every
1662/// `/cms-admin/*` page (`cms.css` + the editor JS). The admin chrome
1663/// links these from stable URLs, so without a version query a browser
1664/// that cached an older build keeps serving it — the symptom being a
1665/// stale `cms.css` that misses newer styles (e.g. dark-mode shades)
1666/// while the (query-versioned) public site looks fine.
1667///
1668/// The token folds two signals:
1669///   * a compile-time fingerprint of the bundled CSS + JS, so an
1670///     upgraded build always mints a fresh URL; and
1671///   * the hot-override `static/cms_admin/cms.css` file's mtime+len
1672///     when present, so a dev edit busts the cache without a rebuild
1673///     (mirrors how [`serve_cms_css`] reads that override live).
1674fn cms_asset_version() -> String {
1675    static BUNDLED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1676    let bundled = *BUNDLED.get_or_init(|| {
1677        // FNV-1a over the bundled asset bytes — cheap, stable, and
1678        // collision-resistant enough for a cache key.
1679        let mut h: u64 = 0xcbf29ce4_84222325;
1680        let mut feed_bytes = |bytes: &[u8]| {
1681            for &b in bytes {
1682                h ^= u64::from(b);
1683                h = h.wrapping_mul(0x0000_0100_0000_01b3);
1684            }
1685        };
1686        // The brand images are linked with the same `?v=`.
1687        for (_, _, bytes) in ADMIN_BRAND_FILES {
1688            feed_bytes(bytes);
1689        }
1690        let mut feed = |s: &str| feed_bytes(s.as_bytes());
1691        feed(BUNDLED_CMS_CSS);
1692        feed(include_str!("static/cms-ux.js"));
1693        feed(include_str!("static/stream_editor.js"));
1694        feed(include_str!("static/richtext-editor.js"));
1695        // Every other bundled admin script too — leaving one out means a
1696        // changed file ships under an unchanged ?v= and browsers keep the
1697        // stale cached copy (bit us with page_type_builder.js).
1698        feed(include_str!("static/block_tree.js"));
1699        feed(include_str!("static/page_type_builder.js"));
1700        feed(include_str!("static/form_builder.js"));
1701        feed(include_str!("static/menu-builder.js"));
1702        feed(include_str!("static/cms-axe-preview.js"));
1703        feed(include_str!("static/cms-preview-guard.js"));
1704        feed(include_str!("static/cms-preview.js"));
1705        feed(include_str!("static/page_builder_rules.js"));
1706        h
1707    });
1708    if let Ok(meta) = std::fs::metadata("static/cms_admin/cms.css") {
1709        let mtime = meta
1710            .modified()
1711            .ok()
1712            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1713            .map_or(0, |d| d.as_secs());
1714        return format!("{bundled:x}.{mtime:x}.{:x}", meta.len());
1715    }
1716    format!("{bundled:x}")
1717}
1718
1719/// Tera glue for [`cms_asset_version`]: `{{ cms_asset_version() }}`.
1720struct CmsAssetVersionFn;
1721
1722impl tera::Function for CmsAssetVersionFn {
1723    fn call(
1724        &self,
1725        _args: &std::collections::HashMap<String, tera::Value>,
1726    ) -> tera::Result<tera::Value> {
1727        Ok(tera::Value::String(cms_asset_version()))
1728    }
1729}
1730
1731/// `{{ value | json_script }}` — JSON for a `<script>` body or a quoted
1732/// attribute.
1733///
1734/// `json_encode | safe` leaves `<`, `>`, `&` and `'` alone, so a stored
1735/// string containing `</script>` ends the element in the HTML tokenizer.
1736/// This emits the same JSON with those four as `\uXXXX` escapes, which
1737/// every JSON parser and JS engine reads back unchanged. Marked safe, so
1738/// templates use it without `| safe`.
1739struct JsonScriptFilter;
1740
1741impl tera::Filter for JsonScriptFilter {
1742    fn filter(
1743        &self,
1744        value: &tera::Value,
1745        _args: &std::collections::HashMap<String, tera::Value>,
1746    ) -> tera::Result<tera::Value> {
1747        Ok(tera::Value::String(json_script(value)))
1748    }
1749
1750    fn is_safe(&self) -> bool {
1751        true
1752    }
1753}
1754
1755fn json_script(value: &tera::Value) -> String {
1756    serde_json::to_string(value)
1757        .unwrap_or_else(|_| "null".to_owned())
1758        .replace('<', "\\u003c")
1759        .replace('>', "\\u003e")
1760        .replace('&', "\\u0026")
1761        .replace('\'', "\\u0027")
1762}
1763
1764/// Register the bundled admin templates **and** the Tera helpers
1765/// they depend on (named URL reversal via `{{ url(...) }}`, the
1766/// `{% querystring %}` filter, `humanize` filters, and the
1767/// `csrf_input` filter) on a `Tera` instance.
1768///
1769/// Host apps call this once during Tera setup so the admin
1770/// handlers can find their templates without filesystem access.
1771///
1772/// # Customizing the admin
1773///
1774/// Drop a Tera template at `templates/cms_admin/<template-name>.html`
1775/// in your project root to override the bundled CMS admin template
1776/// of the same name. The override walk runs *after* the bundled
1777/// defaults register, so a host file wins over the built-in copy via
1778/// Tera's name-collision semantics.
1779///
1780/// Directory layout mirrors the template namespace:
1781///
1782/// ```text
1783/// templates/cms_admin/
1784///   login.html                 → overrides "login.html"
1785///   _auth_layout.html          → overrides "rcms_admin/_auth_layout.html"
1786///   rcms_admin/_base.html      → overrides "rcms_admin/_base.html"
1787///   blocks/heading.html        → overrides "blocks/heading.html"
1788/// ```
1789///
1790/// Top-level `.html` files at `templates/cms_admin/*.html` get a
1791/// best-fit name: the bare basename is used as the Tera template
1792/// name (so `login.html` overrides the framework's login, and
1793/// `_auth_layout.html` overrides the bundled `rcms_admin/_auth_layout.html`
1794/// via an explicit aliased registration). Files in nested
1795/// subdirectories use their relative path (e.g.
1796/// `blocks/heading.html`).
1797///
1798/// Customizing the stylesheet uses the same pattern but with
1799/// `static/cms_admin/cms.css` (the bundled CSS handler does its own
1800/// override discovery at request time — see `serve_cms_css`).
1801///
1802/// # Errors
1803/// Propagates Tera errors from template registration (only fails on
1804/// internal parse errors of the bundled templates, which would be a
1805/// compile-time bug in this crate, not a runtime concern) and I/O
1806/// errors when reading an unreadable host override.
1807pub fn register_templates(tera: &mut Tera) -> Result<(), tera::Error> {
1808    crate::urls::register_tera_helpers(tera);
1809    // `{{ cms_asset_version() }}` cache-bust token for the admin chrome's
1810    // own static assets (cms.css + editor JS), used in `_base.html`.
1811    tera.register_function("cms_asset_version", CmsAssetVersionFn);
1812    tera.register_filter("json_script", JsonScriptFilter);
1813    // #524 — admin UI i18n. The framework registers the locale helpers;
1814    // `translate`/`translate_plural` are then replaced with bindings that
1815    // layer the request tenant's DB overrides (#532) over the shipped
1816    // catalogs, since the framework's own read one process-wide map (#652).
1817    rustango::i18n::tera_tags::register(tera, i18n::cached_translator().clone());
1818    i18n::register_tera_bindings(tera);
1819    // #641 — Tera registers `get_env` as a default builtin, and it reads
1820    // the process environment (`RUSTANGO_SECRET_KEY`, `DATABASE_URL`, SSO
1821    // secrets, …). Authored templates — written through `write_template`
1822    // over MCP or the admin template editor — compile into this same
1823    // engine and are semi-trusted content, not operator code. Left in
1824    // place, `{{ get_env(name="RUSTANGO_SECRET_KEY") }}` in a template
1825    // would render the deployment's master secret into a page, so a
1826    // template author could forge any tenant's sessions and decrypt every
1827    // stored DSN. `register_function` overrides the builtin (Tera has no
1828    // `unregister`), and per-tenant overlays are `base.clone()` so they
1829    // inherit this neutered version.
1830    tera.register_function(
1831        "get_env",
1832        |_args: &std::collections::HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
1833            Err(tera::Error::msg(
1834                "get_env is disabled in CMS templates for security reasons",
1835            ))
1836        },
1837    );
1838    tera.add_raw_templates(vec![
1839        (
1840            "rcms_admin/_base.html",
1841            include_str!("templates/_base.html"),
1842        ),
1843        (
1844            "rcms_admin/_auth_layout.html",
1845            include_str!("templates/_auth_layout.html"),
1846        ),
1847        // Favicon links for every admin page: the tenant's own, else the
1848        // Rustango CMS icon.
1849        (
1850            "rcms_admin/_brand_icons.html",
1851            include_str!("templates/_brand_icons.html"),
1852        ),
1853        // Sits between `_base.html` and every list/report page: it owns the
1854        // intro card so the page description looks the same everywhere.
1855        (
1856            "rcms_admin/_list_base.html",
1857            include_str!("templates/_list_base.html"),
1858        ),
1859        // One-shot wrapper used to render a single widget through the
1860        // `_widget.html` macro (block/stream editors). Registered here so
1861        // `render_widget_via_macro_with` can render it on the SHARED Tera:
1862        // it used to `tera.clone()` + `add_raw_template` on every call,
1863        // deep-copying every compiled admin template ~173x per page-edit
1864        // load (~2.4ms each, 423ms total).
1865        (
1866            "rcms_admin/_stream_widget.html",
1867            "{% import \"rcms_admin/_widget.html\" as widget %}{{ widget::render(w=w) }}",
1868        ),
1869        (
1870            "rcms_admin/member_login.html",
1871            include_str!("templates/member_login.html"),
1872        ),
1873        (
1874            "rcms_admin/member_signup.html",
1875            include_str!("templates/member_signup.html"),
1876        ),
1877        (
1878            "rcms_admin/_mcp_keys_card.html",
1879            include_str!("templates/_mcp_keys_card.html"),
1880        ),
1881        (
1882            "rcms_admin/_pagination.html",
1883            include_str!("templates/_pagination.html"),
1884        ),
1885        (
1886            "rcms_admin/_preview_pane.html",
1887            include_str!("templates/_preview_pane.html"),
1888        ),
1889        (
1890            "rcms_admin/notifications.html",
1891            include_str!("templates/notifications.html"),
1892        ),
1893        ("rcms_admin/sites.html", include_str!("templates/sites.html")),
1894        (
1895            "rcms_admin/_widget.html",
1896            include_str!("templates/_widget.html"),
1897        ),
1898        (
1899            "rcms_admin/_widget_group.html",
1900            include_str!("templates/_widget_group.html"),
1901        ),
1902        (
1903            "rcms_admin/_permissions_tab.html",
1904            include_str!("templates/_permissions_tab.html"),
1905        ),
1906        (
1907            "rcms_admin/page_list.html",
1908            include_str!("templates/page_list.html"),
1909        ),
1910        (
1911            "rcms_admin/page_form.html",
1912            include_str!("templates/page_form.html"),
1913        ),
1914        (
1915            "rcms_admin/page_type_picker.html",
1916            include_str!("templates/page_type_picker.html"),
1917        ),
1918        (
1919            "rcms_admin/library_list.html",
1920            include_str!("templates/library_list.html"),
1921        ),
1922        (
1923            "rcms_admin/snippet_form.html",
1924            include_str!("templates/snippet_form.html"),
1925        ),
1926        (
1927            "rcms_admin/form_builder.html",
1928            include_str!("templates/form_builder.html"),
1929        ),
1930        (
1931            "rcms_admin/form_submissions.html",
1932            include_str!("templates/form_submissions.html"),
1933        ),
1934        (
1935            "rcms_admin/forms_list.html",
1936            include_str!("templates/forms_list.html"),
1937        ),
1938        (
1939            "rcms_admin/form_translate.html",
1940            include_str!("templates/form_translate.html"),
1941        ),
1942        (
1943            "rcms_admin/page_type_translate.html",
1944            include_str!("templates/page_type_translate.html"),
1945        ),
1946        (
1947            "rcms_admin/media_list.html",
1948            include_str!("templates/media_list.html"),
1949        ),
1950        (
1951            "rcms_admin/media_upload.html",
1952            include_str!("templates/media_upload.html"),
1953        ),
1954        (
1955            "rcms_admin/model_admin_list.html",
1956            include_str!("templates/model_admin_list.html"),
1957        ),
1958        (
1959            "rcms_admin/report.html",
1960            include_str!("templates/report.html"),
1961        ),
1962        (
1963            "rcms_admin/locale_list.html",
1964            include_str!("templates/locale_list.html"),
1965        ),
1966        (
1967            "rcms_admin/locale_form.html",
1968            include_str!("templates/locale_form.html"),
1969        ),
1970        (
1971            "rcms_admin/sso_provider_list.html",
1972            include_str!("templates/sso_provider_list.html"),
1973        ),
1974        (
1975            "rcms_admin/sso_provider_form.html",
1976            include_str!("templates/sso_provider_form.html"),
1977        ),
1978        (
1979            "rcms_admin/workflow_list.html",
1980            include_str!("templates/workflow_list.html"),
1981        ),
1982        (
1983            "rcms_admin/workflow_form.html",
1984            include_str!("templates/workflow_form.html"),
1985        ),
1986        (
1987            "rcms_admin/history_diff.html",
1988            include_str!("templates/history_diff.html"),
1989        ),
1990        (
1991            "rcms_admin/admin_search.html",
1992            include_str!("templates/admin_search.html"),
1993        ),
1994        (
1995            "rcms_admin/analytics.html",
1996            include_str!("templates/analytics.html"),
1997        ),
1998        (
1999            "rcms_admin/aging_pages.html",
2000            include_str!("templates/aging_pages.html"),
2001        ),
2002        (
2003            "rcms_admin/locked_pages.html",
2004            include_str!("templates/locked_pages.html"),
2005        ),
2006        (
2007            "rcms_admin/workflow_report.html",
2008            include_str!("templates/workflow_report.html"),
2009        ),
2010        (
2011            "rcms_admin/revisions_report.html",
2012            include_str!("templates/revisions_report.html"),
2013        ),
2014        (
2015            "rcms_admin/scheduled_report.html",
2016            include_str!("templates/scheduled_report.html"),
2017        ),
2018        (
2019            "rcms_admin/search_promotions_report.html",
2020            include_str!("templates/search_promotions_report.html"),
2021        ),
2022        (
2023            "rcms_admin/search_promotion_edit.html",
2024            include_str!("templates/search_promotion_edit.html"),
2025        ),
2026        (
2027            "rcms_admin/styleguide.html",
2028            include_str!("templates/styleguide.html"),
2029        ),
2030        (
2031            "rcms_admin/dashboard.html",
2032            include_str!("templates/dashboard.html"),
2033        ),
2034        (
2035            "rcms_admin/redirect_import.html",
2036            include_str!("templates/redirect_import.html"),
2037        ),
2038        (
2039            "rcms_admin/snippet_import.html",
2040            include_str!("templates/snippet_import.html"),
2041        ),
2042        (
2043            "rcms_admin/site_settings_list.html",
2044            include_str!("templates/site_settings_list.html"),
2045        ),
2046        (
2047            "rcms_admin/template_list.html",
2048            include_str!("templates/template_list.html"),
2049        ),
2050        (
2051            "rcms_admin/template_form.html",
2052            include_str!("templates/template_form.html"),
2053        ),
2054        (
2055            "rcms_admin/page_type_template_form.html",
2056            include_str!("templates/page_type_template_form.html"),
2057        ),
2058        (
2059            "rcms_admin/site_setting_form.html",
2060            include_str!("templates/site_setting_form.html"),
2061        ),
2062        // #76 — public-facing password-prompt page for view-restricted
2063        // pages. Sits under the `rcms/` namespace (vs `rcms_admin/`)
2064        // because it renders to anonymous visitors.
2065        (
2066            "rcms/view_password.html",
2067            include_str!("templates/view_password.html"),
2068        ),
2069        (
2070            "rcms_admin/redirect_list.html",
2071            include_str!("templates/redirect_list.html"),
2072        ),
2073        (
2074            "rcms_admin/redirect_form.html",
2075            include_str!("templates/redirect_form.html"),
2076        ),
2077        (
2078            "rcms_admin/settings.html",
2079            include_str!("templates/settings.html"),
2080        ),
2081        (
2082            "rcms_admin/history.html",
2083            include_str!("templates/history.html"),
2084        ),
2085        (
2086            "rcms_admin/navigation_list.html",
2087            include_str!("templates/navigation_list.html"),
2088        ),
2089        (
2090            "rcms_admin/navigation_edit.html",
2091            include_str!("templates/navigation_edit.html"),
2092        ),
2093        (
2094            "rcms_admin/page_types.html",
2095            include_str!("templates/page_types.html"),
2096        ),
2097        (
2098            "rcms_admin/page_type_builder.html",
2099            include_str!("templates/page_type_builder.html"),
2100        ),
2101        (
2102            "rcms_admin/components_list.html",
2103            include_str!("templates/components_list.html"),
2104        ),
2105        (
2106            "rcms_admin/schema_page.html",
2107            include_str!("templates/schema_page.html"),
2108        ),
2109        (
2110            "rcms_admin/page_type_form.html",
2111            include_str!("templates/page_type_form.html"),
2112        ),
2113        (
2114            "rcms_admin/component_builder.html",
2115            include_str!("templates/component_builder.html"),
2116        ),
2117        (
2118            "rcms_admin/users_list.html",
2119            include_str!("templates/users_list.html"),
2120        ),
2121        (
2122            "rcms_admin/security_log.html",
2123            include_str!("templates/security_log.html"),
2124        ),
2125        (
2126            "rcms_admin/user_form.html",
2127            include_str!("templates/user_form.html"),
2128        ),
2129        (
2130            "rcms_admin/roles_list.html",
2131            include_str!("templates/roles_list.html"),
2132        ),
2133        (
2134            "rcms_admin/permissions_overview.html",
2135            include_str!("templates/permissions_overview.html"),
2136        ),
2137        (
2138            "rcms_admin/role_form.html",
2139            include_str!("templates/role_form.html"),
2140        ),
2141        (
2142            "rcms_admin/media_unused.html",
2143            include_str!("templates/media_unused.html"),
2144        ),
2145        (
2146            "rcms_admin/media_edit.html",
2147            include_str!("templates/media_edit.html"),
2148        ),
2149        (
2150            "rcms_admin/collection_permissions.html",
2151            include_str!("templates/collection_permissions.html"),
2152        ),
2153        (
2154            "rcms_admin/collections_list.html",
2155            include_str!("templates/collections_list.html"),
2156        ),
2157        // #557 — categories / taxonomies admin.
2158        (
2159            "rcms_admin/taxonomies_list.html",
2160            include_str!("templates/taxonomies_list.html"),
2161        ),
2162        (
2163            "rcms_admin/category_tree.html",
2164            include_str!("templates/category_tree.html"),
2165        ),
2166        (
2167            "rcms_admin/category_form.html",
2168            include_str!("templates/category_form.html"),
2169        ),
2170        // Authentication chrome — five stand-alone screens that
2171        // share `rcms_admin/_auth_layout.html`. The `login.html`
2172        // name is unprefixed because the framework's login_view
2173        // looks it up by that bare name; registering it here wins
2174        // over the framework's bundled copy.
2175        ("login.html", include_str!("templates/login.html")),
2176        (
2177            "rcms_admin/password_reset_request.html",
2178            include_str!("templates/password_reset_request.html"),
2179        ),
2180        (
2181            "rcms_admin/password_reset_sent.html",
2182            include_str!("templates/password_reset_sent.html"),
2183        ),
2184        (
2185            "rcms_admin/password_reset_confirm.html",
2186            include_str!("templates/password_reset_confirm.html"),
2187        ),
2188        (
2189            "rcms_admin/password_reset_done.html",
2190            include_str!("templates/password_reset_done.html"),
2191        ),
2192        (
2193            "rcms_admin/no_access.html",
2194            include_str!("templates/no_access.html"),
2195        ),
2196        (
2197            "rcms_admin/account_preferences.html",
2198            include_str!("templates/account_preferences.html"),
2199        ),
2200        (
2201            "rcms_admin/_breadcrumbs.html",
2202            include_str!("templates/_breadcrumbs.html"),
2203        ),
2204        // Block render templates — used by the public-render path
2205        // (`stream_render` Tera function). Same Tera instance keeps
2206        // them reachable from anywhere (`blocks/heading.html`,
2207        // `blocks/paragraph.html`, …). Host apps override per-block
2208        // via the filesystem walk below.
2209        (
2210            "blocks/heading.html",
2211            include_str!("templates/blocks/heading.html"),
2212        ),
2213        (
2214            "blocks/paragraph.html",
2215            include_str!("templates/blocks/paragraph.html"),
2216        ),
2217        (
2218            "blocks/image.html",
2219            include_str!("templates/blocks/image.html"),
2220        ),
2221        (
2222            "blocks/quote.html",
2223            include_str!("templates/blocks/quote.html"),
2224        ),
2225        (
2226            "blocks/embed.html",
2227            include_str!("templates/blocks/embed.html"),
2228        ),
2229        (
2230            "blocks/code.html",
2231            include_str!("templates/blocks/code.html"),
2232        ),
2233        // #194 — expanded block catalog.
2234        (
2235            "blocks/text.html",
2236            include_str!("templates/blocks/text.html"),
2237        ),
2238        (
2239            "blocks/boolean.html",
2240            include_str!("templates/blocks/boolean.html"),
2241        ),
2242        (
2243            "blocks/date.html",
2244            include_str!("templates/blocks/date.html"),
2245        ),
2246        (
2247            "blocks/datetime.html",
2248            include_str!("templates/blocks/datetime.html"),
2249        ),
2250        (
2251            "blocks/email.html",
2252            include_str!("templates/blocks/email.html"),
2253        ),
2254        ("blocks/url.html", include_str!("templates/blocks/url.html")),
2255        (
2256            "blocks/integer.html",
2257            include_str!("templates/blocks/integer.html"),
2258        ),
2259        (
2260            "blocks/choice.html",
2261            include_str!("templates/blocks/choice.html"),
2262        ),
2263        (
2264            "blocks/table.html",
2265            include_str!("templates/blocks/table.html"),
2266        ),
2267        // Further built-in blocks.
2268        (
2269            "blocks/float.html",
2270            include_str!("templates/blocks/float.html"),
2271        ),
2272        (
2273            "blocks/decimal.html",
2274            include_str!("templates/blocks/decimal.html"),
2275        ),
2276        (
2277            "blocks/regex.html",
2278            include_str!("templates/blocks/regex.html"),
2279        ),
2280        (
2281            "blocks/rich_text.html",
2282            include_str!("templates/blocks/rich_text.html"),
2283        ),
2284        (
2285            "blocks/typed_table_row.html",
2286            include_str!("templates/blocks/typed_table_row.html"),
2287        ),
2288        (
2289            "blocks/typed_table.html",
2290            include_str!("templates/blocks/typed_table.html"),
2291        ),
2292        (
2293            "blocks/time.html",
2294            include_str!("templates/blocks/time.html"),
2295        ),
2296        (
2297            "blocks/multiple_choice.html",
2298            include_str!("templates/blocks/multiple_choice.html"),
2299        ),
2300        (
2301            "blocks/static.html",
2302            include_str!("templates/blocks/static.html"),
2303        ),
2304        (
2305            "blocks/raw_html.html",
2306            include_str!("templates/blocks/raw_html.html"),
2307        ),
2308        (
2309            "blocks/page_chooser.html",
2310            include_str!("templates/blocks/page_chooser.html"),
2311        ),
2312        (
2313            "blocks/snippet_chooser.html",
2314            include_str!("templates/blocks/snippet_chooser.html"),
2315        ),
2316        (
2317            "blocks/document_chooser.html",
2318            include_str!("templates/blocks/document_chooser.html"),
2319        ),
2320    ])?;
2321
2322    // Public error-page default (the built-in ErrorPage type's
2323    // `default_template()`), registered ONLY when the host hasn't
2324    // shipped its own `error_page.html`. Hosts build their Tera from
2325    // their template glob BEFORE calling `register_templates`, so an
2326    // unconditional add here would silently clobber a host override
2327    // that extends the site's own base/nav/footer.
2328    if !tera.get_template_names().any(|n| n == "error_page.html") {
2329        tera.add_raw_template("error_page.html", include_str!("templates/error_page.html"))?;
2330    }
2331
2332    // Filesystem override walk. Bundled defaults are already
2333    // registered above; anything found under `templates/cms_admin/`
2334    // re-registers with the same Tera name, winning the lookup. See
2335    // the rustdoc above for the directory-to-template-name mapping.
2336    let override_root = std::path::PathBuf::from("templates/cms_admin");
2337    if override_root.is_dir() {
2338        let count = load_template_overrides(&override_root, "", tera)?;
2339        if count > 0 {
2340            tracing::info!(
2341                target: "rustango_cms::admin",
2342                count,
2343                path = %override_root.display(),
2344                "loaded admin template overrides",
2345            );
2346        }
2347    }
2348    Ok(())
2349}
2350
2351/// Recursive walk of `dir` registering every `.html` file as a
2352/// template override. `prefix` accumulates the subdirectory path
2353/// relative to the override root, so `templates/cms_admin/blocks/heading.html`
2354/// becomes Tera template name `blocks/heading.html`.
2355///
2356/// Top-level files get a special-case for `_auth_layout.html`,
2357/// rewriting the bare name to its prefixed form so the override
2358/// reaches the bundled template (which is registered under
2359/// `rcms_admin/_auth_layout.html`). All other top-level files keep
2360/// their bare basename — that's the convention for `login.html` and
2361/// other framework-aligned names.
2362fn load_template_overrides(
2363    dir: &std::path::Path,
2364    prefix: &str,
2365    tera: &mut Tera,
2366) -> Result<usize, tera::Error> {
2367    let mut count = 0;
2368    let entries = std::fs::read_dir(dir)
2369        .map_err(|e| tera::Error::msg(format!("read_dir {}: {e}", dir.display())))?;
2370    for entry in entries {
2371        let entry = entry
2372            .map_err(|e| tera::Error::msg(format!("read_dir entry in {}: {e}", dir.display())))?;
2373        let path = entry.path();
2374        let name = match entry.file_name().into_string() {
2375            Ok(n) => n,
2376            Err(_) => continue,
2377        };
2378        if path.is_dir() {
2379            let nested_prefix = if prefix.is_empty() {
2380                name.clone()
2381            } else {
2382                format!("{prefix}/{name}")
2383            };
2384            count += load_template_overrides(&path, &nested_prefix, tera)?;
2385        } else if path.extension().and_then(|e| e.to_str()) == Some("html") {
2386            let template_name = derive_override_template_name(prefix, &name);
2387            let source = std::fs::read_to_string(&path)
2388                .map_err(|e| tera::Error::msg(format!("read {}: {e}", path.display())))?;
2389            tera.add_raw_template(&template_name, &source)?;
2390            tracing::info!(
2391                target: "rustango_cms::admin",
2392                path = %path.display(),
2393                template = %template_name,
2394                "registered admin template override",
2395            );
2396            count += 1;
2397        }
2398    }
2399    Ok(count)
2400}
2401
2402/// Map an override file's relative path to the Tera template name it
2403/// should re-register as. Subdirectory files use their literal path;
2404/// top-level `_auth_layout.html` is special-cased to the prefixed
2405/// `rcms_admin/_auth_layout.html` name so hosts can override the
2406/// bundled auth chrome with the natural bare filename.
2407fn derive_override_template_name(prefix: &str, file_name: &str) -> String {
2408    if prefix.is_empty() {
2409        // Top-level file — match the bundled namespace for the
2410        // auth-layout partial. Everything else (login.html,
2411        // anything host-side) registers under its bare name.
2412        match file_name {
2413            "_auth_layout.html" => "rcms_admin/_auth_layout.html".to_owned(),
2414            other => other.to_owned(),
2415        }
2416    } else {
2417        format!("{prefix}/{file_name}")
2418    }
2419}
2420
2421/// Errors surfaced through admin handlers. Renders as HTTP responses
2422/// via `IntoResponse`.
2423#[derive(Debug, thiserror::Error)]
2424pub(crate) enum AdminError {
2425    #[error(transparent)]
2426    Tree(#[from] TreeError),
2427    #[error(transparent)]
2428    Exec(#[from] rustango::sql::ExecError),
2429    #[error(transparent)]
2430    Sqlx(#[from] rustango::sql::sqlx::Error),
2431    #[error(transparent)]
2432    Tera(#[from] tera::Error),
2433    #[error("page {0} not found")]
2434    NotFound(i64),
2435    #[error("upload failed: {0}")]
2436    Upload(String),
2437    #[error("{0}")]
2438    Validation(String),
2439}
2440
2441impl IntoResponse for AdminError {
2442    fn into_response(self) -> Response {
2443        let status = match &self {
2444            AdminError::NotFound(_) => StatusCode::NOT_FOUND,
2445            AdminError::Tree(TreeError::DisallowedChildType { .. })
2446            | AdminError::Tree(TreeError::DisallowedParentType { .. })
2447            | AdminError::Tree(TreeError::CycleAttempt) => StatusCode::BAD_REQUEST,
2448            AdminError::Upload(_) => StatusCode::BAD_REQUEST,
2449            AdminError::Validation(_) => StatusCode::BAD_REQUEST,
2450            _ => StatusCode::INTERNAL_SERVER_ERROR,
2451        };
2452        let mut chain = self.to_string();
2453        let mut src: Option<&dyn std::error::Error> = std::error::Error::source(&self);
2454        while let Some(s) = src {
2455            chain.push_str("\n  caused by: ");
2456            chain.push_str(&s.to_string());
2457            src = s.source();
2458        }
2459        if status != StatusCode::INTERNAL_SERVER_ERROR {
2460            // 4xx messages are written for the user.
2461            return (status, chain).into_response();
2462        }
2463        // A 500 carries driver and template internals — table and column
2464        // names, hosts, template source. Log them; give the caller only a
2465        // reference to find the log line by (#711).
2466        let reference = crate::mcp::mint_uuid4();
2467        tracing::error!(target: "rustango_cms::admin", error_ref = %reference, "{chain}");
2468        (status, format!("Internal server error (ref {reference})")).into_response()
2469    }
2470}
2471
2472/// Form payload for the new-page and edit-page POST handlers.
2473#[derive(Debug, Deserialize)]
2474pub struct PageForm {
2475    pub title: String,
2476    pub slug: String,
2477    pub page_type_id: i64,
2478    pub status: String,
2479    /// Which submit button the editor pressed: `save` (→ page
2480    /// list), `continue` (→ keep editing this page), or `addanother`
2481    /// (→ a fresh new-page form under the same parent). Missing or
2482    /// unknown values fall back to `save` in `redirect_after_page_save`.
2483    #[serde(rename = "_action", default)]
2484    pub action: String,
2485    #[serde(default)]
2486    pub seo_title: String,
2487    #[serde(default)]
2488    pub seo_description: String,
2489    #[serde(default)]
2490    pub robots_index: Option<String>,
2491    #[serde(default)]
2492    pub sitemap_priority: Option<f32>,
2493    /// "Show in menus" opt-in checkbox. Pages with this flag
2494    /// set surface in the navigation editor's page picker as
2495    /// suggested entries.
2496    #[serde(default)]
2497    pub show_in_menus: Option<String>,
2498    /// Optional parent id — only honored on `new`. Edit ignores it
2499    /// (moves go through a separate verb, not implemented in v0.1
2500    /// admin).
2501    #[serde(default)]
2502    pub parent_id: Option<i64>,
2503    /// Optional per-page theme override: `None` when the form doesn't
2504    /// carry the field (the editor has no theme input), so a save keeps
2505    /// the stored theme; `Some(None)` when posted empty / 0, which means
2506    /// inherit from ancestors / site default / admin default (#902).
2507    #[serde(default, deserialize_with = "deserialize_present_optional_i64")]
2508    pub theme_id: Option<Option<i64>>,
2509    /// Schedule — page auto-publishes at this moment when the chosen
2510    /// status is `scheduled`. Empty string from the datetime input
2511    /// → None. The admin's form script converts the editor's local time
2512    /// to UTC before submit; a value without an offset is read as UTC
2513    /// (see `parse_datetime_local`).
2514    #[serde(default)]
2515    pub go_live_at: Option<String>,
2516    /// Schedule — page auto-archives at this moment.
2517    #[serde(default)]
2518    pub expire_at: Option<String>,
2519    /// Where this page lives on a decoupled frontend, when that differs
2520    /// from its CMS `url_path`. Empty means "same as `url_path`"; a path
2521    /// replaces `{path}` in the site-wide preview template; an absolute
2522    /// URL replaces the template outright.
2523    #[serde(default)]
2524    pub preview_path: String,
2525    /// Template this page renders through, instead of its page type's.
2526    /// Empty means "use the type's template".
2527    #[serde(default)]
2528    pub template_override: String,
2529    /// Social sharing fields. All optional; the renderer
2530    /// falls back to title / seo_description / first body image
2531    /// when empty.
2532    #[serde(default)]
2533    pub og_title: String,
2534    #[serde(default)]
2535    pub og_description: String,
2536    #[serde(default, deserialize_with = "deserialize_optional_i64")]
2537    pub og_image_media_id: Option<i64>,
2538    #[serde(default)]
2539    pub twitter_card: Option<String>,
2540    /// Comma-separated tags. Read by the create path; an edit reads
2541    /// the raw form.
2542    #[serde(default)]
2543    pub tags: Option<String>,
2544    /// JSON array of category ids, as `tags`.
2545    #[serde(default)]
2546    pub categories: Option<String>,
2547}
2548
2549/// HTML forms submit empty strings for unselected dropdowns; serde
2550/// would reject them as `Option<i64>`. This deserializer maps empty
2551/// string + `"0"` to `None`.
2552pub(crate) fn deserialize_optional_i64<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
2553where
2554    D: serde::Deserializer<'de>,
2555{
2556    use serde::Deserialize as _;
2557    let s = String::deserialize(deserializer)?;
2558    if s.is_empty() || s == "0" {
2559        return Ok(None);
2560    }
2561    s.parse::<i64>().map(Some).map_err(serde::de::Error::custom)
2562}
2563
2564/// [`deserialize_optional_i64`] for a field whose absence means "leave
2565/// unchanged": present → `Some(..)`, absent → `None` via `default`.
2566fn deserialize_present_optional_i64<'de, D>(deserializer: D) -> Result<Option<Option<i64>>, D::Error>
2567where
2568    D: serde::Deserializer<'de>,
2569{
2570    deserialize_optional_i64(deserializer).map(Some)
2571}
2572
2573impl PageForm {
2574    /// Parse the `status` field into the typed enum, defaulting to
2575    /// `Draft` on any unrecognized value rather than failing the
2576    /// submit. Editors fix the value on the next save.
2577    fn parsed_status(&self) -> PageStatus {
2578        match self.status.as_str() {
2579            "published" => PageStatus::Published,
2580            "scheduled" => PageStatus::Scheduled,
2581            "archived" => PageStatus::Archived,
2582            _ => PageStatus::Draft,
2583        }
2584    }
2585
2586    /// HTML form checkboxes submit `on` when checked, are absent when
2587    /// unchecked. Map to bool.
2588    fn parsed_robots_index(&self) -> bool {
2589        self.robots_index.is_some()
2590    }
2591
2592    fn parsed_sitemap_priority(&self) -> f32 {
2593        self.sitemap_priority.unwrap_or(0.5)
2594    }
2595
2596    fn parsed_show_in_menus(&self) -> bool {
2597        self.show_in_menus.is_some()
2598    }
2599
2600    /// Parse an HTML5 `datetime-local` value (`YYYY-MM-DDTHH:MM`)
2601    /// into a UTC instant. Empty / unparseable → `None`. The browser
2602    /// emits naive local time; until per-user timezones land
2603    /// we treat the value as UTC. Editors set realistic times in
2604    /// their own zone and accept the small offset for now.
2605    fn parsed_go_live_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
2606        parse_datetime_local(self.go_live_at.as_deref())
2607    }
2608
2609    fn parsed_expire_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
2610        parse_datetime_local(self.expire_at.as_deref())
2611    }
2612}
2613
2614fn parse_datetime_local(raw: Option<&str>) -> Option<chrono::DateTime<chrono::Utc>> {
2615    let raw = raw?.trim();
2616    if raw.is_empty() {
2617        return None;
2618    }
2619    // The admin's datetime inputs send UTC with a `Z` (converted from the
2620    // editor's timezone in the browser); an offset is honoured too.
2621    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
2622        return Some(dt.with_timezone(&chrono::Utc));
2623    }
2624    if let Some(utc) = raw.strip_suffix('Z') {
2625        return parse_datetime_local(Some(utc));
2626    }
2627    // Without JS the input posts its UTC value bare: "YYYY-MM-DDTHH:MM"
2628    // or "YYYY-MM-DDTHH:MM:SS".
2629    chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M")
2630        .or_else(|_| chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S"))
2631        .ok()
2632        .map(|naive| chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(naive, chrono::Utc))
2633}
2634
2635#[cfg(test)]
2636mod datetime_input_tests {
2637    use super::parse_datetime_local;
2638
2639    /// The schedule inputs post UTC (`…Z`), converted in the browser from the
2640    /// editor's timezone; without JS they post the bare UTC value back.
2641    #[test]
2642    fn utc_offset_and_bare_values_parse_to_the_same_instant() {
2643        let want = chrono::DateTime::parse_from_rfc3339("2026-12-01T12:00:00Z")
2644            .unwrap()
2645            .with_timezone(&chrono::Utc);
2646        for raw in ["2026-12-01T12:00Z", "2026-12-01T12:00:00Z", "2026-12-01T09:00:00-03:00", "2026-12-01T12:00", " 2026-12-01T12:00:00 "] {
2647            assert_eq!(parse_datetime_local(Some(raw)), Some(want), "{raw}");
2648        }
2649        assert_eq!(parse_datetime_local(Some("")), None);
2650        assert_eq!(parse_datetime_local(Some("tomorrow")), None);
2651    }
2652}
2653
2654#[cfg(test)]
2655mod admin_error_tests {
2656    use super::AdminError;
2657    use axum::response::IntoResponse as _;
2658
2659    async fn body(e: AdminError) -> (u16, String) {
2660        let resp = e.into_response();
2661        let status = resp.status().as_u16();
2662        let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16).await.expect("body");
2663        (status, String::from_utf8(bytes.to_vec()).expect("utf8"))
2664    }
2665
2666    /// A 500 names no table, host or template; a 4xx keeps its
2667    /// user-facing message.
2668    #[tokio::test]
2669    async fn server_errors_hide_their_cause_and_client_errors_do_not() {
2670        let tera_err = tera::Tera::one_off("{{ secret_column | nope }}", &tera::Context::new(), false)
2671            .expect_err("bad template");
2672        let (status, text) = body(AdminError::Tera(tera_err)).await;
2673        assert_eq!(status, 500);
2674        assert!(text.starts_with("Internal server error (ref "), "{text}");
2675        assert!(!text.contains("secret_column") && !text.contains("nope"), "{text}");
2676
2677        let (status, text) = body(AdminError::Validation("slug is taken".into())).await;
2678        assert_eq!(status, 400);
2679        assert!(text.contains("slug is taken"));
2680    }
2681}
2682
2683#[cfg(test)]
2684mod template_shape_tests {
2685    /// JSON inlined into a script body cannot end the element, and
2686    /// still parses back to the same value.
2687    #[test]
2688    fn json_script_cannot_close_the_script_element() {
2689        let hostile = serde_json::json!([{
2690            "name": "</script><script>alert('x')</script> & <!--",
2691        }]);
2692        let mut tera = tera::Tera::default();
2693        super::register_templates(&mut tera).expect("register");
2694        tera.add_raw_template("t", "<script>const X = {{ v | json_script }};</script>")
2695            .expect("template");
2696        let mut ctx = tera::Context::new();
2697        ctx.insert("v", &hostile);
2698        let out = tera.render("t", &ctx).expect("render");
2699        let body = out
2700            .strip_prefix("<script>const X = ")
2701            .and_then(|r| r.strip_suffix(";</script>"))
2702            .expect("one script element");
2703        assert!(!body.contains('<') && !body.contains('>') && !body.contains('\''), "{body}");
2704        let back: serde_json::Value = serde_json::from_str(body).expect("still JSON");
2705        assert_eq!(back, hostile);
2706    }
2707
2708    /// Guard: `json_encode | safe` let raw JSON break out of a script. Script and
2709    /// attribute contexts use `json_script`.
2710    #[test]
2711    fn no_admin_template_inlines_raw_json() {
2712        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin/templates");
2713        let offenders: Vec<String> = std::fs::read_dir(&dir)
2714            .expect("read templates dir")
2715            .filter_map(|e| {
2716                let path = e.expect("dir entry").path();
2717                let src = std::fs::read_to_string(&path).ok()?;
2718                src.contains("json_encode | safe")
2719                    .then(|| path.file_name().unwrap().to_string_lossy().to_string())
2720            })
2721            .collect();
2722        assert!(offenders.is_empty(), "use `| json_script` instead: {offenders:?}");
2723    }
2724
2725    /// Every admin page opens the same way, and the opening comes from
2726    /// one place.
2727    ///
2728    /// It used not to. Thirteen templates dropped a bare
2729    /// `<p class="rcms-hint">` straight into the content column while
2730    /// eight wrapped the same prose in a `.rcms-card`, so Taxonomies and
2731    /// Library described themselves in visibly different boxes — and
2732    /// each one got fixed only when somebody noticed it on screen.
2733    /// `_list_base.html` owns the intro card now; this keeps the next
2734    /// page from hand-rolling its own.
2735    #[test]
2736    fn page_descriptions_come_from_the_shared_intro_card() {
2737        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin/templates");
2738        let mut offenders = Vec::new();
2739        let mut checked = 0;
2740        for entry in std::fs::read_dir(&dir).expect("read templates dir") {
2741            let path = entry.expect("dir entry").path();
2742            if path.extension().and_then(|e| e.to_str()) != Some("html") {
2743                continue;
2744            }
2745            let src = std::fs::read_to_string(&path).expect("read template");
2746            let name = path.file_name().unwrap().to_string_lossy().to_string();
2747            if src.contains("rcms_admin/_list_base.html") {
2748                // Conformant by construction: the base emits the card.
2749                checked += 1;
2750                continue;
2751            }
2752            let Some(rest) = src.split_once("{% block content %}") else {
2753                continue;
2754            };
2755            checked += 1;
2756            let head = rest.1.trim_start();
2757            if head.starts_with("<p class=\"rcms-hint") {
2758                offenders.push(format!(
2759                    "{name}: bare <p class=\"rcms-hint\"> opens the content \
2760                     column — extend rcms_admin/_list_base.html and put the \
2761                     prose in {{% block description %}}"
2762                ));
2763            } else if rest
2764                .1
2765                .contains("<div class=\"rcms-card\">\n    <p class=\"rcms-hint")
2766            {
2767                // Two pages hid the intro card inside an `{% if %}` branch,
2768                // so it looked right on screen while still being a private
2769                // copy — checking only the first element missed them.
2770                offenders.push(format!(
2771                    "{name}: hand-rolled intro card — extend \
2772                     rcms_admin/_list_base.html instead"
2773                ));
2774            }
2775        }
2776        assert!(
2777            checked > 40,
2778            "expected to scan most admin templates, scanned {checked} — \
2779             the `{{% block content %}}` probe is broken"
2780        );
2781        assert!(
2782            offenders.is_empty(),
2783            "{} page(s) don't use the shared intro card:\n{}",
2784            offenders.len(),
2785            offenders.join("\n")
2786        );
2787    }
2788
2789    /// An authored template must not be able to read the process
2790    /// environment through Tera's `get_env` builtin. `register_templates`
2791    /// overrides it; here we prove a template calling it cannot leak one.
2792    /// Removing the override makes this fail.
2793    ///
2794    /// Probes `CARGO_PKG_NAME`, which cargo sets for every test binary,
2795    /// rather than setting a variable: `set_var` while other tests run in
2796    /// parallel is a data race.
2797    #[test]
2798    fn get_env_is_disabled_in_the_render_engine() {
2799        let secret = std::env::var("CARGO_PKG_NAME").expect("cargo sets CARGO_PKG_NAME");
2800        let mut tera = tera::Tera::default();
2801        super::register_templates(&mut tera).expect("register_templates");
2802        tera.add_raw_template("ssti.html", r#"{{ get_env(name="CARGO_PKG_NAME") }}"#)
2803            .expect("add template");
2804        match tera.render("ssti.html", &tera::Context::new()) {
2805            // The override returns an error, so the render fails closed.
2806            Err(_) => {}
2807            // Belt-and-braces: even if a future change makes it fail open,
2808            // the value must never appear in the output.
2809            Ok(out) => assert!(
2810                !out.contains(&secret),
2811                "get_env leaked the process environment into a template: {out}"
2812            ),
2813        }
2814    }
2815}