slabs-html 0.3.0

Hypermedia SSR HTML battery: compile-time maud markup, Turbo-style HTML streams, layouts, and CSRF tokens
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
//! Compile-time HTML rendering, document layout, HTMX helpers, and CSRF tokens for Slabs.
//!
//! This crate re-exports [`html!`] (aliased as `maud!` in `slabs::prelude`) so handlers build
//! auto-escaped HTML at compile time with zero runtime template engine.
//!
//! # Document layout
//!
//! [`document`] renders a complete, CSP-friendly HTML5 page with zero inline `<style>` or inline
//! `<script>` elements. Native view transitions (`@view-transition { navigation: auto; }`) ship
//! inside `/_slabs/vendor/basecoat.min.css`, and service-worker registration loads externally via
//! `/_slabs/vendor/sw-register.js` alongside Basecoat UI, HTMX 2 (with SSE and Idiomorph
//! `hx-ext="morph"` on `<body>`), and Alpine.js 3.
//! Pass app-compiled Tailwind CSS v4 stylesheets (for example `&ctx.assets.stylesheet_urls()`) and
//! module scripts via the `stylesheets` and `scripts` arguments.
//! All frontend assets are self-hosted with zero CDN or Node runtime requirement.
//!
//! # HTMX helpers
//!
//! The [`htmx`] module emits standard `HX-*` headers and `hx-swap-oob` fragments:
//!
//! - [`htmx::redirect`] triggers a full same-origin navigation via `HX-Redirect` (sanitized against open redirects).
//! - [`redirect_external`] emits an explicit `303 See Other` redirect to an `http://` or `https://` URL.
//! - [`htmx::with_trigger`] attaches an `HX-Trigger` client event header to a fragment.
//! - [`htmx::oob`], [`htmx::oob_replace`], and [`htmx::oob_delete`] wrap sanitized out-of-band DOM swaps.
//! - [`htmx::is_htmx`] and [`htmx::wants_json`] inspect `HX-Request` and `Accept` headers.
//!
//! # CSRF protection
//!
//! Use [`csrf_token`] to mint a domain-separated, expiring HMAC-signed token bound to a session
//! scope and [`verify_csrf`] to verify submitted tokens.
//!
//! # Usage
//!
//! ```rust,no_run
//! use axum::http::HeaderMap;
//! use axum::response::IntoResponse;
//! use slabs_html::{document, html, htmx};
//!
//! fn render_notice(headers: &HeaderMap, styles: &[String]) -> axum::response::Response {
//!     let fragment = html! {
//!         p id="notice" { "Saved." }
//!     };
//!
//!     if htmx::is_htmx(headers) {
//!         return htmx::oob_replace("notice", fragment).into_response();
//!     }
//!
//!     document("Notice", styles, &[], fragment).into_response()
//! }
//! ```

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

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

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

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

/// External bug-reporter script served at `/_slabs/vendor/slabs-bug-report.js`.
///
/// Referenced via `<script src="/_slabs/vendor/slabs-bug-report.js" defer></script>` from
/// [`bug_report_widget`] and [`bug_report_widget_with_label`] so pages emit zero inline scripts
/// under strict Content Security Policies.
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;
      });
  });
})();
"##;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// Render a toggleable, CSP-safe user bug reporter button and native `<dialog>` widget.
///
/// When `enabled` is `false`, returns empty [`Markup`] with zero HTML or JavaScript emitted.
/// When `enabled` is `true`, renders a floating `"Report bug"` button, a `<dialog data-slabs-bug-reporter="true">`
/// form posting multipart reports (description, default-on viewport screenshot excluding the bug
/// widget itself, up to 3 file attachments, and automatic redacted metadata) to
/// `POST /_slabs/bug-reports`, and loads `/_slabs/vendor/slabs-bug-report.js` externally with zero
/// inline `<script>` or `<style>` tags.
#[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")
}

/// Render a toggleable, CSP-safe user bug reporter widget with a custom trigger `button_label`.
///
/// Returns empty [`Markup`] when `enabled` is `false`. See [`bug_report_widget`] for details.
#[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 {}
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    #[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"));
    }
}