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