slabs-html 0.5.0

Hypermedia SSR HTML battery: compile-time maud markup, Turbo-style HTML streams, layouts, and CSRF tokens
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
//! Compile-time HTML rendering, document layout, HTMX helpers, and CSRF tokens for Slabs.
//!
//! This crate re-exports [`html!`] (aliased as `maud!` in `slabs::prelude`) so handlers build
//! auto-escaped HTML at compile time with zero runtime template engine.
//!
//! # Document layout
//!
//! [`document`] renders a complete, CSP-friendly HTML5 page with zero inline `<style>` or inline
//! `<script>` elements. Native view transitions (`@view-transition { navigation: auto; }`) ship
//! inside `/_slabs/vendor/basecoat.min.css`, and service-worker registration loads externally via
//! `/_slabs/vendor/sw-register.js` alongside Basecoat UI, HTMX 2 (with SSE and Idiomorph
//! `hx-ext="morph"` on `<body>`), and Alpine.js 3.
//! Pass app-compiled Tailwind CSS v4 stylesheets (for example `&ctx.assets.stylesheet_urls()`) and
//! module scripts via the `stylesheets` and `scripts` arguments.
//! All frontend assets are self-hosted with zero CDN or Node runtime requirement.
//!
//! # HTMX helpers
//!
//! The [`htmx`] module emits standard `HX-*` headers and `hx-swap-oob` fragments:
//!
//! - [`htmx::redirect`] triggers a full same-origin navigation via `HX-Redirect` (sanitized against open redirects).
//! - [`redirect_external`] emits an explicit `303 See Other` redirect to an `http://` or `https://` URL.
//! - [`htmx::with_trigger`] attaches an `HX-Trigger` client event header to a fragment.
//! - [`htmx::oob`], [`htmx::oob_replace`], and [`htmx::oob_delete`] wrap sanitized out-of-band DOM swaps.
//! - [`htmx::is_htmx`] and [`htmx::wants_json`] inspect `HX-Request` and `Accept` headers.
//!
//! # CSRF protection
//!
//! Use [`csrf_token`] to mint a domain-separated, expiring HMAC-signed token bound to a session
//! scope and [`verify_csrf`] to verify submitted tokens.
//!
//! # Usage
//!
//! ```rust,no_run
//! use axum::http::HeaderMap;
//! use axum::response::IntoResponse;
//! use slabs_html::{document, html, htmx};
//!
//! fn render_notice(headers: &HeaderMap, styles: &[String]) -> axum::response::Response {
//!     let fragment = html! {
//!         p id="notice" { "Saved." }
//!     };
//!
//!     if htmx::is_htmx(headers) {
//!         return htmx::oob_replace("notice", fragment).into_response();
//!     }
//!
//!     document("Notice", styles, &[], fragment).into_response()
//! }
//! ```

use axum::response::{IntoResponse, Response};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use chrono::Utc;
use http::{header, HeaderMap, HeaderValue, StatusCode};
use rand_core::{OsRng, RngCore};
use serde::{Deserialize, Serialize};
use slabs_auth::Auth;
use slabs_core::{SlabError, SlabResult};

pub use maud::{html, Markup, PreEscaped, Render, DOCTYPE};

/// Cookie name used to store one-shot signed flash messages.
pub const FLASH_COOKIE_NAME: &str = "slabs_flash";

/// External service-worker registration script served at `/_slabs/vendor/sw-register.js`.
///
/// Referenced via `<script src="/_slabs/vendor/sw-register.js" defer></script>` from [`document`]
/// so pages emit zero inline scripts under strict Content Security Policies.
pub const SW_REGISTER_JS: &str = r#"if ("serviceWorker" in navigator) { window.addEventListener("load", function() { navigator.serviceWorker.register("/sw.js").catch(function() {}); }); }"#;

/// Severity level for a one-shot [`Flash`] banner message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FlashKind {
    /// Confirmation that an action succeeded.
    Success,
    /// Neutral informational notice.
    Info,
    /// Non-fatal cautionary notice.
    Warning,
    /// Error or failure notice.
    Error,
}

/// One-shot feedback message carried across a redirect in a signed cookie.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Flash {
    /// Severity level determining how the banner is styled.
    pub kind: FlashKind,
    /// Human-readable feedback text displayed to the user.
    pub message: String,
}

impl Flash {
    /// Create a [`FlashKind::Success`] flash message.
    #[must_use]
    pub fn success(message: impl Into<String>) -> Self {
        Self {
            kind: FlashKind::Success,
            message: message.into(),
        }
    }

    /// Create a [`FlashKind::Info`] flash message.
    #[must_use]
    pub fn info(message: impl Into<String>) -> Self {
        Self {
            kind: FlashKind::Info,
            message: message.into(),
        }
    }

    /// Create a [`FlashKind::Warning`] flash message.
    #[must_use]
    pub fn warning(message: impl Into<String>) -> Self {
        Self {
            kind: FlashKind::Warning,
            message: message.into(),
        }
    }

    /// Create a [`FlashKind::Error`] flash message.
    #[must_use]
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            kind: FlashKind::Error,
            message: message.into(),
        }
    }
}

/// Returns `true` iff `path` is a safe relative application path that cannot trigger open redirects
/// or HTTP header injection.
fn is_safe_relative_path(path: &str) -> bool {
    path.starts_with('/')
        && !path.starts_with("//")
        && !path.starts_with("/\\")
        && !path.contains('\\')
        && !path.bytes().any(|b| b < 0x20 || b == 0x7f)
}

/// Emit an explicit `303 See Other` redirect to an external `http://` or `https://` URL.
///
/// Rejects non-HTTP(S) schemes (such as `javascript:`, `data:`, or relative paths) and any URL
/// containing ASCII control characters (`< 0x20` or `0x7F`).
pub fn redirect_external(url: &str) -> SlabResult<Response> {
    let trimmed = url.trim();
    if trimmed.bytes().any(|b| b < 0x20 || b == 0x7f) {
        return Err(SlabError::bad_request(
            "redirect URL must not contain control characters",
        ));
    }
    let lower = trimmed.to_ascii_lowercase();
    let is_http = (lower.starts_with("http://") && trimmed.len() > "http://".len())
        || (lower.starts_with("https://") && trimmed.len() > "https://".len());
    if !is_http {
        return Err(SlabError::bad_request(
            "external redirect URL must start with http:// or https://",
        ));
    }
    let target = HeaderValue::from_str(trimmed)
        .map_err(|_| SlabError::bad_request("invalid redirect URL header value"))?;
    let mut headers = HeaderMap::new();
    headers.insert(header::LOCATION, target.clone());
    headers.insert("hx-redirect", target);
    Ok((StatusCode::SEE_OTHER, headers).into_response())
}

/// Escape `&`, `<`, `>`, `"`, and `'` into HTML entities for manually assembled strings.
///
/// Prefer [`html!`] (`maud!` in `slabs::prelude`), which auto-escapes interpolated values at
/// compile time.
pub fn escape(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#x27;"),
            _ => out.push(ch),
        }
    }
    out
}

/// Serialize `value` as JSON safely embedded inside `<script type="application/json" id="...">`.
///
/// Escapes `<`, `>`, `&`, U+2028, and U+2029 so untrusted strings cannot break out of the
/// `<script>` tag or smuggle executable HTML/JavaScript.
pub fn json_script<T: Serialize>(id: &str, value: &T) -> SlabResult<Markup> {
    let raw = serde_json::to_string(value)
        .map_err(|e| SlabError::internal(format!("json_script serialize failed: {e}")))?;
    let mut safe = String::with_capacity(raw.len());
    for ch in raw.chars() {
        match ch {
            '<' => safe.push_str("\\u003c"),
            '>' => safe.push_str("\\u003e"),
            '&' => safe.push_str("\\u0026"),
            '\u{2028}' => safe.push_str("\\u2028"),
            '\u{2029}' => safe.push_str("\\u2029"),
            _ => safe.push(ch),
        }
    }
    Ok(html! {
        script type="application/json" id=(id) { (PreEscaped(safe)) }
    })
}

/// Standard HTMX 2 helpers for `HX-*` headers, `hx-swap-oob` fragments, and signed flash cookies.
pub mod htmx {
    use super::{
        header, html, is_safe_relative_path, Auth, Cookie, CookieJar, Deserialize, Flash,
        FlashKind, HeaderMap, HeaderValue, IntoResponse, Markup, PreEscaped, Response, SameSite,
        Serialize, StatusCode, Utc, FLASH_COOKIE_NAME, URL_SAFE_NO_PAD,
    };
    use base64::Engine as _;

    #[derive(Serialize, Deserialize)]
    struct FlashEnvelope {
        kind: FlashKind,
        message: String,
        exp: i64,
    }

    fn sanitize_dom_id(target_id: &str) -> String {
        let clean: String = target_id
            .trim_start_matches('#')
            .chars()
            .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
            .collect();
        if clean.is_empty() {
            "oob".to_string()
        } else {
            clean
        }
    }

    fn sanitize_swap(swap: &str) -> &'static str {
        match swap {
            "innerHTML" => "innerHTML",
            "beforebegin" => "beforebegin",
            "afterbegin" => "afterbegin",
            "beforeend" => "beforeend",
            "afterend" => "afterend",
            "delete" => "delete",
            "none" => "none",
            _ => "outerHTML",
        }
    }

    /// Store a signed, 60-second expiring one-shot [`Flash`] message in the `slabs_flash` cookie
    /// (`HttpOnly`, `SameSite=Lax`, `Path=/`, `Max-Age=60`).
    #[must_use = "return the updated CookieJar in your response so the flash cookie is sent"]
    pub fn set_flash(auth: &Auth, jar: CookieJar, flash: &Flash) -> CookieJar {
        let envelope = FlashEnvelope {
            kind: flash.kind,
            message: flash.message.clone(),
            exp: Utc::now().timestamp() + 60,
        };
        let Ok(json) = serde_json::to_vec(&envelope) else {
            return jar;
        };
        let encoded = URL_SAFE_NO_PAD.encode(json);
        let sig = auth.sign_with_domain("flash:v1", &encoded);
        let cookie = Cookie::build((FLASH_COOKIE_NAME, format!("{encoded}.{sig}")))
            .path("/")
            .http_only(true)
            .same_site(SameSite::Lax)
            .secure(auth.cookie_secure())
            .max_age(time::Duration::seconds(60))
            .build();
        jar.add(cookie)
    }

    /// Read and verify the signed `slabs_flash` cookie, removing it from `jar` if present.
    ///
    /// Returns `(jar, None)` when the cookie is absent, malformed, expired, or fails domain-separated
    /// HMAC verification.
    #[must_use = "return the updated CookieJar in your response so the flash cookie is cleared"]
    pub fn take_flash(auth: &Auth, jar: CookieJar) -> (CookieJar, Option<Flash>) {
        let Some(raw) = jar.get(FLASH_COOKIE_NAME).map(|c| c.value().to_string()) else {
            return (jar, None);
        };

        let removal = Cookie::build((FLASH_COOKIE_NAME, ""))
            .path("/")
            .http_only(true)
            .same_site(SameSite::Lax)
            .secure(auth.cookie_secure())
            .build();
        let jar = jar.remove(removal);

        let flash = decode_flash(auth, &raw);
        (jar, flash)
    }

    /// Set a signed [`Flash`] cookie and return `303 See Other` with both `Location` and `HX-Redirect`.
    ///
    /// Works identically for standard browser form posts and HTMX requests. Falls back to `"/"`
    /// if `location` is not a safe relative path (blocking open redirects such as `//evil.com`).
    pub fn flash_redirect(auth: &Auth, jar: CookieJar, location: &str, flash: &Flash) -> Response {
        let jar = set_flash(auth, jar, flash);
        let safe_location = if is_safe_relative_path(location) {
            location
        } else {
            "/"
        };
        let target =
            HeaderValue::from_str(safe_location).unwrap_or_else(|_| HeaderValue::from_static("/"));
        let mut headers = HeaderMap::new();
        headers.insert(header::LOCATION, target.clone());
        headers.insert("hx-redirect", target);
        (StatusCode::SEE_OTHER, jar, headers).into_response()
    }

    fn decode_flash(auth: &Auth, raw: &str) -> Option<Flash> {
        let (encoded, sig) = raw.split_once('.')?;
        if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
            return None;
        }
        if !auth.verify_with_domain("flash:v1", encoded, sig) {
            return None;
        }
        let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?;
        let envelope: FlashEnvelope = serde_json::from_slice(&bytes).ok()?;
        if envelope.exp < Utc::now().timestamp() {
            return None;
        }
        Some(Flash {
            kind: envelope.kind,
            message: envelope.message,
        })
    }

    /// Return a `200 OK` response with `HX-Redirect` so HTMX performs a full navigation.
    ///
    /// Falls back to `"/"` if `path` is not a safe relative path (blocking open redirects).
    pub fn redirect(path: &str) -> Response {
        let safe_path = if is_safe_relative_path(path) {
            path
        } else {
            "/"
        };
        let mut headers = HeaderMap::new();
        headers.insert(
            "hx-redirect",
            HeaderValue::from_str(safe_path).unwrap_or_else(|_| HeaderValue::from_static("/")),
        );
        (StatusCode::OK, headers).into_response()
    }

    /// Return a `200 OK` HTML fragment with an `HX-Trigger` client event header.
    pub fn with_trigger(markup: Markup, event: &str) -> Response {
        let mut headers = HeaderMap::new();
        if let Ok(val) = HeaderValue::from_str(event) {
            headers.insert("hx-trigger", val);
        }
        (StatusCode::OK, headers, markup).into_response()
    }

    /// Wrap `inner` in an HTMX out-of-band swap container (`hx-swap-oob`).
    ///
    /// Sanitizes `target_id` to `[A-Za-z0-9_-]` (falling back to `"oob"`) and validates `swap`
    /// against the HTMX swap allowlist (`innerHTML`, `outerHTML`, `beforebegin`, `afterbegin`,
    /// `beforeend`, `afterend`, `delete`, `none`; defaulting to `"outerHTML"`).
    pub fn oob(target_id: &str, swap: &str, inner: Markup) -> Markup {
        let clean_id = sanitize_dom_id(target_id);
        let safe_swap = sanitize_swap(swap);
        let attr = format!("{safe_swap}:#{clean_id}");
        html! {
            div hx-swap-oob=(attr) { (PreEscaped(inner.into_string())) }
        }
    }

    /// Emit an HTMX out-of-band delete instruction (`hx-swap-oob="delete"`) for `target_id`.
    ///
    /// Sanitizes `target_id` to `[A-Za-z0-9_-]` (falling back to `"oob"`).
    pub fn oob_delete(target_id: &str) -> Markup {
        let clean_id = sanitize_dom_id(target_id);
        html! {
            div id=(clean_id) hx-swap-oob="delete" {}
        }
    }

    /// Emit an HTMX out-of-band `outerHTML` swap targeting `target_id`.
    ///
    /// Sanitizes `target_id` to `[A-Za-z0-9_-]` (falling back to `"oob"`).
    pub fn oob_replace(target_id: &str, inner: Markup) -> Markup {
        let clean_id = sanitize_dom_id(target_id);
        html! {
            div hx-swap-oob=(format!("outerHTML:#{clean_id}")) { (PreEscaped(inner.into_string())) }
        }
    }

    /// Return `true` when the request carries `HX-Request: true`.
    pub fn is_htmx(headers: &HeaderMap) -> bool {
        headers
            .get("hx-request")
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v == "true")
    }

    /// Return `true` when the `Accept` header contains `application/json`.
    pub fn wants_json(headers: &HeaderMap) -> bool {
        headers
            .get(header::ACCEPT)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.contains("application/json"))
    }
}

/// Render a Basecoat alert banner for an optional [`Flash`] message.
///
/// Renders a `<div class="alert" role="status">` when `flash` is `Some`, applying
/// `data-variant="destructive"` for [`FlashKind::Error`], or empty [`Markup`] when `None`.
#[must_use]
pub fn flash_banner(flash: Option<&Flash>) -> Markup {
    let Some(flash) = flash else {
        return html! {};
    };
    let (kind_str, variant) = match flash.kind {
        FlashKind::Success => ("success", None),
        FlashKind::Info => ("info", None),
        FlashKind::Warning => ("warning", None),
        FlashKind::Error => ("error", Some("destructive")),
    };
    html! {
        div class="alert" role="status" data-flash-kind=(kind_str) data-variant=[variant] {
            section {
                p { (flash.message) }
            }
        }
    }
}

/// Render a complete, CSP-friendly HTML5 page around `body` using compile-time [`Markup`].
///
/// Emits zero inline `<style>` or inline `<script>` elements. Loads PWA manifest and theme
/// metadata, Basecoat UI (`/_slabs/vendor/basecoat.min.css`, which includes
/// `@view-transition { navigation: auto; }`, and `/_slabs/vendor/basecoat.min.js`), HTMX 2 with
/// SSE and Idiomorph (`hx-ext="morph"` on `<body>`), Alpine.js 3 (`/_slabs/vendor/alpine.min.js`),
/// and external service-worker registration (`/_slabs/vendor/sw-register.js`). Pass app-compiled
/// Tailwind CSS v4 URLs in `stylesheets` (such as `&ctx.assets.stylesheet_urls()`) and ES module
/// URLs in `scripts`.
pub fn document(title: &str, stylesheets: &[String], scripts: &[String], body: Markup) -> Markup {
    html! {
        (DOCTYPE)
        html lang="en" class="dark" {
            head {
                meta charset="utf-8";
                meta name="viewport" content="width=device-width, initial-scale=1";
                link rel="manifest" href="/manifest.webmanifest";
                meta name="theme-color" content="#1a1b26";
                meta name="apple-mobile-web-app-capable" content="yes";
                title { (title) }
                link rel="stylesheet" href="/_slabs/vendor/basecoat.min.css";
                @for href in stylesheets {
                    link rel="stylesheet" href=(href);
                }
                script src="/_slabs/vendor/htmx.min.js" defer {}
                script src="/_slabs/vendor/htmx-ext-sse.js" defer {}
                script src="/_slabs/vendor/idiomorph-ext.min.js" defer {}
                script src="/_slabs/vendor/basecoat.min.js" defer {}
                script src="/_slabs/vendor/alpine.min.js" defer {}
                @for src in scripts {
                    script type="module" src=(src) defer {}
                }
            }
            body class="min-h-screen bg-background text-foreground antialiased" hx-ext="morph" {
                (PreEscaped(body.into_string()))
                script src="/_slabs/vendor/sw-register.js" defer {}
            }
        }
    }
}

/// Generate a domain-separated, expiring HMAC-signed CSRF token bound to `scope`.
///
/// Uses 16 cryptographically random bytes (`OsRng`, 32 lowercase hex chars), embeds a 4-hour
/// Unix timestamp expiration, and signs `"{scope}\0{exp}\0{nonce}"` under domain `"csrf:v1"`.
/// Returns `"{exp}.{nonce}.{sig}"`.
pub fn csrf_token(auth: &Auth, scope: &str) -> String {
    let mut nonce_bytes = [0u8; 16];
    OsRng.fill_bytes(&mut nonce_bytes);
    let nonce = hex::encode(nonce_bytes);
    let exp = Utc::now().timestamp() + 4 * 3600;
    let payload = format!("{scope}\0{exp}\0{nonce}");
    let sig = auth.sign_with_domain("csrf:v1", &payload);
    format!("{exp}.{nonce}.{sig}")
}

/// Verify a submitted CSRF token against `scope`.
///
/// Returns a `403 Forbidden` [`SlabError`] if the token format, nonce, expiration, or
/// domain-separated HMAC signature is invalid.
pub fn verify_csrf(auth: &Auth, scope: &str, token: &str) -> SlabResult<()> {
    let mut parts = token.split('.');
    let (Some(exp_str), Some(nonce), Some(sig), None) =
        (parts.next(), parts.next(), parts.next(), parts.next())
    else {
        return Err(SlabError::forbidden("invalid csrf token format"));
    };
    if nonce.len() != 32 || !nonce.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(SlabError::forbidden("invalid csrf token format"));
    }
    let exp: i64 = exp_str
        .parse()
        .map_err(|_| SlabError::forbidden("invalid csrf token format"))?;
    if Utc::now().timestamp() > exp {
        return Err(SlabError::forbidden("csrf token expired"));
    }
    let payload = format!("{scope}\0{exp}\0{nonce}");
    if auth.verify_with_domain("csrf:v1", &payload, sig) {
        Ok(())
    } else {
        Err(SlabError::forbidden("csrf token verification failed"))
    }
}

/// Render untrusted `CommonMark` and GitHub-flavored Markdown into safe [`Markup`].
///
/// Enables tables, strikethrough, and task lists. Heading attributes are explicitly disabled to
/// prevent Alpine/HTMX attribute injection (`x-init`, `x-data`, `hx-*`). Drops raw HTML blocks
/// and inline HTML tags so untrusted authors cannot inject `<script>` or event handlers. Rewrites
/// unsafe link or image URLs (disallowed schemes such as `javascript:`, `vbscript:`, `data:`,
/// protocol-relative `//` or `/\`, or URLs with ASCII control characters) to `"#"`, and adds
/// `rel="noopener noreferrer ugc"` to every rendered `<a>` link.
pub fn render_markdown(input: &str) -> Markup {
    use pulldown_cmark::{Event, LinkType, Options, Parser, Tag, TagEnd};

    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);

    let parser = Parser::new_ext(input, options).filter_map(|event| match event {
        Event::Html(_) | Event::InlineHtml(_) => None,
        Event::Start(Tag::Link {
            link_type,
            dest_url,
            title,
            ..
        }) => {
            let candidate = if link_type == LinkType::Email
                && !dest_url.trim().to_ascii_lowercase().starts_with("mailto:")
            {
                format!("mailto:{}", dest_url.trim())
            } else {
                dest_url.to_string()
            };
            let href = escape(&sanitize_url(&candidate));
            let open_tag = if title.is_empty() {
                format!("<a href=\"{href}\" rel=\"noopener noreferrer ugc\">")
            } else {
                format!(
                    "<a href=\"{href}\" title=\"{}\" rel=\"noopener noreferrer ugc\">",
                    escape(&title)
                )
            };
            Some(Event::Html(open_tag.into()))
        }
        Event::End(TagEnd::Link) => Some(Event::Html("</a>".into())),
        Event::Start(Tag::Image {
            link_type,
            dest_url,
            title,
            id,
        }) => Some(Event::Start(Tag::Image {
            link_type,
            dest_url: sanitize_url(&dest_url).into(),
            title,
            id,
        })),
        other => Some(other),
    });

    let mut html_out = String::with_capacity(input.len() + 64);
    pulldown_cmark::html::push_html(&mut html_out, parser);
    PreEscaped(html_out)
}

fn sanitize_url(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty()
        || trimmed.bytes().any(|b| b <= 0x1f || b == 0x7f)
        || trimmed.starts_with("//")
        || trimmed.starts_with("/\\")
    {
        return "#".to_string();
    }
    let lower = trimmed.to_ascii_lowercase();
    if lower.starts_with("http://")
        || lower.starts_with("https://")
        || lower.starts_with("mailto:")
        || lower.starts_with('/')
        || lower.starts_with('#')
        || !lower.contains(':')
    {
        trimmed.to_string()
    } else {
        "#".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn render_markdown_renders_gfm_adds_rel_and_blocks_xss_and_heading_attrs() {
        let md = "# Title\n\n# Hi {x-init=alert(1)}\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)) and [proto](//evil.com) and [slash](/\\evil.com) and [ctrl](java&#x09;script:alert(1))\n\n| A | B |\n| - | - |\n| 1 | 2 |\n";
        let rendered = render_markdown(md).into_string();
        assert!(rendered.contains("<h1>Title</h1>"));
        assert!(rendered.contains("<h1>Hi {x-init=alert(1)}</h1>"));
        assert!(!rendered.contains("<h1 "));
        assert!(rendered.contains("<table>"));
        assert!(rendered
            .contains("<a href=\"https://example.com\" rel=\"noopener noreferrer ugc\">ok</a>"));
        assert!(!rendered.contains("<script>"));
        assert!(!rendered.contains("hx-get"));
        assert!(!rendered.contains("x-init=\"pwn()\""));
        assert!(!rendered.contains("javascript:"));
        assert!(!rendered.contains("href=\"//evil.com\""));
        assert!(!rendered.contains("href=\"/\\evil.com\""));
        assert!(!rendered.contains("java\tscript:"));
        assert_eq!(sanitize_url("https://example.com/\x01bad"), "#");
        assert_eq!(sanitize_url("https://example.com/\x7fbad"), "#");
    }

    #[test]
    fn render_markdown_heading_attributes_disabled_no_x_init_attr() {
        let rendered = render_markdown("# Hi {x-init=alert(1)}").into_string();
        assert!(rendered.contains("<h1>Hi {x-init=alert(1)}</h1>"));
        assert!(!rendered.contains("<h1 "));
    }

    #[test]
    fn safe_redirects_block_open_redirects_and_allow_relative_paths() {
        let auth = Auth::for_signing("test-redirect-secret-key", false);
        for unsafe_target in [
            "https://evil.com",
            "//evil.com",
            "/\\evil.com",
            "/foo\\bar",
            "/ok\r\nSet-Cookie: a=b",
            "relative/path",
        ] {
            let r1 = htmx::redirect(unsafe_target);
            assert_eq!(
                r1.headers()
                    .get("hx-redirect")
                    .and_then(|v| v.to_str().ok()),
                Some("/"),
                "redirect should reject {unsafe_target:?}"
            );

            let r2 =
                htmx::flash_redirect(&auth, CookieJar::new(), unsafe_target, &Flash::info("hi"));
            assert_eq!(
                r2.headers()
                    .get(header::LOCATION)
                    .and_then(|v| v.to_str().ok()),
                Some("/"),
                "flash_redirect should reject {unsafe_target:?}"
            );
        }

        let ok = htmx::redirect("/rooms/42?tab=chat");
        assert_eq!(
            ok.headers()
                .get("hx-redirect")
                .and_then(|v| v.to_str().ok()),
            Some("/rooms/42?tab=chat")
        );
    }

    #[test]
    fn redirect_external_allows_http_https_only() {
        let ok = redirect_external("https://example.com/callback?ok=1").unwrap();
        assert_eq!(ok.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            ok.headers()
                .get(header::LOCATION)
                .and_then(|v| v.to_str().ok()),
            Some("https://example.com/callback?ok=1")
        );

        assert!(redirect_external("javascript:alert(1)").is_err());
        assert!(redirect_external("/relative").is_err());
        assert!(redirect_external("https://example.com/\r\nbad").is_err());
        assert!(redirect_external("https://").is_err());
    }

    #[test]
    fn csrf_token_roundtrip_and_expiration_and_tamper_rejection() {
        let auth = Auth::for_signing("test-csrf-secret-key", false);
        let token = csrf_token(&auth, "ses_123");
        let parts: Vec<&str> = token.split('.').collect();
        assert_eq!(parts.len(), 3);
        assert_eq!(parts[1].len(), 32);

        verify_csrf(&auth, "ses_123", &token).expect("valid csrf token");
        assert!(verify_csrf(&auth, "ses_other", &token).is_err());
        assert!(verify_csrf(&auth, "ses_123", "not-a-valid-token").is_err());

        // Expired token signed with valid domain key must be rejected
        let expired_exp = Utc::now().timestamp() - 10;
        let nonce = "0123456789abcdef0123456789abcdef";
        let sig = auth.sign_with_domain("csrf:v1", &format!("ses_123\0{expired_exp}\0{nonce}"));
        let expired = format!("{expired_exp}.{nonce}.{sig}");
        assert!(verify_csrf(&auth, "ses_123", &expired).is_err());
    }

    #[test]
    fn flash_roundtrip_max_age_and_expiration() {
        use base64::Engine as _;

        let auth = Auth::for_signing("test-flash-secret-key", false);
        let flash = Flash::success("Saved changes.");

        let jar = htmx::set_flash(&auth, CookieJar::new(), &flash);
        let cookie = jar.get(FLASH_COOKIE_NAME).expect("flash cookie set");
        assert_eq!(cookie.path(), Some("/"));
        assert_eq!(cookie.http_only(), Some(true));
        assert_eq!(cookie.same_site(), Some(SameSite::Lax));
        assert_eq!(cookie.max_age(), Some(time::Duration::seconds(60)));

        let (jar, taken) = htmx::take_flash(&auth, jar);
        assert_eq!(taken, Some(flash));
        assert!(jar.get(FLASH_COOKIE_NAME).is_none());

        let (_jar, second) = htmx::take_flash(&auth, jar);
        assert_eq!(second, None);

        // Expired flash cookie must be rejected
        let expired_json = serde_json::json!({
            "kind": "info",
            "message": "stale",
            "exp": Utc::now().timestamp() - 5,
        });
        let encoded = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&expired_json).unwrap());
        let sig = auth.sign_with_domain("flash:v1", &encoded);
        let mut headers = HeaderMap::new();
        headers.insert(
            header::COOKIE,
            HeaderValue::from_str(&format!("{FLASH_COOKIE_NAME}={encoded}.{sig}")).unwrap(),
        );
        let expired_jar = CookieJar::from_headers(&headers);
        let (_cleared, result) = htmx::take_flash(&auth, expired_jar);
        assert_eq!(result, None);
    }

    #[test]
    fn flash_rejects_tampered_cookie_and_clears_it() {
        let auth = Auth::for_signing("test-flash-secret-key", false);
        let jar = htmx::set_flash(&auth, CookieJar::new(), &Flash::info("Hello"));
        let raw = jar.get(FLASH_COOKIE_NAME).unwrap().value().to_string();
        let (encoded, sig) = raw.split_once('.').unwrap();
        let flipped = if sig.starts_with('0') { '1' } else { '0' };
        let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);

        let mut tampered_headers = HeaderMap::new();
        tampered_headers.insert(
            header::COOKIE,
            HeaderValue::from_str(&format!("{FLASH_COOKIE_NAME}={tampered}")).unwrap(),
        );
        let tampered_jar = CookieJar::from_headers(&tampered_headers);

        let (cleared_jar, taken) = htmx::take_flash(&auth, tampered_jar);
        assert_eq!(taken, None);
        assert!(cleared_jar.get(FLASH_COOKIE_NAME).is_none());
    }

    #[test]
    fn flash_redirect_sets_see_other_location_hx_redirect_and_cookie() {
        let auth = Auth::for_signing("test-flash-secret-key", false);
        let resp = htmx::flash_redirect(
            &auth,
            CookieJar::new(),
            "/rooms",
            &Flash::warning("Room archived"),
        );

        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            resp.headers()
                .get(header::LOCATION)
                .and_then(|v| v.to_str().ok()),
            Some("/rooms")
        );
        assert_eq!(
            resp.headers()
                .get("hx-redirect")
                .and_then(|v| v.to_str().ok()),
            Some("/rooms")
        );
        let set_cookie = resp
            .headers()
            .get(header::SET_COOKIE)
            .and_then(|v| v.to_str().ok())
            .expect("Set-Cookie header present");
        assert!(set_cookie.contains("slabs_flash="));
        assert!(set_cookie.contains("HttpOnly"));
        assert!(set_cookie.contains("SameSite=Lax"));
        assert!(set_cookie.contains("Path=/"));
        assert!(set_cookie.contains("Max-Age=60"));
    }

    #[test]
    fn oob_sanitizes_id_and_swap_strategy() {
        let rendered =
            htmx::oob("#list\" onclick=\"x", "evilSwap", html! { p { "ok" } }).into_string();
        assert!(rendered.contains("hx-swap-oob=\"outerHTML:#listonclickx\""));

        let empty_id = htmx::oob_replace("!!!", html! { p { "ok" } }).into_string();
        assert!(empty_id.contains("hx-swap-oob=\"outerHTML:#oob\""));

        let valid_swap =
            htmx::oob("messages_1-a", "beforeend", html! { li { "hi" } }).into_string();
        assert!(valid_swap.contains("hx-swap-oob=\"beforeend:#messages_1-a\""));
    }

    #[test]
    fn flash_banner_renders_accessible_alert_or_empty() {
        assert_eq!(flash_banner(None).into_string(), "");

        let ok_html = flash_banner(Some(&Flash::success("Item <saved>"))).into_string();
        assert!(ok_html.contains("class=\"alert\""));
        assert!(ok_html.contains("role=\"status\""));
        assert!(ok_html.contains("data-flash-kind=\"success\""));
        assert!(ok_html.contains("Item &lt;saved&gt;"));
        assert!(!ok_html.contains("data-variant=\"destructive\""));

        let err_html = flash_banner(Some(&Flash::error("Failed"))).into_string();
        assert!(err_html.contains("role=\"status\""));
        assert!(err_html.contains("data-flash-kind=\"error\""));
        assert!(err_html.contains("data-variant=\"destructive\""));
        assert!(err_html.contains("Failed"));
    }

    #[test]
    fn document_is_csp_friendly_with_zero_inline_scripts_or_styles() {
        let rendered = document("Campfire", &[], &[], html! { main { "Hi" } }).into_string();
        assert!(rendered.contains("<link rel=\"manifest\" href=\"/manifest.webmanifest\">"));
        assert!(rendered.contains("<meta name=\"theme-color\" content=\"#1a1b26\">"));
        assert!(rendered.contains("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">"));
        assert!(rendered.contains("<script src=\"/_slabs/vendor/sw-register.js\" defer></script>"));
        assert!(!rendered.contains("<style"));
        assert!(!rendered.contains("<script>"));
    }

    #[test]
    fn json_script_escapes_script_breakout_and_line_separators() {
        let payload = serde_json::json!({
            "html": "</script><img src=x>&",
            "sep": "a\u{2028}b\u{2029}c",
        });
        let rendered = json_script("boot-data", &payload).unwrap().into_string();
        assert!(rendered.starts_with("<script type=\"application/json\" id=\"boot-data\">"));
        assert!(rendered.ends_with("</script>"));
        assert!(!rendered.contains("</script><img"));
        assert!(rendered.contains("\\u003c/script\\u003e\\u003cimg src=x\\u003e\\u0026"));
        assert!(rendered.contains("\\u2028"));
        assert!(rendered.contains("\\u2029"));
    }
}