Skip to main content

slabs_html/
lib.rs

1//! Compile-time HTML rendering, document layout, HTMX helpers, and CSRF tokens for Slabs.
2//!
3//! This crate re-exports [`html!`] (aliased as `maud!` in `slabs::prelude`) so handlers build
4//! auto-escaped HTML at compile time with zero runtime template engine.
5//!
6//! # Document layout
7//!
8//! [`document`] renders a complete HTML5 page with native view transitions
9//! (`@view-transition { navigation: auto; }`), vendored Basecoat UI styles and scripts
10//! (`/_slabs/vendor/basecoat.min.css` and `/_slabs/vendor/basecoat.min.js`), HTMX 2 with the SSE
11//! and Idiomorph extensions (`hx-ext="morph"` on `<body>`), and Alpine.js 3.
12//! Pass app-compiled Tailwind CSS v4 stylesheets (for example `&ctx.assets.stylesheet_urls()`) and
13//! module scripts via the `stylesheets` and `scripts` arguments.
14//! All frontend assets are self-hosted with zero CDN or Node runtime requirement.
15//!
16//! # HTMX helpers
17//!
18//! The [`htmx`] module emits standard `HX-*` headers and `hx-swap-oob` fragments:
19//!
20//! - [`htmx::redirect`] triggers a full navigation via `HX-Redirect`.
21//! - [`htmx::with_trigger`] attaches an `HX-Trigger` client event header to a fragment.
22//! - [`htmx::oob`], [`htmx::oob_replace`], and [`htmx::oob_delete`] wrap out-of-band DOM swaps.
23//! - [`htmx::is_htmx`] and [`htmx::wants_json`] inspect `HX-Request` and `Accept` headers.
24//!
25//! # CSRF protection
26//!
27//! Use [`csrf_token`] to mint a signed token bound to a session scope and [`verify_csrf`] to check
28//! submitted tokens.
29//!
30//! # Usage
31//!
32//! ```rust,no_run
33//! use axum::http::HeaderMap;
34//! use axum::response::IntoResponse;
35//! use slabs_html::{document, html, htmx};
36//!
37//! fn render_notice(headers: &HeaderMap, styles: &[String]) -> axum::response::Response {
38//!     let fragment = html! {
39//!         p id="notice" { "Saved." }
40//!     };
41//!
42//!     if htmx::is_htmx(headers) {
43//!         return htmx::oob_replace("notice", fragment).into_response();
44//!     }
45//!
46//!     document("Notice", styles, &[], fragment).into_response()
47//! }
48//! ```
49
50use axum::response::{IntoResponse, Response};
51use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
52use base64::engine::general_purpose::URL_SAFE_NO_PAD;
53use http::{header, HeaderMap, HeaderValue, StatusCode};
54use serde::{Deserialize, Serialize};
55use slabs_auth::Auth;
56use slabs_core::{SlabError, SlabResult};
57
58pub use maud::{html, Markup, PreEscaped, Render, DOCTYPE};
59
60/// Cookie name used to store one-shot signed flash messages.
61pub const FLASH_COOKIE_NAME: &str = "slabs_flash";
62
63/// Severity level for a one-shot [`Flash`] banner message.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "lowercase")]
66pub enum FlashKind {
67    /// Confirmation that an action succeeded.
68    Success,
69    /// Neutral informational notice.
70    Info,
71    /// Non-fatal cautionary notice.
72    Warning,
73    /// Error or failure notice.
74    Error,
75}
76
77/// One-shot feedback message carried across a redirect in a signed cookie.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct Flash {
80    /// Severity level determining how the banner is styled.
81    pub kind: FlashKind,
82    /// Human-readable feedback text displayed to the user.
83    pub message: String,
84}
85
86impl Flash {
87    /// Create a [`FlashKind::Success`] flash message.
88    #[must_use]
89    pub fn success(message: impl Into<String>) -> Self {
90        Self {
91            kind: FlashKind::Success,
92            message: message.into(),
93        }
94    }
95
96    /// Create a [`FlashKind::Info`] flash message.
97    #[must_use]
98    pub fn info(message: impl Into<String>) -> Self {
99        Self {
100            kind: FlashKind::Info,
101            message: message.into(),
102        }
103    }
104
105    /// Create a [`FlashKind::Warning`] flash message.
106    #[must_use]
107    pub fn warning(message: impl Into<String>) -> Self {
108        Self {
109            kind: FlashKind::Warning,
110            message: message.into(),
111        }
112    }
113
114    /// Create a [`FlashKind::Error`] flash message.
115    #[must_use]
116    pub fn error(message: impl Into<String>) -> Self {
117        Self {
118            kind: FlashKind::Error,
119            message: message.into(),
120        }
121    }
122}
123
124/// Escape `&`, `<`, `>`, `"`, and `'` into HTML entities for manually assembled strings.
125///
126/// Prefer [`html!`] (`maud!` in `slabs::prelude`), which auto-escapes interpolated values at
127/// compile time.
128pub fn escape(input: &str) -> String {
129    let mut out = String::with_capacity(input.len());
130    for ch in input.chars() {
131        match ch {
132            '&' => out.push_str("&amp;"),
133            '<' => out.push_str("&lt;"),
134            '>' => out.push_str("&gt;"),
135            '"' => out.push_str("&quot;"),
136            '\'' => out.push_str("&#x27;"),
137            _ => out.push(ch),
138        }
139    }
140    out
141}
142
143/// Standard HTMX 2 helpers for `HX-*` headers, `hx-swap-oob` fragments, and signed flash cookies.
144pub mod htmx {
145    use super::{
146        header, html, Auth, Cookie, CookieJar, Flash, HeaderMap, HeaderValue, IntoResponse, Markup,
147        PreEscaped, Response, SameSite, StatusCode, FLASH_COOKIE_NAME, URL_SAFE_NO_PAD,
148    };
149    use base64::Engine as _;
150
151    /// Store a signed one-shot [`Flash`] message in the `slabs_flash` cookie (`HttpOnly`, `SameSite=Lax`, `Path=/`).
152    #[must_use = "return the updated CookieJar in your response so the flash cookie is sent"]
153    pub fn set_flash(auth: &Auth, jar: CookieJar, flash: &Flash) -> CookieJar {
154        let Ok(json) = serde_json::to_vec(flash) else {
155            return jar;
156        };
157        let encoded = URL_SAFE_NO_PAD.encode(json);
158        let sig = auth.sign(&format!("flash:{encoded}"));
159        let cookie = Cookie::build((FLASH_COOKIE_NAME, format!("{encoded}.{sig}")))
160            .path("/")
161            .http_only(true)
162            .same_site(SameSite::Lax)
163            .secure(auth.cookie_secure())
164            .build();
165        jar.add(cookie)
166    }
167
168    /// Read and verify the signed `slabs_flash` cookie, removing it from `jar` if present.
169    ///
170    /// Returns `(jar, None)` when the cookie is absent, malformed, or fails HMAC verification.
171    #[must_use = "return the updated CookieJar in your response so the flash cookie is cleared"]
172    pub fn take_flash(auth: &Auth, jar: CookieJar) -> (CookieJar, Option<Flash>) {
173        let Some(raw) = jar.get(FLASH_COOKIE_NAME).map(|c| c.value().to_string()) else {
174            return (jar, None);
175        };
176
177        let removal = Cookie::build((FLASH_COOKIE_NAME, ""))
178            .path("/")
179            .http_only(true)
180            .same_site(SameSite::Lax)
181            .secure(auth.cookie_secure())
182            .build();
183        let jar = jar.remove(removal);
184
185        let flash = decode_flash(auth, &raw);
186        (jar, flash)
187    }
188
189    /// Set a signed [`Flash`] cookie and return `303 See Other` with both `Location` and `HX-Redirect`.
190    ///
191    /// Works identically for standard browser form posts and HTMX requests. Falls back to `"/"`
192    /// if `location` is not a valid HTTP header value.
193    pub fn flash_redirect(auth: &Auth, jar: CookieJar, location: &str, flash: &Flash) -> Response {
194        let jar = set_flash(auth, jar, flash);
195        let target =
196            HeaderValue::from_str(location).unwrap_or_else(|_| HeaderValue::from_static("/"));
197        let mut headers = HeaderMap::new();
198        headers.insert(header::LOCATION, target.clone());
199        headers.insert("hx-redirect", target);
200        (StatusCode::SEE_OTHER, jar, headers).into_response()
201    }
202
203    fn decode_flash(auth: &Auth, raw: &str) -> Option<Flash> {
204        let (encoded, sig) = raw.split_once('.')?;
205        if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
206            return None;
207        }
208        if !auth.verify_signature(&format!("flash:{encoded}"), sig) {
209            return None;
210        }
211        let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?;
212        serde_json::from_slice(&bytes).ok()
213    }
214
215    /// Return a `200 OK` response with `HX-Redirect` so HTMX performs a full navigation.
216    ///
217    /// Falls back to `"/"` if `path` is not a valid HTTP header value.
218    pub fn redirect(path: &str) -> Response {
219        let mut headers = HeaderMap::new();
220        headers.insert(
221            "hx-redirect",
222            HeaderValue::from_str(path).unwrap_or_else(|_| HeaderValue::from_static("/")),
223        );
224        (StatusCode::OK, headers).into_response()
225    }
226
227    /// Return a `200 OK` HTML fragment with an `HX-Trigger` client event header.
228    pub fn with_trigger(markup: Markup, event: &str) -> Response {
229        let mut headers = HeaderMap::new();
230        if let Ok(val) = HeaderValue::from_str(event) {
231            headers.insert("hx-trigger", val);
232        }
233        (StatusCode::OK, headers, markup).into_response()
234    }
235
236    /// Wrap `inner` in an HTMX out-of-band swap container (`hx-swap-oob`).
237    ///
238    /// `swap` accepts any HTMX swap strategy such as `"beforeend"`, `"afterbegin"`, `"innerHTML"`,
239    /// `"outerHTML"`, or `"true"`. A leading `#` on `target_id` is stripped automatically.
240    pub fn oob(target_id: &str, swap: &str, inner: Markup) -> Markup {
241        let clean_id = target_id.trim_start_matches('#');
242        let attr = format!("{swap}:#{clean_id}");
243        html! {
244            div hx-swap-oob=(attr) { (PreEscaped(inner.into_string())) }
245        }
246    }
247
248    /// Emit an HTMX out-of-band delete instruction (`hx-swap-oob="delete"`) for `target_id`.
249    ///
250    /// A leading `#` on `target_id` is stripped automatically.
251    pub fn oob_delete(target_id: &str) -> Markup {
252        let clean_id = target_id.trim_start_matches('#');
253        html! {
254            div id=(clean_id) hx-swap-oob="delete" {}
255        }
256    }
257
258    /// Emit an HTMX out-of-band `outerHTML` swap targeting `target_id`.
259    ///
260    /// A leading `#` on `target_id` is stripped automatically.
261    pub fn oob_replace(target_id: &str, inner: Markup) -> Markup {
262        let clean_id = target_id.trim_start_matches('#');
263        html! {
264            div hx-swap-oob=(format!("outerHTML:#{clean_id}")) { (PreEscaped(inner.into_string())) }
265        }
266    }
267
268    /// Return `true` when the request carries `HX-Request: true`.
269    pub fn is_htmx(headers: &HeaderMap) -> bool {
270        headers
271            .get("hx-request")
272            .and_then(|v| v.to_str().ok())
273            .is_some_and(|v| v == "true")
274    }
275
276    /// Return `true` when the `Accept` header contains `application/json`.
277    pub fn wants_json(headers: &HeaderMap) -> bool {
278        headers
279            .get(header::ACCEPT)
280            .and_then(|v| v.to_str().ok())
281            .is_some_and(|v| v.contains("application/json"))
282    }
283}
284
285/// Render a Basecoat alert banner for an optional [`Flash`] message.
286///
287/// Renders a `<div class="alert" role="status">` when `flash` is `Some`, applying
288/// `data-variant="destructive"` for [`FlashKind::Error`], or empty [`Markup`] when `None`.
289#[must_use]
290pub fn flash_banner(flash: Option<&Flash>) -> Markup {
291    let Some(flash) = flash else {
292        return html! {};
293    };
294    let (kind_str, variant) = match flash.kind {
295        FlashKind::Success => ("success", None),
296        FlashKind::Info => ("info", None),
297        FlashKind::Warning => ("warning", None),
298        FlashKind::Error => ("error", Some("destructive")),
299    };
300    html! {
301        div class="alert" role="status" data-flash-kind=(kind_str) data-variant=[variant] {
302            section {
303                p { (flash.message) }
304            }
305        }
306    }
307}
308
309/// Render a complete HTML5 page around `body` using compile-time [`Markup`].
310///
311/// Loads native view transitions (`@view-transition { navigation: auto; }`), PWA manifest and
312/// theme metadata, Basecoat UI (`/_slabs/vendor/basecoat.min.css` and
313/// `/_slabs/vendor/basecoat.min.js`), HTMX 2 with SSE and Idiomorph (`hx-ext="morph"` on
314/// `<body>`), Alpine.js 3 (`/_slabs/vendor/alpine.min.js`), and a non-blocking service-worker
315/// registration script at the end of `<body>`. Pass app-compiled Tailwind CSS v4 URLs in
316/// `stylesheets` (such as `&ctx.assets.stylesheet_urls()`) and ES module URLs in `scripts`.
317pub fn document(title: &str, stylesheets: &[String], scripts: &[String], body: Markup) -> Markup {
318    html! {
319        (DOCTYPE)
320        html lang="en" class="dark" {
321            head {
322                meta charset="utf-8";
323                meta name="viewport" content="width=device-width, initial-scale=1";
324                link rel="manifest" href="/manifest.webmanifest";
325                meta name="theme-color" content="#1a1b26";
326                meta name="apple-mobile-web-app-capable" content="yes";
327                title { (title) }
328                style { (PreEscaped("@view-transition { navigation: auto; }")) }
329                link rel="stylesheet" href="/_slabs/vendor/basecoat.min.css";
330                @for href in stylesheets {
331                    link rel="stylesheet" href=(href);
332                }
333                script src="/_slabs/vendor/htmx.min.js" defer {}
334                script src="/_slabs/vendor/htmx-ext-sse.js" defer {}
335                script src="/_slabs/vendor/idiomorph-ext.min.js" defer {}
336                script src="/_slabs/vendor/basecoat.min.js" defer {}
337                script src="/_slabs/vendor/alpine.min.js" defer {}
338                @for src in scripts {
339                    script type="module" src=(src) defer {}
340                }
341            }
342            body class="min-h-screen bg-background text-foreground antialiased" hx-ext="morph" {
343                (PreEscaped(body.into_string()))
344                script {
345                    (PreEscaped("if('serviceWorker' in navigator){window.addEventListener('load',function(){navigator.serviceWorker.register('/service-worker.js').catch(function(){});});}"))
346                }
347            }
348        }
349    }
350}
351
352/// Generate an HMAC-signed CSRF token bound to `scope` (such as a session ID or `"anon"`).
353///
354/// Returns `<nonce>.<signature>`, where the signature covers `"{scope}:{nonce}"`.
355pub fn csrf_token(auth: &Auth, scope: &str) -> String {
356    let nonce = slabs_core::id::new("csrf");
357    let payload = format!("{scope}:{nonce}");
358    let sig = auth.sign(&payload);
359    format!("{nonce}.{sig}")
360}
361
362/// Verify a submitted CSRF token against `scope`.
363///
364/// Returns a `403 Forbidden` [`SlabError`] if the token format or signature is invalid.
365pub fn verify_csrf(auth: &Auth, scope: &str, token: &str) -> SlabResult<()> {
366    let Some((nonce, sig)) = token.split_once('.') else {
367        return Err(SlabError::forbidden("invalid csrf token format"));
368    };
369    let payload = format!("{scope}:{nonce}");
370    if auth.verify_signature(&payload, sig) {
371        Ok(())
372    } else {
373        Err(SlabError::forbidden("csrf token verification failed"))
374    }
375}
376
377/// Render untrusted `CommonMark` and GitHub-flavored Markdown into safe [`Markup`].
378///
379/// Enables tables, strikethrough, task lists, and heading attributes. Drops raw HTML blocks and
380/// inline HTML tags so untrusted authors cannot inject `<script>`, `on*` event handlers, or
381/// HTMX/Alpine attributes (`hx-*`, `x-data`, `x-init`). Rewrites unsafe link or image URL schemes
382/// (`javascript:`, `vbscript:`, `data:`) to `"#"`.
383pub fn render_markdown(input: &str) -> Markup {
384    use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
385
386    let mut options = Options::empty();
387    options.insert(Options::ENABLE_TABLES);
388    options.insert(Options::ENABLE_STRIKETHROUGH);
389    options.insert(Options::ENABLE_TASKLISTS);
390
391    let parser = Parser::new_ext(input, options).filter_map(|event| match event {
392        Event::Html(_) | Event::InlineHtml(_) => None,
393        Event::Start(Tag::Link {
394            link_type,
395            dest_url,
396            title,
397            id,
398        }) => Some(Event::Start(Tag::Link {
399            link_type,
400            dest_url: sanitize_url(&dest_url).into(),
401            title,
402            id,
403        })),
404        Event::Start(Tag::Image {
405            link_type,
406            dest_url,
407            title,
408            id,
409        }) => Some(Event::Start(Tag::Image {
410            link_type,
411            dest_url: sanitize_url(&dest_url).into(),
412            title,
413            id,
414        })),
415        Event::End(TagEnd::Link) => Some(Event::End(TagEnd::Link)),
416        other => Some(other),
417    });
418
419    let mut html_out = String::with_capacity(input.len() + 64);
420    pulldown_cmark::html::push_html(&mut html_out, parser);
421    PreEscaped(html_out)
422}
423
424fn sanitize_url(raw: &str) -> String {
425    let trimmed = raw.trim();
426    let lower = trimmed.to_ascii_lowercase();
427    if lower.starts_with("http://")
428        || lower.starts_with("https://")
429        || lower.starts_with("mailto:")
430        || lower.starts_with('/')
431        || lower.starts_with('#')
432        || !lower.contains(':')
433    {
434        trimmed.to_string()
435    } else {
436        "#".to_string()
437    }
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn render_markdown_renders_gfm_and_blocks_xss_and_htmx_injection() {
446        let md = "# Title\n\n<script>alert(1)</script>\n<div hx-get=\"/evil\" x-init=\"pwn()\">bad</div>\n\n[ok](https://example.com) and [bad](javascript:alert(1))\n\n| A | B |\n| - | - |\n| 1 | 2 |\n";
447        let rendered = render_markdown(md).into_string();
448        assert!(rendered.contains("<h1>Title</h1>"));
449        assert!(rendered.contains("<table>"));
450        assert!(rendered.contains("href=\"https://example.com\""));
451        assert!(!rendered.contains("<script>"));
452        assert!(!rendered.contains("hx-get"));
453        assert!(!rendered.contains("x-init"));
454        assert!(!rendered.contains("javascript:"));
455    }
456
457    #[test]
458    fn flash_roundtrip_and_one_shot_consumption() {
459        let auth = Auth::for_signing("test-flash-secret-key", false);
460        let flash = Flash::success("Saved changes.");
461
462        let jar = htmx::set_flash(&auth, CookieJar::new(), &flash);
463        let cookie = jar.get(FLASH_COOKIE_NAME).expect("flash cookie set");
464        assert_eq!(cookie.path(), Some("/"));
465        assert_eq!(cookie.http_only(), Some(true));
466        assert_eq!(cookie.same_site(), Some(SameSite::Lax));
467
468        let (jar, taken) = htmx::take_flash(&auth, jar);
469        assert_eq!(taken, Some(flash));
470        assert!(jar.get(FLASH_COOKIE_NAME).is_none());
471
472        let (_jar, second) = htmx::take_flash(&auth, jar);
473        assert_eq!(second, None);
474    }
475
476    #[test]
477    fn flash_rejects_tampered_cookie_and_clears_it() {
478        let auth = Auth::for_signing("test-flash-secret-key", false);
479        let jar = htmx::set_flash(&auth, CookieJar::new(), &Flash::info("Hello"));
480        let raw = jar.get(FLASH_COOKIE_NAME).unwrap().value().to_string();
481        let (encoded, sig) = raw.split_once('.').unwrap();
482        let flipped = if sig.starts_with('0') { '1' } else { '0' };
483        let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);
484
485        let mut tampered_headers = HeaderMap::new();
486        tampered_headers.insert(
487            header::COOKIE,
488            HeaderValue::from_str(&format!("{FLASH_COOKIE_NAME}={tampered}")).unwrap(),
489        );
490        let tampered_jar = CookieJar::from_headers(&tampered_headers);
491
492        let (cleared_jar, taken) = htmx::take_flash(&auth, tampered_jar);
493        assert_eq!(taken, None);
494        assert!(cleared_jar.get(FLASH_COOKIE_NAME).is_none());
495    }
496
497    #[test]
498    fn flash_redirect_sets_see_other_location_hx_redirect_and_cookie() {
499        let auth = Auth::for_signing("test-flash-secret-key", false);
500        let resp = htmx::flash_redirect(
501            &auth,
502            CookieJar::new(),
503            "/rooms",
504            &Flash::warning("Room archived"),
505        );
506
507        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
508        assert_eq!(
509            resp.headers()
510                .get(header::LOCATION)
511                .and_then(|v| v.to_str().ok()),
512            Some("/rooms")
513        );
514        assert_eq!(
515            resp.headers()
516                .get("hx-redirect")
517                .and_then(|v| v.to_str().ok()),
518            Some("/rooms")
519        );
520        let set_cookie = resp
521            .headers()
522            .get(header::SET_COOKIE)
523            .and_then(|v| v.to_str().ok())
524            .expect("Set-Cookie header present");
525        assert!(set_cookie.contains("slabs_flash="));
526        assert!(set_cookie.contains("HttpOnly"));
527        assert!(set_cookie.contains("SameSite=Lax"));
528        assert!(set_cookie.contains("Path=/"));
529    }
530
531    #[test]
532    fn flash_banner_renders_accessible_alert_or_empty() {
533        assert_eq!(flash_banner(None).into_string(), "");
534
535        let ok_html = flash_banner(Some(&Flash::success("Item <saved>"))).into_string();
536        assert!(ok_html.contains("class=\"alert\""));
537        assert!(ok_html.contains("role=\"status\""));
538        assert!(ok_html.contains("data-flash-kind=\"success\""));
539        assert!(ok_html.contains("Item &lt;saved&gt;"));
540        assert!(!ok_html.contains("data-variant=\"destructive\""));
541
542        let err_html = flash_banner(Some(&Flash::error("Failed"))).into_string();
543        assert!(err_html.contains("role=\"status\""));
544        assert!(err_html.contains("data-flash-kind=\"error\""));
545        assert!(err_html.contains("data-variant=\"destructive\""));
546        assert!(err_html.contains("Failed"));
547    }
548
549    #[test]
550    fn document_includes_pwa_head_tags_and_service_worker_registration() {
551        let rendered = document("Campfire", &[], &[], html! { main { "Hi" } }).into_string();
552        assert!(rendered.contains("<link rel=\"manifest\" href=\"/manifest.webmanifest\">"));
553        assert!(rendered.contains("<meta name=\"theme-color\" content=\"#1a1b26\">"));
554        assert!(rendered.contains("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">"));
555        assert!(rendered.contains(
556            "if('serviceWorker' in navigator){window.addEventListener('load',function(){navigator.serviceWorker.register('/service-worker.js').catch(function(){});});}"
557        ));
558    }
559}