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};
pub const FLASH_COOKIE_NAME: &str = "slabs_flash";
pub const SW_REGISTER_JS: &str = r#"if ("serviceWorker" in navigator) { window.addEventListener("load", function() { navigator.serviceWorker.register("/sw.js").catch(function() {}); }); }"#;
pub const BUG_REPORT_JS: &str = r##"(function () {
if (typeof window === "undefined" || window.__slabsBugReporterInstalled) return;
window.__slabsBugReporterInstalled = true;
var MAX_ERRORS = 10;
var MAX_ATTACHMENTS = 3;
var recentErrors = [];
function pushError(kind, message, detail) {
recentErrors.push({
kind: String(kind || "error").slice(0, 64),
message: String(message || "error").slice(0, 512),
detail: detail ? String(detail).slice(0, 512) : null,
at: new Date().toISOString()
});
if (recentErrors.length > MAX_ERRORS) {
recentErrors.shift();
}
}
window.addEventListener("error", function (e) {
var loc = e.filename ? e.filename + ":" + e.lineno + ":" + e.colno : null;
pushError("onerror", e.message || "Script error", loc);
});
window.addEventListener("unhandledrejection", function (e) {
var r = e.reason;
pushError(
"unhandledrejection",
(r && r.message) || String(r || "Unhandled promise rejection"),
r && r.stack
);
});
["htmx:targetError", "htmx:swapError", "htmx:responseError"].forEach(function (ev) {
document.addEventListener(ev, function (e) {
var d = e.detail || {};
var msg = d.error || (d.xhr ? "HTTP " + d.xhr.status : ev);
var target = d.target && d.target.id ? "#" + d.target.id : null;
pushError(ev, msg, target);
});
});
function findDialog() {
return document.querySelector('dialog[data-slabs-bug-reporter="true"]');
}
function openDialog(dialog) {
if (!dialog) return;
var statusEl = dialog.querySelector('[data-slabs-bug-status="true"]');
if (statusEl) statusEl.textContent = "";
if (typeof dialog.showModal === "function") {
if (!dialog.open) dialog.showModal();
} else {
dialog.setAttribute("open", "");
}
}
function closeDialog(dialog) {
if (!dialog) return;
if (typeof dialog.close === "function") {
if (dialog.open) dialog.close();
} else {
dialog.removeAttribute("open");
}
}
function nextFrame() {
return new Promise(function (resolve) {
if (typeof window.requestAnimationFrame === "function") {
window.requestAnimationFrame(function () { resolve(); });
} else {
setTimeout(resolve, 16);
}
});
}
function captureViewportScreenshot(dialog) {
return new Promise(function (resolve) {
var reporterNodes = Array.prototype.slice.call(
document.querySelectorAll("[data-slabs-bug-reporter]")
);
var prevHidden = reporterNodes.map(function (el) { return el.hidden; });
var wasOpen = Boolean(dialog && dialog.open);
function restoreUi() {
reporterNodes.forEach(function (el, idx) {
el.hidden = prevHidden[idx];
});
if (wasOpen) {
openDialog(dialog);
}
}
try {
closeDialog(dialog);
reporterNodes.forEach(function (el) { el.hidden = true; });
} catch (_) {
restoreUi();
resolve(null);
return;
}
nextFrame().then(function () {
var settled = false;
function finish(blob) {
if (settled) return;
settled = true;
restoreUi();
resolve(blob);
}
var timer = setTimeout(function () { finish(null); }, 2500);
try {
var width = Math.min(Math.max(window.innerWidth || 1280, 320), 1920);
var height = Math.min(Math.max(window.innerHeight || 720, 240), 1080);
var clone = document.documentElement.cloneNode(true);
var toStrip = clone.querySelectorAll("[data-slabs-bug-reporter], script");
for (var i = 0; i < toStrip.length; i++) {
if (toStrip[i].parentNode) {
toStrip[i].parentNode.removeChild(toStrip[i]);
}
}
clone.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
var xhtml = new XMLSerializer().serializeToString(clone);
var svg =
'<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' +
'<foreignObject width="100%" height="100%">' + xhtml + "</foreignObject>" +
"</svg>";
var img = new Image();
img.onload = function () {
try {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
if (!ctx) {
clearTimeout(timer);
finish(null);
return;
}
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(function (blob) {
clearTimeout(timer);
finish(blob || null);
}, "image/png");
} catch (_) {
clearTimeout(timer);
finish(null);
}
};
img.onerror = function () {
clearTimeout(timer);
finish(null);
};
img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
} catch (_) {
clearTimeout(timer);
finish(null);
}
});
});
}
document.addEventListener("click", function (e) {
var target = e.target;
if (!target || typeof target.closest !== "function") return;
if (target.closest('[data-slabs-bug-open="true"]')) {
openDialog(findDialog());
return;
}
if (target.closest('[data-slabs-bug-close="true"]')) {
closeDialog(findDialog());
}
});
document.addEventListener("submit", function (e) {
var form = e.target;
if (!form || !form.matches || !form.matches('form[data-slabs-bug-form="true"]')) return;
e.preventDefault();
var dialog = form.closest('dialog[data-slabs-bug-reporter="true"]') || findDialog();
var statusEl = form.querySelector('[data-slabs-bug-status="true"]');
var submitBtn = form.querySelector('[data-slabs-bug-submit="true"]');
var descEl = form.querySelector('textarea[name="description"]');
var sourceEl = form.querySelector('input[name="source_file"]');
var csrfEl = form.querySelector('input[name="csrf_token"]');
var includeShotEl = form.querySelector('input[name="include_screenshot"]');
var filesEl = form.querySelector('input[name="attachments"]');
var description = descEl ? descEl.value.trim() : "";
if (description.length < 3) {
if (statusEl) statusEl.textContent = "Please enter at least 3 characters describing the issue.";
return;
}
if (submitBtn) submitBtn.disabled = true;
if (statusEl) statusEl.textContent = "Preparing report...";
var metadata = {
url_path: window.location ? window.location.pathname : "/",
viewport: (window.innerWidth || 0) + "x" + (window.innerHeight || 0),
device_pixel_ratio: window.devicePixelRatio || 1,
user_agent: (navigator && navigator.userAgent) ? String(navigator.userAgent).slice(0, 256) : "",
color_scheme:
window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light",
online: navigator && typeof navigator.onLine === "boolean" ? navigator.onLine : true,
recent_errors: recentErrors.slice()
};
var shotPromise =
includeShotEl && includeShotEl.checked
? captureViewportScreenshot(dialog)
: Promise.resolve(null);
shotPromise
.then(function (screenshotBlob) {
if (statusEl) statusEl.textContent = "Submitting bug report...";
var fd = new FormData();
fd.append("description", description);
if (sourceEl && sourceEl.value) {
fd.append("source_file", sourceEl.value);
}
if (csrfEl && csrfEl.value) {
fd.append("csrf_token", csrfEl.value);
}
fd.append("metadata_json", JSON.stringify(metadata));
if (screenshotBlob) {
fd.append("screenshot", screenshotBlob, "screenshot.png");
}
if (filesEl && filesEl.files) {
var count = Math.min(filesEl.files.length, MAX_ATTACHMENTS);
for (var i = 0; i < count; i++) {
fd.append("attachments", filesEl.files[i], filesEl.files[i].name || "attachment.bin");
}
}
return fetch("/_slabs/bug-reports", {
method: "POST",
body: fd,
credentials: "same-origin"
});
})
.then(function (resp) {
return resp.json().catch(function () { return {}; }).then(function (data) {
if (!resp.ok) {
var errMsg = (data && data.message) || ("Submission failed (HTTP " + resp.status + ")");
throw new Error(errMsg);
}
if (statusEl) {
statusEl.textContent = "Bug report submitted (" + (data.id || "recorded") + "). Thank you!";
}
if (descEl) descEl.value = "";
if (filesEl) filesEl.value = "";
});
})
.catch(function (err) {
if (statusEl) {
statusEl.textContent = (err && err.message) || "Failed to submit bug report.";
}
})
.finally(function () {
if (submitBtn) submitBtn.disabled = false;
});
});
})();
"##;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FlashKind {
Success,
Info,
Warning,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Flash {
pub kind: FlashKind,
pub message: String,
}
impl Flash {
#[must_use]
pub fn success(message: impl Into<String>) -> Self {
Self {
kind: FlashKind::Success,
message: message.into(),
}
}
#[must_use]
pub fn info(message: impl Into<String>) -> Self {
Self {
kind: FlashKind::Info,
message: message.into(),
}
}
#[must_use]
pub fn warning(message: impl Into<String>) -> Self {
Self {
kind: FlashKind::Warning,
message: message.into(),
}
}
#[must_use]
pub fn error(message: impl Into<String>) -> Self {
Self {
kind: FlashKind::Error,
message: message.into(),
}
}
}
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)
}
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())
}
pub fn escape(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(ch),
}
}
out
}
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)) }
})
}
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",
}
}
#[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)
}
#[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)
}
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,
})
}
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()
}
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()
}
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())) }
}
}
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" {}
}
}
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())) }
}
}
pub fn is_htmx(headers: &HeaderMap) -> bool {
headers
.get("hx-request")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v == "true")
}
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"))
}
}
#[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) }
}
}
}
}
#[must_use]
pub fn bug_report_widget(enabled: bool, source_file: &str, csrf_token: Option<&str>) -> Markup {
bug_report_widget_with_label(enabled, source_file, csrf_token, "Report bug")
}
#[must_use]
pub fn bug_report_widget_with_label(
enabled: bool,
source_file: &str,
csrf_token: Option<&str>,
button_label: &str,
) -> Markup {
if !enabled {
return html! {};
}
html! {
div data-slabs-bug-reporter="true" class="fixed bottom-4 right-4 z-50" {
button
type="button"
class="btn-outline shadow-md"
data-slabs-bug-open="true"
aria-haspopup="dialog"
{
(button_label)
}
}
dialog
data-slabs-bug-reporter="true"
data-slabs-bug-dialog="true"
data-source-file=(source_file)
aria-labelledby="slabs-bug-dialog-title"
class="dialog w-full max-w-lg rounded-lg border bg-card p-6 text-card-foreground shadow-xl backdrop:bg-black/60"
{
form
data-slabs-bug-form="true"
method="post"
action="/_slabs/bug-reports"
enctype="multipart/form-data"
class="grid gap-4"
{
header class="flex items-center justify-between gap-2" {
h2 id="slabs-bug-dialog-title" class="text-lg font-semibold" { "Report a bug" }
button
type="button"
class="btn-ghost"
data-slabs-bug-close="true"
aria-label="Close"
{
"×"
}
}
input type="hidden" name="source_file" value=(source_file);
@if let Some(tok) = csrf_token {
input type="hidden" name="csrf_token" value=(tok);
}
div class="grid gap-1.5" {
label for="slabs-bug-description" class="text-sm font-medium" { "Description" }
textarea
id="slabs-bug-description"
name="description"
required
minlength="3"
maxlength="4000"
rows="4"
placeholder="Describe what happened..."
class="textarea w-full"
{}
}
div class="grid gap-1.5" {
label for="slabs-bug-attachments" class="text-sm font-medium" { "Attachments (up to 3 files)" }
input
id="slabs-bug-attachments"
type="file"
name="attachments"
multiple
class="input w-full"
;
}
label class="flex items-center gap-2 text-sm" {
input type="checkbox" name="include_screenshot" checked;
span { "Attach screenshot of this page" }
}
p data-slabs-bug-status="true" role="status" aria-live="polite" class="text-sm text-muted-foreground" {}
footer class="flex items-center justify-end gap-2" {
button type="button" class="btn-outline" data-slabs-bug-close="true" { "Cancel" }
button type="submit" class="btn" data-slabs-bug-submit="true" { "Submit report" }
}
}
}
script src="/_slabs/vendor/slabs-bug-report.js" defer {}
}
}
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 {}
}
}
}
}
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}")
}
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"))
}
}
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	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());
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);
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 <saved>"));
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"));
}
#[test]
fn bug_report_widget_emits_nothing_when_disabled_and_csp_safe_dialog_when_enabled() {
assert_eq!(
bug_report_widget(false, "slabs/rooms/show.rs", Some("tok_123")).into_string(),
""
);
assert_eq!(
bug_report_widget_with_label(false, "slabs/rooms/show.rs", None, "Feedback")
.into_string(),
""
);
let rendered =
bug_report_widget(true, "slabs/rooms/show.rs", Some("tok_abc")).into_string();
assert!(rendered.contains("<dialog data-slabs-bug-reporter=\"true\""));
assert!(rendered.contains("data-source-file=\"slabs/rooms/show.rs\""));
assert!(rendered.contains("name=\"source_file\" value=\"slabs/rooms/show.rs\""));
assert!(rendered.contains("name=\"csrf_token\" value=\"tok_abc\""));
assert!(rendered.contains("name=\"description\""));
assert!(rendered.contains("name=\"attachments\" multiple"));
assert!(rendered.contains("<input type=\"checkbox\" name=\"include_screenshot\" checked>"));
assert!(
rendered.contains("<script src=\"/_slabs/vendor/slabs-bug-report.js\" defer></script>")
);
assert!(!rendered.contains("<style"));
assert!(!rendered.contains("<script>"));
assert!(!rendered.contains("style=\""));
let custom = bug_report_widget_with_label(true, "slabs/home.rs", None, "Send feedback")
.into_string();
assert!(custom.contains("Send feedback"));
assert!(!custom.contains("name=\"csrf_token\""));
assert!(BUG_REPORT_JS.contains("/_slabs/bug-reports"));
assert!(BUG_REPORT_JS.contains("[data-slabs-bug-reporter]"));
assert!(BUG_REPORT_JS.contains("htmx:responseError"));
assert!(BUG_REPORT_JS.contains("window.location.pathname"));
}
}