use axum::response::{IntoResponse, Response};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use chrono::Utc;
use http::{header, HeaderMap, HeaderValue, StatusCode};
use rand_core::{OsRng, RngCore};
use serde::{Deserialize, Serialize};
use slabs_auth::Auth;
use slabs_core::{SlabError, SlabResult};
pub use maud::{html, Markup, PreEscaped, Render, DOCTYPE};
pub const FLASH_COOKIE_NAME: &str = "slabs_flash";
pub const SW_REGISTER_JS: &str = r#"if ("serviceWorker" in navigator) { window.addEventListener("load", function() { navigator.serviceWorker.register("/sw.js").catch(function() {}); }); }"#;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FlashKind {
Success,
Info,
Warning,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Flash {
pub kind: FlashKind,
pub message: String,
}
impl Flash {
#[must_use]
pub fn success(message: impl Into<String>) -> Self {
Self {
kind: FlashKind::Success,
message: message.into(),
}
}
#[must_use]
pub fn info(message: impl Into<String>) -> Self {
Self {
kind: FlashKind::Info,
message: message.into(),
}
}
#[must_use]
pub fn warning(message: impl Into<String>) -> Self {
Self {
kind: FlashKind::Warning,
message: message.into(),
}
}
#[must_use]
pub fn error(message: impl Into<String>) -> Self {
Self {
kind: FlashKind::Error,
message: message.into(),
}
}
}
fn is_safe_relative_path(path: &str) -> bool {
path.starts_with('/')
&& !path.starts_with("//")
&& !path.starts_with("/\\")
&& !path.contains('\\')
&& !path.bytes().any(|b| b < 0x20 || b == 0x7f)
}
pub fn redirect_external(url: &str) -> SlabResult<Response> {
let trimmed = url.trim();
if trimmed.bytes().any(|b| b < 0x20 || b == 0x7f) {
return Err(SlabError::bad_request(
"redirect URL must not contain control characters",
));
}
let lower = trimmed.to_ascii_lowercase();
let is_http = (lower.starts_with("http://") && trimmed.len() > "http://".len())
|| (lower.starts_with("https://") && trimmed.len() > "https://".len());
if !is_http {
return Err(SlabError::bad_request(
"external redirect URL must start with http:// or https://",
));
}
let target = HeaderValue::from_str(trimmed)
.map_err(|_| SlabError::bad_request("invalid redirect URL header value"))?;
let mut headers = HeaderMap::new();
headers.insert(header::LOCATION, target.clone());
headers.insert("hx-redirect", target);
Ok((StatusCode::SEE_OTHER, headers).into_response())
}
pub fn escape(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(ch),
}
}
out
}
pub fn json_script<T: Serialize>(id: &str, value: &T) -> SlabResult<Markup> {
let raw = serde_json::to_string(value)
.map_err(|e| SlabError::internal(format!("json_script serialize failed: {e}")))?;
let mut safe = String::with_capacity(raw.len());
for ch in raw.chars() {
match ch {
'<' => safe.push_str("\\u003c"),
'>' => safe.push_str("\\u003e"),
'&' => safe.push_str("\\u0026"),
'\u{2028}' => safe.push_str("\\u2028"),
'\u{2029}' => safe.push_str("\\u2029"),
_ => safe.push(ch),
}
}
Ok(html! {
script type="application/json" id=(id) { (PreEscaped(safe)) }
})
}
pub mod htmx {
use super::{
header, html, is_safe_relative_path, Auth, Cookie, CookieJar, Deserialize, Flash,
FlashKind, HeaderMap, HeaderValue, IntoResponse, Markup, PreEscaped, Response, SameSite,
Serialize, StatusCode, Utc, FLASH_COOKIE_NAME, URL_SAFE_NO_PAD,
};
use base64::Engine as _;
#[derive(Serialize, Deserialize)]
struct FlashEnvelope {
kind: FlashKind,
message: String,
exp: i64,
}
fn sanitize_dom_id(target_id: &str) -> String {
let clean: String = target_id
.trim_start_matches('#')
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
.collect();
if clean.is_empty() {
"oob".to_string()
} else {
clean
}
}
fn sanitize_swap(swap: &str) -> &'static str {
match swap {
"innerHTML" => "innerHTML",
"beforebegin" => "beforebegin",
"afterbegin" => "afterbegin",
"beforeend" => "beforeend",
"afterend" => "afterend",
"delete" => "delete",
"none" => "none",
_ => "outerHTML",
}
}
#[must_use = "return the updated CookieJar in your response so the flash cookie is sent"]
pub fn set_flash(auth: &Auth, jar: CookieJar, flash: &Flash) -> CookieJar {
let envelope = FlashEnvelope {
kind: flash.kind,
message: flash.message.clone(),
exp: Utc::now().timestamp() + 60,
};
let Ok(json) = serde_json::to_vec(&envelope) else {
return jar;
};
let encoded = URL_SAFE_NO_PAD.encode(json);
let sig = auth.sign_with_domain("flash:v1", &encoded);
let cookie = Cookie::build((FLASH_COOKIE_NAME, format!("{encoded}.{sig}")))
.path("/")
.http_only(true)
.same_site(SameSite::Lax)
.secure(auth.cookie_secure())
.max_age(time::Duration::seconds(60))
.build();
jar.add(cookie)
}
#[must_use = "return the updated CookieJar in your response so the flash cookie is cleared"]
pub fn take_flash(auth: &Auth, jar: CookieJar) -> (CookieJar, Option<Flash>) {
let Some(raw) = jar.get(FLASH_COOKIE_NAME).map(|c| c.value().to_string()) else {
return (jar, None);
};
let removal = Cookie::build((FLASH_COOKIE_NAME, ""))
.path("/")
.http_only(true)
.same_site(SameSite::Lax)
.secure(auth.cookie_secure())
.build();
let jar = jar.remove(removal);
let flash = decode_flash(auth, &raw);
(jar, flash)
}
pub fn flash_redirect(auth: &Auth, jar: CookieJar, location: &str, flash: &Flash) -> Response {
let jar = set_flash(auth, jar, flash);
let safe_location = if is_safe_relative_path(location) {
location
} else {
"/"
};
let target =
HeaderValue::from_str(safe_location).unwrap_or_else(|_| HeaderValue::from_static("/"));
let mut headers = HeaderMap::new();
headers.insert(header::LOCATION, target.clone());
headers.insert("hx-redirect", target);
(StatusCode::SEE_OTHER, jar, headers).into_response()
}
fn decode_flash(auth: &Auth, raw: &str) -> Option<Flash> {
let (encoded, sig) = raw.split_once('.')?;
if encoded.is_empty() || sig.is_empty() || sig.contains('.') {
return None;
}
if !auth.verify_with_domain("flash:v1", encoded, sig) {
return None;
}
let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?;
let envelope: FlashEnvelope = serde_json::from_slice(&bytes).ok()?;
if envelope.exp < Utc::now().timestamp() {
return None;
}
Some(Flash {
kind: envelope.kind,
message: envelope.message,
})
}
pub fn redirect(path: &str) -> Response {
let safe_path = if is_safe_relative_path(path) {
path
} else {
"/"
};
let mut headers = HeaderMap::new();
headers.insert(
"hx-redirect",
HeaderValue::from_str(safe_path).unwrap_or_else(|_| HeaderValue::from_static("/")),
);
(StatusCode::OK, headers).into_response()
}
pub fn with_trigger(markup: Markup, event: &str) -> Response {
let mut headers = HeaderMap::new();
if let Ok(val) = HeaderValue::from_str(event) {
headers.insert("hx-trigger", val);
}
(StatusCode::OK, headers, markup).into_response()
}
pub fn oob(target_id: &str, swap: &str, inner: Markup) -> Markup {
let clean_id = sanitize_dom_id(target_id);
let safe_swap = sanitize_swap(swap);
let attr = format!("{safe_swap}:#{clean_id}");
html! {
div hx-swap-oob=(attr) { (PreEscaped(inner.into_string())) }
}
}
pub fn oob_delete(target_id: &str) -> Markup {
let clean_id = sanitize_dom_id(target_id);
html! {
div id=(clean_id) hx-swap-oob="delete" {}
}
}
pub fn oob_replace(target_id: &str, inner: Markup) -> Markup {
let clean_id = sanitize_dom_id(target_id);
html! {
div hx-swap-oob=(format!("outerHTML:#{clean_id}")) { (PreEscaped(inner.into_string())) }
}
}
pub fn is_htmx(headers: &HeaderMap) -> bool {
headers
.get("hx-request")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v == "true")
}
pub fn wants_json(headers: &HeaderMap) -> bool {
headers
.get(header::ACCEPT)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("application/json"))
}
}
#[must_use]
pub fn flash_banner(flash: Option<&Flash>) -> Markup {
let Some(flash) = flash else {
return html! {};
};
let (kind_str, variant) = match flash.kind {
FlashKind::Success => ("success", None),
FlashKind::Info => ("info", None),
FlashKind::Warning => ("warning", None),
FlashKind::Error => ("error", Some("destructive")),
};
html! {
div class="alert" role="status" data-flash-kind=(kind_str) data-variant=[variant] {
section {
p { (flash.message) }
}
}
}
}
pub fn document(title: &str, stylesheets: &[String], scripts: &[String], body: Markup) -> Markup {
html! {
(DOCTYPE)
html lang="en" class="dark" {
head {
meta charset="utf-8";
meta name="viewport" content="width=device-width, initial-scale=1";
link rel="manifest" href="/manifest.webmanifest";
meta name="theme-color" content="#1a1b26";
meta name="apple-mobile-web-app-capable" content="yes";
title { (title) }
link rel="stylesheet" href="/_slabs/vendor/basecoat.min.css";
@for href in stylesheets {
link rel="stylesheet" href=(href);
}
script src="/_slabs/vendor/htmx.min.js" defer {}
script src="/_slabs/vendor/htmx-ext-sse.js" defer {}
script src="/_slabs/vendor/idiomorph-ext.min.js" defer {}
script src="/_slabs/vendor/basecoat.min.js" defer {}
script src="/_slabs/vendor/alpine.min.js" defer {}
@for src in scripts {
script type="module" src=(src) defer {}
}
}
body class="min-h-screen bg-background text-foreground antialiased" hx-ext="morph" {
(PreEscaped(body.into_string()))
script src="/_slabs/vendor/sw-register.js" defer {}
}
}
}
}
pub fn csrf_token(auth: &Auth, scope: &str) -> String {
let mut nonce_bytes = [0u8; 16];
OsRng.fill_bytes(&mut nonce_bytes);
let nonce = hex::encode(nonce_bytes);
let exp = Utc::now().timestamp() + 4 * 3600;
let payload = format!("{scope}\0{exp}\0{nonce}");
let sig = auth.sign_with_domain("csrf:v1", &payload);
format!("{exp}.{nonce}.{sig}")
}
pub fn verify_csrf(auth: &Auth, scope: &str, token: &str) -> SlabResult<()> {
let mut parts = token.split('.');
let (Some(exp_str), Some(nonce), Some(sig), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return Err(SlabError::forbidden("invalid csrf token format"));
};
if nonce.len() != 32 || !nonce.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(SlabError::forbidden("invalid csrf token format"));
}
let exp: i64 = exp_str
.parse()
.map_err(|_| SlabError::forbidden("invalid csrf token format"))?;
if Utc::now().timestamp() > exp {
return Err(SlabError::forbidden("csrf token expired"));
}
let payload = format!("{scope}\0{exp}\0{nonce}");
if auth.verify_with_domain("csrf:v1", &payload, sig) {
Ok(())
} else {
Err(SlabError::forbidden("csrf token verification failed"))
}
}
pub fn render_markdown(input: &str) -> Markup {
use pulldown_cmark::{Event, LinkType, Options, Parser, Tag, TagEnd};
let mut options = Options::empty();
options.insert(Options::ENABLE_TABLES);
options.insert(Options::ENABLE_STRIKETHROUGH);
options.insert(Options::ENABLE_TASKLISTS);
let parser = Parser::new_ext(input, options).filter_map(|event| match event {
Event::Html(_) | Event::InlineHtml(_) => None,
Event::Start(Tag::Link {
link_type,
dest_url,
title,
..
}) => {
let candidate = if link_type == LinkType::Email
&& !dest_url.trim().to_ascii_lowercase().starts_with("mailto:")
{
format!("mailto:{}", dest_url.trim())
} else {
dest_url.to_string()
};
let href = escape(&sanitize_url(&candidate));
let open_tag = if title.is_empty() {
format!("<a href=\"{href}\" rel=\"noopener noreferrer ugc\">")
} else {
format!(
"<a href=\"{href}\" title=\"{}\" rel=\"noopener noreferrer ugc\">",
escape(&title)
)
};
Some(Event::Html(open_tag.into()))
}
Event::End(TagEnd::Link) => Some(Event::Html("</a>".into())),
Event::Start(Tag::Image {
link_type,
dest_url,
title,
id,
}) => Some(Event::Start(Tag::Image {
link_type,
dest_url: sanitize_url(&dest_url).into(),
title,
id,
})),
other => Some(other),
});
let mut html_out = String::with_capacity(input.len() + 64);
pulldown_cmark::html::push_html(&mut html_out, parser);
PreEscaped(html_out)
}
fn sanitize_url(raw: &str) -> String {
let trimmed = raw.trim();
if trimmed.is_empty()
|| trimmed.bytes().any(|b| b <= 0x1f || b == 0x7f)
|| trimmed.starts_with("//")
|| trimmed.starts_with("/\\")
{
return "#".to_string();
}
let lower = trimmed.to_ascii_lowercase();
if lower.starts_with("http://")
|| lower.starts_with("https://")
|| lower.starts_with("mailto:")
|| lower.starts_with('/')
|| lower.starts_with('#')
|| !lower.contains(':')
{
trimmed.to_string()
} else {
"#".to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_markdown_renders_gfm_adds_rel_and_blocks_xss_and_heading_attrs() {
let md = "# Title\n\n# Hi {x-init=alert(1)}\n\n<script>alert(1)</script>\n<div hx-get=\"/evil\" x-init=\"pwn()\">bad</div>\n\n[ok](https://example.com) and [bad](javascript:alert(1)) and [proto](//evil.com) and [slash](/\\evil.com) and [ctrl](java	script:alert(1))\n\n| A | B |\n| - | - |\n| 1 | 2 |\n";
let rendered = render_markdown(md).into_string();
assert!(rendered.contains("<h1>Title</h1>"));
assert!(rendered.contains("<h1>Hi {x-init=alert(1)}</h1>"));
assert!(!rendered.contains("<h1 "));
assert!(rendered.contains("<table>"));
assert!(rendered
.contains("<a href=\"https://example.com\" rel=\"noopener noreferrer ugc\">ok</a>"));
assert!(!rendered.contains("<script>"));
assert!(!rendered.contains("hx-get"));
assert!(!rendered.contains("x-init=\"pwn()\""));
assert!(!rendered.contains("javascript:"));
assert!(!rendered.contains("href=\"//evil.com\""));
assert!(!rendered.contains("href=\"/\\evil.com\""));
assert!(!rendered.contains("java\tscript:"));
assert_eq!(sanitize_url("https://example.com/\x01bad"), "#");
assert_eq!(sanitize_url("https://example.com/\x7fbad"), "#");
}
#[test]
fn render_markdown_heading_attributes_disabled_no_x_init_attr() {
let rendered = render_markdown("# Hi {x-init=alert(1)}").into_string();
assert!(rendered.contains("<h1>Hi {x-init=alert(1)}</h1>"));
assert!(!rendered.contains("<h1 "));
}
#[test]
fn safe_redirects_block_open_redirects_and_allow_relative_paths() {
let auth = Auth::for_signing("test-redirect-secret-key", false);
for unsafe_target in [
"https://evil.com",
"//evil.com",
"/\\evil.com",
"/foo\\bar",
"/ok\r\nSet-Cookie: a=b",
"relative/path",
] {
let r1 = htmx::redirect(unsafe_target);
assert_eq!(
r1.headers()
.get("hx-redirect")
.and_then(|v| v.to_str().ok()),
Some("/"),
"redirect should reject {unsafe_target:?}"
);
let r2 =
htmx::flash_redirect(&auth, CookieJar::new(), unsafe_target, &Flash::info("hi"));
assert_eq!(
r2.headers()
.get(header::LOCATION)
.and_then(|v| v.to_str().ok()),
Some("/"),
"flash_redirect should reject {unsafe_target:?}"
);
}
let ok = htmx::redirect("/rooms/42?tab=chat");
assert_eq!(
ok.headers()
.get("hx-redirect")
.and_then(|v| v.to_str().ok()),
Some("/rooms/42?tab=chat")
);
}
#[test]
fn redirect_external_allows_http_https_only() {
let ok = redirect_external("https://example.com/callback?ok=1").unwrap();
assert_eq!(ok.status(), StatusCode::SEE_OTHER);
assert_eq!(
ok.headers()
.get(header::LOCATION)
.and_then(|v| v.to_str().ok()),
Some("https://example.com/callback?ok=1")
);
assert!(redirect_external("javascript:alert(1)").is_err());
assert!(redirect_external("/relative").is_err());
assert!(redirect_external("https://example.com/\r\nbad").is_err());
assert!(redirect_external("https://").is_err());
}
#[test]
fn csrf_token_roundtrip_and_expiration_and_tamper_rejection() {
let auth = Auth::for_signing("test-csrf-secret-key", false);
let token = csrf_token(&auth, "ses_123");
let parts: Vec<&str> = token.split('.').collect();
assert_eq!(parts.len(), 3);
assert_eq!(parts[1].len(), 32);
verify_csrf(&auth, "ses_123", &token).expect("valid csrf token");
assert!(verify_csrf(&auth, "ses_other", &token).is_err());
assert!(verify_csrf(&auth, "ses_123", "not-a-valid-token").is_err());
let expired_exp = Utc::now().timestamp() - 10;
let nonce = "0123456789abcdef0123456789abcdef";
let sig = auth.sign_with_domain("csrf:v1", &format!("ses_123\0{expired_exp}\0{nonce}"));
let expired = format!("{expired_exp}.{nonce}.{sig}");
assert!(verify_csrf(&auth, "ses_123", &expired).is_err());
}
#[test]
fn flash_roundtrip_max_age_and_expiration() {
use base64::Engine as _;
let auth = Auth::for_signing("test-flash-secret-key", false);
let flash = Flash::success("Saved changes.");
let jar = htmx::set_flash(&auth, CookieJar::new(), &flash);
let cookie = jar.get(FLASH_COOKIE_NAME).expect("flash cookie set");
assert_eq!(cookie.path(), Some("/"));
assert_eq!(cookie.http_only(), Some(true));
assert_eq!(cookie.same_site(), Some(SameSite::Lax));
assert_eq!(cookie.max_age(), Some(time::Duration::seconds(60)));
let (jar, taken) = htmx::take_flash(&auth, jar);
assert_eq!(taken, Some(flash));
assert!(jar.get(FLASH_COOKIE_NAME).is_none());
let (_jar, second) = htmx::take_flash(&auth, jar);
assert_eq!(second, None);
let expired_json = serde_json::json!({
"kind": "info",
"message": "stale",
"exp": Utc::now().timestamp() - 5,
});
let encoded = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&expired_json).unwrap());
let sig = auth.sign_with_domain("flash:v1", &encoded);
let mut headers = HeaderMap::new();
headers.insert(
header::COOKIE,
HeaderValue::from_str(&format!("{FLASH_COOKIE_NAME}={encoded}.{sig}")).unwrap(),
);
let expired_jar = CookieJar::from_headers(&headers);
let (_cleared, result) = htmx::take_flash(&auth, expired_jar);
assert_eq!(result, None);
}
#[test]
fn flash_rejects_tampered_cookie_and_clears_it() {
let auth = Auth::for_signing("test-flash-secret-key", false);
let jar = htmx::set_flash(&auth, CookieJar::new(), &Flash::info("Hello"));
let raw = jar.get(FLASH_COOKIE_NAME).unwrap().value().to_string();
let (encoded, sig) = raw.split_once('.').unwrap();
let flipped = if sig.starts_with('0') { '1' } else { '0' };
let tampered = format!("{encoded}.{flipped}{}", &sig[1..]);
let mut tampered_headers = HeaderMap::new();
tampered_headers.insert(
header::COOKIE,
HeaderValue::from_str(&format!("{FLASH_COOKIE_NAME}={tampered}")).unwrap(),
);
let tampered_jar = CookieJar::from_headers(&tampered_headers);
let (cleared_jar, taken) = htmx::take_flash(&auth, tampered_jar);
assert_eq!(taken, None);
assert!(cleared_jar.get(FLASH_COOKIE_NAME).is_none());
}
#[test]
fn flash_redirect_sets_see_other_location_hx_redirect_and_cookie() {
let auth = Auth::for_signing("test-flash-secret-key", false);
let resp = htmx::flash_redirect(
&auth,
CookieJar::new(),
"/rooms",
&Flash::warning("Room archived"),
);
assert_eq!(resp.status(), StatusCode::SEE_OTHER);
assert_eq!(
resp.headers()
.get(header::LOCATION)
.and_then(|v| v.to_str().ok()),
Some("/rooms")
);
assert_eq!(
resp.headers()
.get("hx-redirect")
.and_then(|v| v.to_str().ok()),
Some("/rooms")
);
let set_cookie = resp
.headers()
.get(header::SET_COOKIE)
.and_then(|v| v.to_str().ok())
.expect("Set-Cookie header present");
assert!(set_cookie.contains("slabs_flash="));
assert!(set_cookie.contains("HttpOnly"));
assert!(set_cookie.contains("SameSite=Lax"));
assert!(set_cookie.contains("Path=/"));
assert!(set_cookie.contains("Max-Age=60"));
}
#[test]
fn oob_sanitizes_id_and_swap_strategy() {
let rendered =
htmx::oob("#list\" onclick=\"x", "evilSwap", html! { p { "ok" } }).into_string();
assert!(rendered.contains("hx-swap-oob=\"outerHTML:#listonclickx\""));
let empty_id = htmx::oob_replace("!!!", html! { p { "ok" } }).into_string();
assert!(empty_id.contains("hx-swap-oob=\"outerHTML:#oob\""));
let valid_swap =
htmx::oob("messages_1-a", "beforeend", html! { li { "hi" } }).into_string();
assert!(valid_swap.contains("hx-swap-oob=\"beforeend:#messages_1-a\""));
}
#[test]
fn flash_banner_renders_accessible_alert_or_empty() {
assert_eq!(flash_banner(None).into_string(), "");
let ok_html = flash_banner(Some(&Flash::success("Item <saved>"))).into_string();
assert!(ok_html.contains("class=\"alert\""));
assert!(ok_html.contains("role=\"status\""));
assert!(ok_html.contains("data-flash-kind=\"success\""));
assert!(ok_html.contains("Item <saved>"));
assert!(!ok_html.contains("data-variant=\"destructive\""));
let err_html = flash_banner(Some(&Flash::error("Failed"))).into_string();
assert!(err_html.contains("role=\"status\""));
assert!(err_html.contains("data-flash-kind=\"error\""));
assert!(err_html.contains("data-variant=\"destructive\""));
assert!(err_html.contains("Failed"));
}
#[test]
fn document_is_csp_friendly_with_zero_inline_scripts_or_styles() {
let rendered = document("Campfire", &[], &[], html! { main { "Hi" } }).into_string();
assert!(rendered.contains("<link rel=\"manifest\" href=\"/manifest.webmanifest\">"));
assert!(rendered.contains("<meta name=\"theme-color\" content=\"#1a1b26\">"));
assert!(rendered.contains("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">"));
assert!(rendered.contains("<script src=\"/_slabs/vendor/sw-register.js\" defer></script>"));
assert!(!rendered.contains("<style"));
assert!(!rendered.contains("<script>"));
}
#[test]
fn json_script_escapes_script_breakout_and_line_separators() {
let payload = serde_json::json!({
"html": "</script><img src=x>&",
"sep": "a\u{2028}b\u{2029}c",
});
let rendered = json_script("boot-data", &payload).unwrap().into_string();
assert!(rendered.starts_with("<script type=\"application/json\" id=\"boot-data\">"));
assert!(rendered.ends_with("</script>"));
assert!(!rendered.contains("</script><img"));
assert!(rendered.contains("\\u003c/script\\u003e\\u003cimg src=x\\u003e\\u0026"));
assert!(rendered.contains("\\u2028"));
assert!(rendered.contains("\\u2029"));
}
}