use ammonia::Builder;
pub fn sanitize_html(html: &str) -> String {
Builder::default().clean(html).to_string()
}
pub fn sanitize_html_strict(html: &str) -> String {
use std::collections::HashSet;
let allowed: HashSet<&str> = ["b", "i", "em", "strong", "u", "s", "code", "pre", "br", "p"]
.into_iter()
.collect();
Builder::default().tags(allowed).clean(html).to_string()
}
pub fn has_potential_xss(html: &str) -> bool {
let cleaned = Builder::default().clean(html).to_string();
cleaned.len() < html.len() || cleaned != html
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanitize_strips_script() {
let out = sanitize_html("<script>alert(1)</script><p>Hello</p>");
assert!(!out.contains("script"), "{out}");
assert!(out.contains("<p>Hello</p>"));
}
#[test]
fn sanitize_keeps_safe_tags_and_strips_events() {
let out = sanitize_html(r#"<a href="http://x.com" onclick="evil()">l</a>"#);
assert!(out.contains("<a"));
assert!(!out.contains("onclick"), "{out}");
let out2 = sanitize_html(r#"<a href="javascript:alert(1)">j</a>"#);
assert!(!out2.contains("javascript"), "{out2}");
}
#[test]
fn strict_removes_all_but_basic_format() {
let out = sanitize_html_strict("<p>ok</p><table><tr><td>x</td></tr></table><b>b</b>");
assert!(out.contains("<p>ok</p>"));
assert!(out.contains("<b>b</b>"));
assert!(!out.contains("table"), "{out}");
assert!(!out.contains("td"), "{out}");
let out2 = sanitize_html_strict(r#"<b title="t">x</b>"#);
assert!(!out2.contains("title"), "{out2}");
}
#[test]
fn has_potential_xss_detects() {
assert!(has_potential_xss("<script>x</script>"));
assert!(!has_potential_xss("plain text")); assert!(has_potential_xss("<p onclick=\"e()\">a</p>"));
}
}