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