1use 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
64pub const FLASH_COOKIE_NAME: &str = "slabs_flash";
66
67pub const SW_REGISTER_JS: &str = r#"if ("serviceWorker" in navigator) { window.addEventListener("load", function() { navigator.serviceWorker.register("/sw.js").catch(function() {}); }); }"#;
72
73pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
351#[serde(rename_all = "lowercase")]
352pub enum FlashKind {
353 Success,
355 Info,
357 Warning,
359 Error,
361}
362
363#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
365pub struct Flash {
366 pub kind: FlashKind,
368 pub message: String,
370}
371
372impl Flash {
373 #[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 #[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 #[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 #[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
410fn 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
420pub 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
447pub 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("&"),
456 '<' => out.push_str("<"),
457 '>' => out.push_str(">"),
458 '"' => out.push_str("""),
459 '\'' => out.push_str("'"),
460 _ => out.push(ch),
461 }
462 }
463 out
464}
465
466pub 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
489pub 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 #[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 #[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 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 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 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 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 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 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 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 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#[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#[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#[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
821pub 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
862pub 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
877pub 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
905pub 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	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 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 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 <saved>"));
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}