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, CSP-friendly HTML5 page with zero inline `<style>` or inline
9//! `<script>` elements. Native view transitions (`@view-transition { navigation: auto; }`) ship
10//! inside `/_slabs/vendor/basecoat.min.css`, and service-worker registration loads externally via
11//! `/_slabs/vendor/sw-register.js` alongside Basecoat UI, HTMX 2 (with SSE and Idiomorph
12//! `hx-ext="morph"` on `<body>`), and Alpine.js 3.
13//! Pass app-compiled Tailwind CSS v4 stylesheets (for example `&ctx.assets.stylesheet_urls()`) and
14//! module scripts via the `stylesheets` and `scripts` arguments.
15//! All frontend assets are self-hosted with zero CDN or Node runtime requirement.
16//!
17//! # HTMX helpers
18//!
19//! The [`htmx`] module emits standard `HX-*` headers and `hx-swap-oob` fragments:
20//!
21//! - [`htmx::redirect`] triggers a full same-origin navigation via `HX-Redirect` (sanitized against open redirects).
22//! - [`redirect_external`] emits an explicit `303 See Other` redirect to an `http://` or `https://` URL.
23//! - [`htmx::with_trigger`] attaches an `HX-Trigger` client event header to a fragment.
24//! - [`htmx::oob`], [`htmx::oob_replace`], and [`htmx::oob_delete`] wrap sanitized out-of-band DOM swaps.
25//! - [`htmx::is_htmx`] and [`htmx::wants_json`] inspect `HX-Request` and `Accept` headers.
26//!
27//! # CSRF protection
28//!
29//! Use [`csrf_token`] to mint a domain-separated, expiring HMAC-signed token bound to a session
30//! scope and [`verify_csrf`] to verify submitted tokens.
31//!
32//! # Usage
33//!
34//! ```rust,no_run
35//! use axum::http::HeaderMap;
36//! use axum::response::IntoResponse;
37//! use slabs_html::{document, html, htmx};
38//!
39//! fn render_notice(headers: &HeaderMap, styles: &[String]) -> axum::response::Response {
40//!     let fragment = html! {
41//!         p id="notice" { "Saved." }
42//!     };
43//!
44//!     if htmx::is_htmx(headers) {
45//!         return htmx::oob_replace("notice", fragment).into_response();
46//!     }
47//!
48//!     document("Notice", styles, &[], fragment).into_response()
49//! }
50//! ```
51
52use axum::response::{IntoResponse, Response};
53use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
54use base64::engine::general_purpose::URL_SAFE_NO_PAD;
55use chrono::Utc;
56use http::{header, HeaderMap, HeaderValue, StatusCode};
57use rand_core::{OsRng, RngCore};
58use serde::{Deserialize, Serialize};
59use slabs_auth::Auth;
60use slabs_core::{SlabError, SlabResult};
61
62pub use maud::{html, Markup, PreEscaped, Render, DOCTYPE};
63
64/// Cookie name used to store one-shot signed flash messages.
65pub const FLASH_COOKIE_NAME: &str = "slabs_flash";
66
67/// External service-worker registration script served at `/_slabs/vendor/sw-register.js`.
68///
69/// Referenced via `<script src="/_slabs/vendor/sw-register.js" defer></script>` from [`document`]
70/// so pages emit zero inline scripts under strict Content Security Policies.
71pub const SW_REGISTER_JS: &str = r#"if ("serviceWorker" in navigator) { window.addEventListener("load", function() { navigator.serviceWorker.register("/sw.js").catch(function() {}); }); }"#;
72
73/// External bug-reporter script served at `/_slabs/vendor/slabs-bug-report.js`.
74///
75/// Referenced via `<script src="/_slabs/vendor/slabs-bug-report.js" defer></script>` from
76/// [`bug_report_widget`] and [`bug_report_widget_with_label`] so pages emit zero inline scripts
77/// under strict Content Security Policies.
78pub const BUG_REPORT_JS: &str = r##"(function () {
79  if (typeof window === "undefined" || window.__slabsBugReporterInstalled) return;
80  window.__slabsBugReporterInstalled = true;
81
82  var MAX_ERRORS = 10;
83  var MAX_ATTACHMENTS = 3;
84  var recentErrors = [];
85
86  function pushError(kind, message, detail) {
87    recentErrors.push({
88      kind: String(kind || "error").slice(0, 64),
89      message: String(message || "error").slice(0, 512),
90      detail: detail ? String(detail).slice(0, 512) : null,
91      at: new Date().toISOString()
92    });
93    if (recentErrors.length > MAX_ERRORS) {
94      recentErrors.shift();
95    }
96  }
97
98  window.addEventListener("error", function (e) {
99    var loc = e.filename ? e.filename + ":" + e.lineno + ":" + e.colno : null;
100    pushError("onerror", e.message || "Script error", loc);
101  });
102
103  window.addEventListener("unhandledrejection", function (e) {
104    var r = e.reason;
105    pushError(
106      "unhandledrejection",
107      (r && r.message) || String(r || "Unhandled promise rejection"),
108      r && r.stack
109    );
110  });
111
112  ["htmx:targetError", "htmx:swapError", "htmx:responseError"].forEach(function (ev) {
113    document.addEventListener(ev, function (e) {
114      var d = e.detail || {};
115      var msg = d.error || (d.xhr ? "HTTP " + d.xhr.status : ev);
116      var target = d.target && d.target.id ? "#" + d.target.id : null;
117      pushError(ev, msg, target);
118    });
119  });
120
121  function findDialog() {
122    return document.querySelector('dialog[data-slabs-bug-reporter="true"]');
123  }
124
125  function openDialog(dialog) {
126    if (!dialog) return;
127    var statusEl = dialog.querySelector('[data-slabs-bug-status="true"]');
128    if (statusEl) statusEl.textContent = "";
129    if (typeof dialog.showModal === "function") {
130      if (!dialog.open) dialog.showModal();
131    } else {
132      dialog.setAttribute("open", "");
133    }
134  }
135
136  function closeDialog(dialog) {
137    if (!dialog) return;
138    if (typeof dialog.close === "function") {
139      if (dialog.open) dialog.close();
140    } else {
141      dialog.removeAttribute("open");
142    }
143  }
144
145  function nextFrame() {
146    return new Promise(function (resolve) {
147      if (typeof window.requestAnimationFrame === "function") {
148        window.requestAnimationFrame(function () { resolve(); });
149      } else {
150        setTimeout(resolve, 16);
151      }
152    });
153  }
154
155  function captureViewportScreenshot(dialog) {
156    return new Promise(function (resolve) {
157      var reporterNodes = Array.prototype.slice.call(
158        document.querySelectorAll("[data-slabs-bug-reporter]")
159      );
160      var prevHidden = reporterNodes.map(function (el) { return el.hidden; });
161      var wasOpen = Boolean(dialog && dialog.open);
162
163      function restoreUi() {
164        reporterNodes.forEach(function (el, idx) {
165          el.hidden = prevHidden[idx];
166        });
167        if (wasOpen) {
168          openDialog(dialog);
169        }
170      }
171
172      try {
173        closeDialog(dialog);
174        reporterNodes.forEach(function (el) { el.hidden = true; });
175      } catch (_) {
176        restoreUi();
177        resolve(null);
178        return;
179      }
180
181      nextFrame().then(function () {
182        var settled = false;
183        function finish(blob) {
184          if (settled) return;
185          settled = true;
186          restoreUi();
187          resolve(blob);
188        }
189
190        var timer = setTimeout(function () { finish(null); }, 2500);
191        try {
192          var width = Math.min(Math.max(window.innerWidth || 1280, 320), 1920);
193          var height = Math.min(Math.max(window.innerHeight || 720, 240), 1080);
194          var clone = document.documentElement.cloneNode(true);
195          var toStrip = clone.querySelectorAll("[data-slabs-bug-reporter], script");
196          for (var i = 0; i < toStrip.length; i++) {
197            if (toStrip[i].parentNode) {
198              toStrip[i].parentNode.removeChild(toStrip[i]);
199            }
200          }
201          clone.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
202          var xhtml = new XMLSerializer().serializeToString(clone);
203          var svg =
204            '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' +
205            '<foreignObject width="100%" height="100%">' + xhtml + "</foreignObject>" +
206            "</svg>";
207
208          var img = new Image();
209          img.onload = function () {
210            try {
211              var canvas = document.createElement("canvas");
212              canvas.width = width;
213              canvas.height = height;
214              var ctx = canvas.getContext("2d");
215              if (!ctx) {
216                clearTimeout(timer);
217                finish(null);
218                return;
219              }
220              ctx.drawImage(img, 0, 0, width, height);
221              canvas.toBlob(function (blob) {
222                clearTimeout(timer);
223                finish(blob || null);
224              }, "image/png");
225            } catch (_) {
226              clearTimeout(timer);
227              finish(null);
228            }
229          };
230          img.onerror = function () {
231            clearTimeout(timer);
232            finish(null);
233          };
234          img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
235        } catch (_) {
236          clearTimeout(timer);
237          finish(null);
238        }
239      });
240    });
241  }
242
243  document.addEventListener("click", function (e) {
244    var target = e.target;
245    if (!target || typeof target.closest !== "function") return;
246    if (target.closest('[data-slabs-bug-open="true"]')) {
247      openDialog(findDialog());
248      return;
249    }
250    if (target.closest('[data-slabs-bug-close="true"]')) {
251      closeDialog(findDialog());
252    }
253  });
254
255  document.addEventListener("submit", function (e) {
256    var form = e.target;
257    if (!form || !form.matches || !form.matches('form[data-slabs-bug-form="true"]')) return;
258    e.preventDefault();
259
260    var dialog = form.closest('dialog[data-slabs-bug-reporter="true"]') || findDialog();
261    var statusEl = form.querySelector('[data-slabs-bug-status="true"]');
262    var submitBtn = form.querySelector('[data-slabs-bug-submit="true"]');
263    var descEl = form.querySelector('textarea[name="description"]');
264    var sourceEl = form.querySelector('input[name="source_file"]');
265    var csrfEl = form.querySelector('input[name="csrf_token"]');
266    var includeShotEl = form.querySelector('input[name="include_screenshot"]');
267    var filesEl = form.querySelector('input[name="attachments"]');
268
269    var description = descEl ? descEl.value.trim() : "";
270    if (description.length < 3) {
271      if (statusEl) statusEl.textContent = "Please enter at least 3 characters describing the issue.";
272      return;
273    }
274
275    if (submitBtn) submitBtn.disabled = true;
276    if (statusEl) statusEl.textContent = "Preparing report...";
277
278    var metadata = {
279      url_path: window.location ? window.location.pathname : "/",
280      viewport: (window.innerWidth || 0) + "x" + (window.innerHeight || 0),
281      device_pixel_ratio: window.devicePixelRatio || 1,
282      user_agent: (navigator && navigator.userAgent) ? String(navigator.userAgent).slice(0, 256) : "",
283      color_scheme:
284        window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches
285          ? "dark"
286          : "light",
287      online: navigator && typeof navigator.onLine === "boolean" ? navigator.onLine : true,
288      recent_errors: recentErrors.slice()
289    };
290
291    var shotPromise =
292      includeShotEl && includeShotEl.checked
293        ? captureViewportScreenshot(dialog)
294        : Promise.resolve(null);
295
296    shotPromise
297      .then(function (screenshotBlob) {
298        if (statusEl) statusEl.textContent = "Submitting bug report...";
299        var fd = new FormData();
300        fd.append("description", description);
301        if (sourceEl && sourceEl.value) {
302          fd.append("source_file", sourceEl.value);
303        }
304        if (csrfEl && csrfEl.value) {
305          fd.append("csrf_token", csrfEl.value);
306        }
307        fd.append("metadata_json", JSON.stringify(metadata));
308        if (screenshotBlob) {
309          fd.append("screenshot", screenshotBlob, "screenshot.png");
310        }
311        if (filesEl && filesEl.files) {
312          var count = Math.min(filesEl.files.length, MAX_ATTACHMENTS);
313          for (var i = 0; i < count; i++) {
314            fd.append("attachments", filesEl.files[i], filesEl.files[i].name || "attachment.bin");
315          }
316        }
317
318        return fetch("/_slabs/bug-reports", {
319          method: "POST",
320          body: fd,
321          credentials: "same-origin"
322        });
323      })
324      .then(function (resp) {
325        return resp.json().catch(function () { return {}; }).then(function (data) {
326          if (!resp.ok) {
327            var errMsg = (data && data.message) || ("Submission failed (HTTP " + resp.status + ")");
328            throw new Error(errMsg);
329          }
330          if (statusEl) {
331            statusEl.textContent = "Bug report submitted (" + (data.id || "recorded") + "). Thank you!";
332          }
333          if (descEl) descEl.value = "";
334          if (filesEl) filesEl.value = "";
335        });
336      })
337      .catch(function (err) {
338        if (statusEl) {
339          statusEl.textContent = (err && err.message) || "Failed to submit bug report.";
340        }
341      })
342      .finally(function () {
343        if (submitBtn) submitBtn.disabled = false;
344      });
345  });
346})();
347"##;
348
349/// Severity level for a one-shot [`Flash`] banner message.
350#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
351#[serde(rename_all = "lowercase")]
352pub enum FlashKind {
353    /// Confirmation that an action succeeded.
354    Success,
355    /// Neutral informational notice.
356    Info,
357    /// Non-fatal cautionary notice.
358    Warning,
359    /// Error or failure notice.
360    Error,
361}
362
363/// One-shot feedback message carried across a redirect in a signed cookie.
364#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
365pub struct Flash {
366    /// Severity level determining how the banner is styled.
367    pub kind: FlashKind,
368    /// Human-readable feedback text displayed to the user.
369    pub message: String,
370}
371
372impl Flash {
373    /// Create a [`FlashKind::Success`] flash message.
374    #[must_use]
375    pub fn success(message: impl Into<String>) -> Self {
376        Self {
377            kind: FlashKind::Success,
378            message: message.into(),
379        }
380    }
381
382    /// Create a [`FlashKind::Info`] flash message.
383    #[must_use]
384    pub fn info(message: impl Into<String>) -> Self {
385        Self {
386            kind: FlashKind::Info,
387            message: message.into(),
388        }
389    }
390
391    /// Create a [`FlashKind::Warning`] flash message.
392    #[must_use]
393    pub fn warning(message: impl Into<String>) -> Self {
394        Self {
395            kind: FlashKind::Warning,
396            message: message.into(),
397        }
398    }
399
400    /// Create a [`FlashKind::Error`] flash message.
401    #[must_use]
402    pub fn error(message: impl Into<String>) -> Self {
403        Self {
404            kind: FlashKind::Error,
405            message: message.into(),
406        }
407    }
408}
409
410/// Returns `true` iff `path` is a safe relative application path that cannot trigger open redirects
411/// or HTTP header injection.
412fn is_safe_relative_path(path: &str) -> bool {
413    path.starts_with('/')
414        && !path.starts_with("//")
415        && !path.starts_with("/\\")
416        && !path.contains('\\')
417        && !path.bytes().any(|b| b < 0x20 || b == 0x7f)
418}
419
420/// Emit an explicit `303 See Other` redirect to an external `http://` or `https://` URL.
421///
422/// Rejects non-HTTP(S) schemes (such as `javascript:`, `data:`, or relative paths) and any URL
423/// containing ASCII control characters (`< 0x20` or `0x7F`).
424pub fn redirect_external(url: &str) -> SlabResult<Response> {
425    let trimmed = url.trim();
426    if trimmed.bytes().any(|b| b < 0x20 || b == 0x7f) {
427        return Err(SlabError::bad_request(
428            "redirect URL must not contain control characters",
429        ));
430    }
431    let lower = trimmed.to_ascii_lowercase();
432    let is_http = (lower.starts_with("http://") && trimmed.len() > "http://".len())
433        || (lower.starts_with("https://") && trimmed.len() > "https://".len());
434    if !is_http {
435        return Err(SlabError::bad_request(
436            "external redirect URL must start with http:// or https://",
437        ));
438    }
439    let target = HeaderValue::from_str(trimmed)
440        .map_err(|_| SlabError::bad_request("invalid redirect URL header value"))?;
441    let mut headers = HeaderMap::new();
442    headers.insert(header::LOCATION, target.clone());
443    headers.insert("hx-redirect", target);
444    Ok((StatusCode::SEE_OTHER, headers).into_response())
445}
446
447/// Escape `&`, `<`, `>`, `"`, and `'` into HTML entities for manually assembled strings.
448///
449/// Prefer [`html!`] (`maud!` in `slabs::prelude`), which auto-escapes interpolated values at
450/// compile time.
451pub fn escape(input: &str) -> String {
452    let mut out = String::with_capacity(input.len());
453    for ch in input.chars() {
454        match ch {
455            '&' => out.push_str("&amp;"),
456            '<' => out.push_str("&lt;"),
457            '>' => out.push_str("&gt;"),
458            '"' => out.push_str("&quot;"),
459            '\'' => out.push_str("&#x27;"),
460            _ => out.push(ch),
461        }
462    }
463    out
464}
465
466/// Serialize `value` as JSON safely embedded inside `<script type="application/json" id="...">`.
467///
468/// Escapes `<`, `>`, `&`, U+2028, and U+2029 so untrusted strings cannot break out of the
469/// `<script>` tag or smuggle executable HTML/JavaScript.
470pub fn json_script<T: Serialize>(id: &str, value: &T) -> SlabResult<Markup> {
471    let raw = serde_json::to_string(value)
472        .map_err(|e| SlabError::internal(format!("json_script serialize failed: {e}")))?;
473    let mut safe = String::with_capacity(raw.len());
474    for ch in raw.chars() {
475        match ch {
476            '<' => safe.push_str("\\u003c"),
477            '>' => safe.push_str("\\u003e"),
478            '&' => safe.push_str("\\u0026"),
479            '\u{2028}' => safe.push_str("\\u2028"),
480            '\u{2029}' => safe.push_str("\\u2029"),
481            _ => safe.push(ch),
482        }
483    }
484    Ok(html! {
485        script type="application/json" id=(id) { (PreEscaped(safe)) }
486    })
487}
488
489/// Standard HTMX 2 helpers for `HX-*` headers, `hx-swap-oob` fragments, and signed flash cookies.
490pub mod htmx {
491    use super::{
492        header, html, is_safe_relative_path, Auth, Cookie, CookieJar, Deserialize, Flash,
493        FlashKind, HeaderMap, HeaderValue, IntoResponse, Markup, PreEscaped, Response, SameSite,
494        Serialize, StatusCode, Utc, FLASH_COOKIE_NAME, URL_SAFE_NO_PAD,
495    };
496    use base64::Engine as _;
497
498    #[derive(Serialize, Deserialize)]
499    struct FlashEnvelope {
500        kind: FlashKind,
501        message: String,
502        exp: i64,
503    }
504
505    fn sanitize_dom_id(target_id: &str) -> String {
506        let clean: String = target_id
507            .trim_start_matches('#')
508            .chars()
509            .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
510            .collect();
511        if clean.is_empty() {
512            "oob".to_string()
513        } else {
514            clean
515        }
516    }
517
518    fn sanitize_swap(swap: &str) -> &'static str {
519        match swap {
520            "innerHTML" => "innerHTML",
521            "beforebegin" => "beforebegin",
522            "afterbegin" => "afterbegin",
523            "beforeend" => "beforeend",
524            "afterend" => "afterend",
525            "delete" => "delete",
526            "none" => "none",
527            _ => "outerHTML",
528        }
529    }
530
531    /// Store a signed, 60-second expiring one-shot [`Flash`] message in the `slabs_flash` cookie
532    /// (`HttpOnly`, `SameSite=Lax`, `Path=/`, `Max-Age=60`).
533    #[must_use = "return the updated CookieJar in your response so the flash cookie is sent"]
534    pub fn set_flash(auth: &Auth, jar: CookieJar, flash: &Flash) -> CookieJar {
535        let envelope = FlashEnvelope {
536            kind: flash.kind,
537            message: flash.message.clone(),
538            exp: Utc::now().timestamp() + 60,
539        };
540        let Ok(json) = serde_json::to_vec(&envelope) else {
541            return jar;
542        };
543        let encoded = URL_SAFE_NO_PAD.encode(json);
544        let sig = auth.sign_with_domain("flash:v1", &encoded);
545        let cookie = Cookie::build((FLASH_COOKIE_NAME, format!("{encoded}.{sig}")))
546            .path("/")
547            .http_only(true)
548            .same_site(SameSite::Lax)
549            .secure(auth.cookie_secure())
550            .max_age(time::Duration::seconds(60))
551            .build();
552        jar.add(cookie)
553    }
554
555    /// Read and verify the signed `slabs_flash` cookie, removing it from `jar` if present.
556    ///
557    /// Returns `(jar, None)` when the cookie is absent, malformed, expired, or fails domain-separated
558    /// HMAC verification.
559    #[must_use = "return the updated CookieJar in your response so the flash cookie is cleared"]
560    pub fn take_flash(auth: &Auth, jar: CookieJar) -> (CookieJar, Option<Flash>) {
561        let Some(raw) = jar.get(FLASH_COOKIE_NAME).map(|c| c.value().to_string()) else {
562            return (jar, None);
563        };
564
565        let removal = Cookie::build((FLASH_COOKIE_NAME, ""))
566            .path("/")
567            .http_only(true)
568            .same_site(SameSite::Lax)
569            .secure(auth.cookie_secure())
570            .build();
571        let jar = jar.remove(removal);
572
573        let flash = decode_flash(auth, &raw);
574        (jar, flash)
575    }
576
577    /// Set a signed [`Flash`] cookie and return `303 See Other` with both `Location` and `HX-Redirect`.
578    ///
579    /// Works identically for standard browser form posts and HTMX requests. Falls back to `"/"`
580    /// if `location` is not a safe relative path (blocking open redirects such as `//evil.com`).
581    pub fn flash_redirect(auth: &Auth, jar: CookieJar, location: &str, flash: &Flash) -> Response {
582        let jar = set_flash(auth, jar, flash);
583        let safe_location = if is_safe_relative_path(location) {
584            location
585        } else {
586            "/"
587        };
588        let target =
589            HeaderValue::from_str(safe_location).unwrap_or_else(|_| HeaderValue::from_static("/"));
590        let mut headers = HeaderMap::new();
591        headers.insert(header::LOCATION, target.clone());
592        headers.insert("hx-redirect", target);
593        (StatusCode::SEE_OTHER, jar, headers).into_response()
594    }
595
596    fn decode_flash(auth: &Auth, raw: &str) -> Option<Flash> {
597        let (encoded, sig) = raw.split_once('.')?;
598        if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
599            return None;
600        }
601        if !auth.verify_with_domain("flash:v1", encoded, sig) {
602            return None;
603        }
604        let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?;
605        let envelope: FlashEnvelope = serde_json::from_slice(&bytes).ok()?;
606        if envelope.exp < Utc::now().timestamp() {
607            return None;
608        }
609        Some(Flash {
610            kind: envelope.kind,
611            message: envelope.message,
612        })
613    }
614
615    /// Return a `200 OK` response with `HX-Redirect` so HTMX performs a full navigation.
616    ///
617    /// Falls back to `"/"` if `path` is not a safe relative path (blocking open redirects).
618    pub fn redirect(path: &str) -> Response {
619        let safe_path = if is_safe_relative_path(path) {
620            path
621        } else {
622            "/"
623        };
624        let mut headers = HeaderMap::new();
625        headers.insert(
626            "hx-redirect",
627            HeaderValue::from_str(safe_path).unwrap_or_else(|_| HeaderValue::from_static("/")),
628        );
629        (StatusCode::OK, headers).into_response()
630    }
631
632    /// Return a `200 OK` HTML fragment with an `HX-Trigger` client event header.
633    pub fn with_trigger(markup: Markup, event: &str) -> Response {
634        let mut headers = HeaderMap::new();
635        if let Ok(val) = HeaderValue::from_str(event) {
636            headers.insert("hx-trigger", val);
637        }
638        (StatusCode::OK, headers, markup).into_response()
639    }
640
641    /// Wrap `inner` in an HTMX out-of-band swap container (`hx-swap-oob`).
642    ///
643    /// Sanitizes `target_id` to `[A-Za-z0-9_-]` (falling back to `"oob"`) and validates `swap`
644    /// against the HTMX swap allowlist (`innerHTML`, `outerHTML`, `beforebegin`, `afterbegin`,
645    /// `beforeend`, `afterend`, `delete`, `none`; defaulting to `"outerHTML"`).
646    pub fn oob(target_id: &str, swap: &str, inner: Markup) -> Markup {
647        let clean_id = sanitize_dom_id(target_id);
648        let safe_swap = sanitize_swap(swap);
649        let attr = format!("{safe_swap}:#{clean_id}");
650        html! {
651            div hx-swap-oob=(attr) { (PreEscaped(inner.into_string())) }
652        }
653    }
654
655    /// Emit an HTMX out-of-band delete instruction (`hx-swap-oob="delete"`) for `target_id`.
656    ///
657    /// Sanitizes `target_id` to `[A-Za-z0-9_-]` (falling back to `"oob"`).
658    pub fn oob_delete(target_id: &str) -> Markup {
659        let clean_id = sanitize_dom_id(target_id);
660        html! {
661            div id=(clean_id) hx-swap-oob="delete" {}
662        }
663    }
664
665    /// Emit an HTMX out-of-band `outerHTML` swap targeting `target_id`.
666    ///
667    /// Sanitizes `target_id` to `[A-Za-z0-9_-]` (falling back to `"oob"`).
668    pub fn oob_replace(target_id: &str, inner: Markup) -> Markup {
669        let clean_id = sanitize_dom_id(target_id);
670        html! {
671            div hx-swap-oob=(format!("outerHTML:#{clean_id}")) { (PreEscaped(inner.into_string())) }
672        }
673    }
674
675    /// Return `true` when the request carries `HX-Request: true`.
676    pub fn is_htmx(headers: &HeaderMap) -> bool {
677        headers
678            .get("hx-request")
679            .and_then(|v| v.to_str().ok())
680            .is_some_and(|v| v == "true")
681    }
682
683    /// Return `true` when the `Accept` header contains `application/json`.
684    pub fn wants_json(headers: &HeaderMap) -> bool {
685        headers
686            .get(header::ACCEPT)
687            .and_then(|v| v.to_str().ok())
688            .is_some_and(|v| v.contains("application/json"))
689    }
690}
691
692/// Render a Basecoat alert banner for an optional [`Flash`] message.
693///
694/// Renders a `<div class="alert" role="status">` when `flash` is `Some`, applying
695/// `data-variant="destructive"` for [`FlashKind::Error`], or empty [`Markup`] when `None`.
696#[must_use]
697pub fn flash_banner(flash: Option<&Flash>) -> Markup {
698    let Some(flash) = flash else {
699        return html! {};
700    };
701    let (kind_str, variant) = match flash.kind {
702        FlashKind::Success => ("success", None),
703        FlashKind::Info => ("info", None),
704        FlashKind::Warning => ("warning", None),
705        FlashKind::Error => ("error", Some("destructive")),
706    };
707    html! {
708        div class="alert" role="status" data-flash-kind=(kind_str) data-variant=[variant] {
709            section {
710                p { (flash.message) }
711            }
712        }
713    }
714}
715
716/// Render a toggleable, CSP-safe user bug reporter button and native `<dialog>` widget.
717///
718/// When `enabled` is `false`, returns empty [`Markup`] with zero HTML or JavaScript emitted.
719/// When `enabled` is `true`, renders a floating `"Report bug"` button, a `<dialog data-slabs-bug-reporter="true">`
720/// form posting multipart reports (description, default-on viewport screenshot excluding the bug
721/// widget itself, up to 3 file attachments, and automatic redacted metadata) to
722/// `POST /_slabs/bug-reports`, and loads `/_slabs/vendor/slabs-bug-report.js` externally with zero
723/// inline `<script>` or `<style>` tags.
724#[must_use]
725pub fn bug_report_widget(enabled: bool, source_file: &str, csrf_token: Option<&str>) -> Markup {
726    bug_report_widget_with_label(enabled, source_file, csrf_token, "Report bug")
727}
728
729/// Render a toggleable, CSP-safe user bug reporter widget with a custom trigger `button_label`.
730///
731/// Returns empty [`Markup`] when `enabled` is `false`. See [`bug_report_widget`] for details.
732#[must_use]
733pub fn bug_report_widget_with_label(
734    enabled: bool,
735    source_file: &str,
736    csrf_token: Option<&str>,
737    button_label: &str,
738) -> Markup {
739    if !enabled {
740        return html! {};
741    }
742
743    html! {
744        div data-slabs-bug-reporter="true" class="fixed bottom-4 right-4 z-50" {
745            button
746                type="button"
747                class="btn-outline shadow-md"
748                data-slabs-bug-open="true"
749                aria-haspopup="dialog"
750            {
751                (button_label)
752            }
753        }
754        dialog
755            data-slabs-bug-reporter="true"
756            data-slabs-bug-dialog="true"
757            data-source-file=(source_file)
758            aria-labelledby="slabs-bug-dialog-title"
759            class="dialog w-full max-w-lg rounded-lg border bg-card p-6 text-card-foreground shadow-xl backdrop:bg-black/60"
760        {
761            form
762                data-slabs-bug-form="true"
763                method="post"
764                action="/_slabs/bug-reports"
765                enctype="multipart/form-data"
766                class="grid gap-4"
767            {
768                header class="flex items-center justify-between gap-2" {
769                    h2 id="slabs-bug-dialog-title" class="text-lg font-semibold" { "Report a bug" }
770                    button
771                        type="button"
772                        class="btn-ghost"
773                        data-slabs-bug-close="true"
774                        aria-label="Close"
775                    {
776                        "×"
777                    }
778                }
779                input type="hidden" name="source_file" value=(source_file);
780                @if let Some(tok) = csrf_token {
781                    input type="hidden" name="csrf_token" value=(tok);
782                }
783                div class="grid gap-1.5" {
784                    label for="slabs-bug-description" class="text-sm font-medium" { "Description" }
785                    textarea
786                        id="slabs-bug-description"
787                        name="description"
788                        required
789                        minlength="3"
790                        maxlength="4000"
791                        rows="4"
792                        placeholder="Describe what happened..."
793                        class="textarea w-full"
794                    {}
795                }
796                div class="grid gap-1.5" {
797                    label for="slabs-bug-attachments" class="text-sm font-medium" { "Attachments (up to 3 files)" }
798                    input
799                        id="slabs-bug-attachments"
800                        type="file"
801                        name="attachments"
802                        multiple
803                        class="input w-full"
804                    ;
805                }
806                label class="flex items-center gap-2 text-sm" {
807                    input type="checkbox" name="include_screenshot" checked;
808                    span { "Attach screenshot of this page" }
809                }
810                p data-slabs-bug-status="true" role="status" aria-live="polite" class="text-sm text-muted-foreground" {}
811                footer class="flex items-center justify-end gap-2" {
812                    button type="button" class="btn-outline" data-slabs-bug-close="true" { "Cancel" }
813                    button type="submit" class="btn" data-slabs-bug-submit="true" { "Submit report" }
814                }
815            }
816        }
817        script src="/_slabs/vendor/slabs-bug-report.js" defer {}
818    }
819}
820
821/// Render a complete, CSP-friendly HTML5 page around `body` using compile-time [`Markup`].
822///
823/// Emits zero inline `<style>` or inline `<script>` elements. Loads PWA manifest and theme
824/// metadata, Basecoat UI (`/_slabs/vendor/basecoat.min.css`, which includes
825/// `@view-transition { navigation: auto; }`, and `/_slabs/vendor/basecoat.min.js`), HTMX 2 with
826/// SSE and Idiomorph (`hx-ext="morph"` on `<body>`), Alpine.js 3 (`/_slabs/vendor/alpine.min.js`),
827/// and external service-worker registration (`/_slabs/vendor/sw-register.js`). Pass app-compiled
828/// Tailwind CSS v4 URLs in `stylesheets` (such as `&ctx.assets.stylesheet_urls()`) and ES module
829/// URLs in `scripts`.
830pub fn document(title: &str, stylesheets: &[String], scripts: &[String], body: Markup) -> Markup {
831    html! {
832        (DOCTYPE)
833        html lang="en" class="dark" {
834            head {
835                meta charset="utf-8";
836                meta name="viewport" content="width=device-width, initial-scale=1";
837                link rel="manifest" href="/manifest.webmanifest";
838                meta name="theme-color" content="#1a1b26";
839                meta name="apple-mobile-web-app-capable" content="yes";
840                title { (title) }
841                link rel="stylesheet" href="/_slabs/vendor/basecoat.min.css";
842                @for href in stylesheets {
843                    link rel="stylesheet" href=(href);
844                }
845                script src="/_slabs/vendor/htmx.min.js" defer {}
846                script src="/_slabs/vendor/htmx-ext-sse.js" defer {}
847                script src="/_slabs/vendor/idiomorph-ext.min.js" defer {}
848                script src="/_slabs/vendor/basecoat.min.js" defer {}
849                script src="/_slabs/vendor/alpine.min.js" defer {}
850                @for src in scripts {
851                    script type="module" src=(src) defer {}
852                }
853            }
854            body class="min-h-screen bg-background text-foreground antialiased" hx-ext="morph" {
855                (PreEscaped(body.into_string()))
856                script src="/_slabs/vendor/sw-register.js" defer {}
857            }
858        }
859    }
860}
861
862/// Generate a domain-separated, expiring HMAC-signed CSRF token bound to `scope`.
863///
864/// Uses 16 cryptographically random bytes (`OsRng`, 32 lowercase hex chars), embeds a 4-hour
865/// Unix timestamp expiration, and signs `"{scope}\0{exp}\0{nonce}"` under domain `"csrf:v1"`.
866/// Returns `"{exp}.{nonce}.{sig}"`.
867pub fn csrf_token(auth: &Auth, scope: &str) -> String {
868    let mut nonce_bytes = [0u8; 16];
869    OsRng.fill_bytes(&mut nonce_bytes);
870    let nonce = hex::encode(nonce_bytes);
871    let exp = Utc::now().timestamp() + 4 * 3600;
872    let payload = format!("{scope}\0{exp}\0{nonce}");
873    let sig = auth.sign_with_domain("csrf:v1", &payload);
874    format!("{exp}.{nonce}.{sig}")
875}
876
877/// Verify a submitted CSRF token against `scope`.
878///
879/// Returns a `403 Forbidden` [`SlabError`] if the token format, nonce, expiration, or
880/// domain-separated HMAC signature is invalid.
881pub fn verify_csrf(auth: &Auth, scope: &str, token: &str) -> SlabResult<()> {
882    let mut parts = token.split('.');
883    let (Some(exp_str), Some(nonce), Some(sig), None) =
884        (parts.next(), parts.next(), parts.next(), parts.next())
885    else {
886        return Err(SlabError::forbidden("invalid csrf token format"));
887    };
888    if nonce.len() != 32 || !nonce.bytes().all(|b| b.is_ascii_hexdigit()) {
889        return Err(SlabError::forbidden("invalid csrf token format"));
890    }
891    let exp: i64 = exp_str
892        .parse()
893        .map_err(|_| SlabError::forbidden("invalid csrf token format"))?;
894    if Utc::now().timestamp() > exp {
895        return Err(SlabError::forbidden("csrf token expired"));
896    }
897    let payload = format!("{scope}\0{exp}\0{nonce}");
898    if auth.verify_with_domain("csrf:v1", &payload, sig) {
899        Ok(())
900    } else {
901        Err(SlabError::forbidden("csrf token verification failed"))
902    }
903}
904
905/// Render untrusted `CommonMark` and GitHub-flavored Markdown into safe [`Markup`].
906///
907/// Enables tables, strikethrough, and task lists. Heading attributes are explicitly disabled to
908/// prevent Alpine/HTMX attribute injection (`x-init`, `x-data`, `hx-*`). Drops raw HTML blocks
909/// and inline HTML tags so untrusted authors cannot inject `<script>` or event handlers. Rewrites
910/// unsafe link or image URLs (disallowed schemes such as `javascript:`, `vbscript:`, `data:`,
911/// protocol-relative `//` or `/\`, or URLs with ASCII control characters) to `"#"`, and adds
912/// `rel="noopener noreferrer ugc"` to every rendered `<a>` link.
913pub fn render_markdown(input: &str) -> Markup {
914    use pulldown_cmark::{Event, LinkType, Options, Parser, Tag, TagEnd};
915
916    let mut options = Options::empty();
917    options.insert(Options::ENABLE_TABLES);
918    options.insert(Options::ENABLE_STRIKETHROUGH);
919    options.insert(Options::ENABLE_TASKLISTS);
920
921    let parser = Parser::new_ext(input, options).filter_map(|event| match event {
922        Event::Html(_) | Event::InlineHtml(_) => None,
923        Event::Start(Tag::Link {
924            link_type,
925            dest_url,
926            title,
927            ..
928        }) => {
929            let candidate = if link_type == LinkType::Email
930                && !dest_url.trim().to_ascii_lowercase().starts_with("mailto:")
931            {
932                format!("mailto:{}", dest_url.trim())
933            } else {
934                dest_url.to_string()
935            };
936            let href = escape(&sanitize_url(&candidate));
937            let open_tag = if title.is_empty() {
938                format!("<a href=\"{href}\" rel=\"noopener noreferrer ugc\">")
939            } else {
940                format!(
941                    "<a href=\"{href}\" title=\"{}\" rel=\"noopener noreferrer ugc\">",
942                    escape(&title)
943                )
944            };
945            Some(Event::Html(open_tag.into()))
946        }
947        Event::End(TagEnd::Link) => Some(Event::Html("</a>".into())),
948        Event::Start(Tag::Image {
949            link_type,
950            dest_url,
951            title,
952            id,
953        }) => Some(Event::Start(Tag::Image {
954            link_type,
955            dest_url: sanitize_url(&dest_url).into(),
956            title,
957            id,
958        })),
959        other => Some(other),
960    });
961
962    let mut html_out = String::with_capacity(input.len() + 64);
963    pulldown_cmark::html::push_html(&mut html_out, parser);
964    PreEscaped(html_out)
965}
966
967fn sanitize_url(raw: &str) -> String {
968    let trimmed = raw.trim();
969    if trimmed.is_empty()
970        || trimmed.bytes().any(|b| b <= 0x1f || b == 0x7f)
971        || trimmed.starts_with("//")
972        || trimmed.starts_with("/\\")
973    {
974        return "#".to_string();
975    }
976    let lower = trimmed.to_ascii_lowercase();
977    if lower.starts_with("http://")
978        || lower.starts_with("https://")
979        || lower.starts_with("mailto:")
980        || lower.starts_with('/')
981        || lower.starts_with('#')
982        || !lower.contains(':')
983    {
984        trimmed.to_string()
985    } else {
986        "#".to_string()
987    }
988}
989
990#[cfg(test)]
991mod tests {
992    use super::*;
993
994    #[test]
995    fn render_markdown_renders_gfm_adds_rel_and_blocks_xss_and_heading_attrs() {
996        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";
997        let rendered = render_markdown(md).into_string();
998        assert!(rendered.contains("<h1>Title</h1>"));
999        assert!(rendered.contains("<h1>Hi {x-init=alert(1)}</h1>"));
1000        assert!(!rendered.contains("<h1 "));
1001        assert!(rendered.contains("<table>"));
1002        assert!(rendered
1003            .contains("<a href=\"https://example.com\" rel=\"noopener noreferrer ugc\">ok</a>"));
1004        assert!(!rendered.contains("<script>"));
1005        assert!(!rendered.contains("hx-get"));
1006        assert!(!rendered.contains("x-init=\"pwn()\""));
1007        assert!(!rendered.contains("javascript:"));
1008        assert!(!rendered.contains("href=\"//evil.com\""));
1009        assert!(!rendered.contains("href=\"/\\evil.com\""));
1010        assert!(!rendered.contains("java\tscript:"));
1011        assert_eq!(sanitize_url("https://example.com/\x01bad"), "#");
1012        assert_eq!(sanitize_url("https://example.com/\x7fbad"), "#");
1013    }
1014
1015    #[test]
1016    fn render_markdown_heading_attributes_disabled_no_x_init_attr() {
1017        let rendered = render_markdown("# Hi {x-init=alert(1)}").into_string();
1018        assert!(rendered.contains("<h1>Hi {x-init=alert(1)}</h1>"));
1019        assert!(!rendered.contains("<h1 "));
1020    }
1021
1022    #[test]
1023    fn safe_redirects_block_open_redirects_and_allow_relative_paths() {
1024        let auth = Auth::for_signing("test-redirect-secret-key", false);
1025        for unsafe_target in [
1026            "https://evil.com",
1027            "//evil.com",
1028            "/\\evil.com",
1029            "/foo\\bar",
1030            "/ok\r\nSet-Cookie: a=b",
1031            "relative/path",
1032        ] {
1033            let r1 = htmx::redirect(unsafe_target);
1034            assert_eq!(
1035                r1.headers()
1036                    .get("hx-redirect")
1037                    .and_then(|v| v.to_str().ok()),
1038                Some("/"),
1039                "redirect should reject {unsafe_target:?}"
1040            );
1041
1042            let r2 =
1043                htmx::flash_redirect(&auth, CookieJar::new(), unsafe_target, &Flash::info("hi"));
1044            assert_eq!(
1045                r2.headers()
1046                    .get(header::LOCATION)
1047                    .and_then(|v| v.to_str().ok()),
1048                Some("/"),
1049                "flash_redirect should reject {unsafe_target:?}"
1050            );
1051        }
1052
1053        let ok = htmx::redirect("/rooms/42?tab=chat");
1054        assert_eq!(
1055            ok.headers()
1056                .get("hx-redirect")
1057                .and_then(|v| v.to_str().ok()),
1058            Some("/rooms/42?tab=chat")
1059        );
1060    }
1061
1062    #[test]
1063    fn redirect_external_allows_http_https_only() {
1064        let ok = redirect_external("https://example.com/callback?ok=1").unwrap();
1065        assert_eq!(ok.status(), StatusCode::SEE_OTHER);
1066        assert_eq!(
1067            ok.headers()
1068                .get(header::LOCATION)
1069                .and_then(|v| v.to_str().ok()),
1070            Some("https://example.com/callback?ok=1")
1071        );
1072
1073        assert!(redirect_external("javascript:alert(1)").is_err());
1074        assert!(redirect_external("/relative").is_err());
1075        assert!(redirect_external("https://example.com/\r\nbad").is_err());
1076        assert!(redirect_external("https://").is_err());
1077    }
1078
1079    #[test]
1080    fn csrf_token_roundtrip_and_expiration_and_tamper_rejection() {
1081        let auth = Auth::for_signing("test-csrf-secret-key", false);
1082        let token = csrf_token(&auth, "ses_123");
1083        let parts: Vec<&str> = token.split('.').collect();
1084        assert_eq!(parts.len(), 3);
1085        assert_eq!(parts[1].len(), 32);
1086
1087        verify_csrf(&auth, "ses_123", &token).expect("valid csrf token");
1088        assert!(verify_csrf(&auth, "ses_other", &token).is_err());
1089        assert!(verify_csrf(&auth, "ses_123", "not-a-valid-token").is_err());
1090
1091        // Expired token signed with valid domain key must be rejected
1092        let expired_exp = Utc::now().timestamp() - 10;
1093        let nonce = "0123456789abcdef0123456789abcdef";
1094        let sig = auth.sign_with_domain("csrf:v1", &format!("ses_123\0{expired_exp}\0{nonce}"));
1095        let expired = format!("{expired_exp}.{nonce}.{sig}");
1096        assert!(verify_csrf(&auth, "ses_123", &expired).is_err());
1097    }
1098
1099    #[test]
1100    fn flash_roundtrip_max_age_and_expiration() {
1101        use base64::Engine as _;
1102
1103        let auth = Auth::for_signing("test-flash-secret-key", false);
1104        let flash = Flash::success("Saved changes.");
1105
1106        let jar = htmx::set_flash(&auth, CookieJar::new(), &flash);
1107        let cookie = jar.get(FLASH_COOKIE_NAME).expect("flash cookie set");
1108        assert_eq!(cookie.path(), Some("/"));
1109        assert_eq!(cookie.http_only(), Some(true));
1110        assert_eq!(cookie.same_site(), Some(SameSite::Lax));
1111        assert_eq!(cookie.max_age(), Some(time::Duration::seconds(60)));
1112
1113        let (jar, taken) = htmx::take_flash(&auth, jar);
1114        assert_eq!(taken, Some(flash));
1115        assert!(jar.get(FLASH_COOKIE_NAME).is_none());
1116
1117        let (_jar, second) = htmx::take_flash(&auth, jar);
1118        assert_eq!(second, None);
1119
1120        // Expired flash cookie must be rejected
1121        let expired_json = serde_json::json!({
1122            "kind": "info",
1123            "message": "stale",
1124            "exp": Utc::now().timestamp() - 5,
1125        });
1126        let encoded = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&expired_json).unwrap());
1127        let sig = auth.sign_with_domain("flash:v1", &encoded);
1128        let mut headers = HeaderMap::new();
1129        headers.insert(
1130            header::COOKIE,
1131            HeaderValue::from_str(&format!("{FLASH_COOKIE_NAME}={encoded}.{sig}")).unwrap(),
1132        );
1133        let expired_jar = CookieJar::from_headers(&headers);
1134        let (_cleared, result) = htmx::take_flash(&auth, expired_jar);
1135        assert_eq!(result, None);
1136    }
1137
1138    #[test]
1139    fn flash_rejects_tampered_cookie_and_clears_it() {
1140        let auth = Auth::for_signing("test-flash-secret-key", false);
1141        let jar = htmx::set_flash(&auth, CookieJar::new(), &Flash::info("Hello"));
1142        let raw = jar.get(FLASH_COOKIE_NAME).unwrap().value().to_string();
1143        let (encoded, sig) = raw.split_once('.').unwrap();
1144        let flipped = if sig.starts_with('0') { '1' } else { '0' };
1145        let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);
1146
1147        let mut tampered_headers = HeaderMap::new();
1148        tampered_headers.insert(
1149            header::COOKIE,
1150            HeaderValue::from_str(&format!("{FLASH_COOKIE_NAME}={tampered}")).unwrap(),
1151        );
1152        let tampered_jar = CookieJar::from_headers(&tampered_headers);
1153
1154        let (cleared_jar, taken) = htmx::take_flash(&auth, tampered_jar);
1155        assert_eq!(taken, None);
1156        assert!(cleared_jar.get(FLASH_COOKIE_NAME).is_none());
1157    }
1158
1159    #[test]
1160    fn flash_redirect_sets_see_other_location_hx_redirect_and_cookie() {
1161        let auth = Auth::for_signing("test-flash-secret-key", false);
1162        let resp = htmx::flash_redirect(
1163            &auth,
1164            CookieJar::new(),
1165            "/rooms",
1166            &Flash::warning("Room archived"),
1167        );
1168
1169        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
1170        assert_eq!(
1171            resp.headers()
1172                .get(header::LOCATION)
1173                .and_then(|v| v.to_str().ok()),
1174            Some("/rooms")
1175        );
1176        assert_eq!(
1177            resp.headers()
1178                .get("hx-redirect")
1179                .and_then(|v| v.to_str().ok()),
1180            Some("/rooms")
1181        );
1182        let set_cookie = resp
1183            .headers()
1184            .get(header::SET_COOKIE)
1185            .and_then(|v| v.to_str().ok())
1186            .expect("Set-Cookie header present");
1187        assert!(set_cookie.contains("slabs_flash="));
1188        assert!(set_cookie.contains("HttpOnly"));
1189        assert!(set_cookie.contains("SameSite=Lax"));
1190        assert!(set_cookie.contains("Path=/"));
1191        assert!(set_cookie.contains("Max-Age=60"));
1192    }
1193
1194    #[test]
1195    fn oob_sanitizes_id_and_swap_strategy() {
1196        let rendered =
1197            htmx::oob("#list\" onclick=\"x", "evilSwap", html! { p { "ok" } }).into_string();
1198        assert!(rendered.contains("hx-swap-oob=\"outerHTML:#listonclickx\""));
1199
1200        let empty_id = htmx::oob_replace("!!!", html! { p { "ok" } }).into_string();
1201        assert!(empty_id.contains("hx-swap-oob=\"outerHTML:#oob\""));
1202
1203        let valid_swap =
1204            htmx::oob("messages_1-a", "beforeend", html! { li { "hi" } }).into_string();
1205        assert!(valid_swap.contains("hx-swap-oob=\"beforeend:#messages_1-a\""));
1206    }
1207
1208    #[test]
1209    fn flash_banner_renders_accessible_alert_or_empty() {
1210        assert_eq!(flash_banner(None).into_string(), "");
1211
1212        let ok_html = flash_banner(Some(&Flash::success("Item <saved>"))).into_string();
1213        assert!(ok_html.contains("class=\"alert\""));
1214        assert!(ok_html.contains("role=\"status\""));
1215        assert!(ok_html.contains("data-flash-kind=\"success\""));
1216        assert!(ok_html.contains("Item &lt;saved&gt;"));
1217        assert!(!ok_html.contains("data-variant=\"destructive\""));
1218
1219        let err_html = flash_banner(Some(&Flash::error("Failed"))).into_string();
1220        assert!(err_html.contains("role=\"status\""));
1221        assert!(err_html.contains("data-flash-kind=\"error\""));
1222        assert!(err_html.contains("data-variant=\"destructive\""));
1223        assert!(err_html.contains("Failed"));
1224    }
1225
1226    #[test]
1227    fn document_is_csp_friendly_with_zero_inline_scripts_or_styles() {
1228        let rendered = document("Campfire", &[], &[], html! { main { "Hi" } }).into_string();
1229        assert!(rendered.contains("<link rel=\"manifest\" href=\"/manifest.webmanifest\">"));
1230        assert!(rendered.contains("<meta name=\"theme-color\" content=\"#1a1b26\">"));
1231        assert!(rendered.contains("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">"));
1232        assert!(rendered.contains("<script src=\"/_slabs/vendor/sw-register.js\" defer></script>"));
1233        assert!(!rendered.contains("<style"));
1234        assert!(!rendered.contains("<script>"));
1235    }
1236
1237    #[test]
1238    fn json_script_escapes_script_breakout_and_line_separators() {
1239        let payload = serde_json::json!({
1240            "html": "</script><img src=x>&",
1241            "sep": "a\u{2028}b\u{2029}c",
1242        });
1243        let rendered = json_script("boot-data", &payload).unwrap().into_string();
1244        assert!(rendered.starts_with("<script type=\"application/json\" id=\"boot-data\">"));
1245        assert!(rendered.ends_with("</script>"));
1246        assert!(!rendered.contains("</script><img"));
1247        assert!(rendered.contains("\\u003c/script\\u003e\\u003cimg src=x\\u003e\\u0026"));
1248        assert!(rendered.contains("\\u2028"));
1249        assert!(rendered.contains("\\u2029"));
1250    }
1251
1252    #[test]
1253    fn bug_report_widget_emits_nothing_when_disabled_and_csp_safe_dialog_when_enabled() {
1254        assert_eq!(
1255            bug_report_widget(false, "slabs/rooms/show.rs", Some("tok_123")).into_string(),
1256            ""
1257        );
1258        assert_eq!(
1259            bug_report_widget_with_label(false, "slabs/rooms/show.rs", None, "Feedback")
1260                .into_string(),
1261            ""
1262        );
1263
1264        let rendered =
1265            bug_report_widget(true, "slabs/rooms/show.rs", Some("tok_abc")).into_string();
1266        assert!(rendered.contains("<dialog data-slabs-bug-reporter=\"true\""));
1267        assert!(rendered.contains("data-source-file=\"slabs/rooms/show.rs\""));
1268        assert!(rendered.contains("name=\"source_file\" value=\"slabs/rooms/show.rs\""));
1269        assert!(rendered.contains("name=\"csrf_token\" value=\"tok_abc\""));
1270        assert!(rendered.contains("name=\"description\""));
1271        assert!(rendered.contains("name=\"attachments\" multiple"));
1272        assert!(rendered.contains("<input type=\"checkbox\" name=\"include_screenshot\" checked>"));
1273        assert!(
1274            rendered.contains("<script src=\"/_slabs/vendor/slabs-bug-report.js\" defer></script>")
1275        );
1276        assert!(!rendered.contains("<style"));
1277        assert!(!rendered.contains("<script>"));
1278        assert!(!rendered.contains("style=\""));
1279
1280        let custom = bug_report_widget_with_label(true, "slabs/home.rs", None, "Send feedback")
1281            .into_string();
1282        assert!(custom.contains("Send feedback"));
1283        assert!(!custom.contains("name=\"csrf_token\""));
1284
1285        assert!(BUG_REPORT_JS.contains("/_slabs/bug-reports"));
1286        assert!(BUG_REPORT_JS.contains("[data-slabs-bug-reporter]"));
1287        assert!(BUG_REPORT_JS.contains("htmx:responseError"));
1288        assert!(BUG_REPORT_JS.contains("window.location.pathname"));
1289    }
1290}