wordval-utils 1.0.8

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
Documentation
//! HTML/XSS 净化工具(按需,仅当后端返回用户富文本时需要)
//!
//! # 使用示例
//!
//! ```ignore
//! use wordval_utils::xss;
//!
//! let safe = xss::sanitize_html("<script>alert(1)</script><p>Hello</p>");
//! assert_eq!(safe, "<p>Hello</p>");
//! ```

use ammonia::Builder;

/// 使用默认规则净化 HTML
///
/// 移除 `<script>`、`<style>`、事件属性(`onclick` 等)、
/// javascript: URL 等危险内容,只保留安全标签和属性。
///
/// # 默认允许的标签
///
/// - 文本格式:`b`, `i`, `em`, `strong`, `u`, `s`, `code`, `pre`, `blockquote`
/// - 段落:`p`, `br`, `hr`
/// - 标题:`h1` ~ `h6`
/// - 链接:`a`(仅 `href`, `title`, `target` 属性)
/// - 列表:`ul`, `ol`, `li`
/// - 表格:`table`, `thead`, `tbody`, `tr`, `th`, `td`
/// - 图片:`img`(仅 `src`, `alt`, `width`, `height`)
/// - 容器:`div`, `span`
pub fn sanitize_html(html: &str) -> String {
    Builder::default().clean(html).to_string()
}

/// 使用严格规则净化 HTML(仅保留基本文本格式标签)
///
/// 允许的标签:`b`、`i`、`em`、`strong`、`u`、`s`、`code`、`pre`、`br`、`p`;
/// 其余标签移除,所有属性清除。
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()
}

/// 检查 HTML 中是否包含潜在 XSS 载荷
///
/// 返回 `true` 表示可能包含恶意内容(需要净化处理)。
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}");
        // javascript: URL 被移除
        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>"));
    }
}