Skip to main content

html_safe_md/
lib.rs

1//! # html-safe-md
2//!
3//! Convert untrusted HTML into safe, readable markdown.
4//!
5//! Built for email but useful anywhere you need to render HTML from an
6//! untrusted source without a webview, remote fetches, or JavaScript execution.
7//!
8//! ## Pipeline
9//!
10//! ```text
11//! untrusted HTML → ammonia (allowlist sanitizer) → html2md (markdown conversion) → safe string
12//! ```
13//!
14//! ## Quick Start
15//!
16//! ```rust
17//! // Sanitize HTML to markdown with default email-tuned config
18//! let md = html_safe_md::sanitize_html("<p>Hello <strong>world</strong></p>");
19//! assert!(md.contains("**world**"));
20//!
21//! // Render an email body (prefers plain text, falls back to sanitized HTML)
22//! let md = html_safe_md::render_email(
23//!     Some("Hey, just following up on our conversation from yesterday.\n\nLet me know."),
24//!     Some("<p>HTML version</p>"),
25//! );
26//! assert!(md.contains("following up"));
27//! ```
28
29use std::collections::HashSet;
30
31/// Max HTML input size before truncation (512 KB).
32const DEFAULT_MAX_HTML_BYTES: usize = 512 * 1024;
33
34/// Max markdown output length in chars.
35const DEFAULT_MAX_MD_CHARS: usize = 200_000;
36
37/// Tags that produce meaningful markdown. Everything else is stripped.
38/// Text content inside stripped tags is preserved — only the tags are removed.
39const ALLOWED_TAGS: &[&str] = &[
40    // Block content
41    "p", "br", "hr", "blockquote", "pre",
42    // Headings
43    "h1", "h2", "h3", "h4", "h5", "h6",
44    // Inline formatting
45    "b", "strong", "i", "em", "code", "s", "del", "u", "small", "sub", "sup",
46    // Lists
47    "ul", "ol", "li",
48    // Links (ammonia sanitizes href — no javascript: URIs)
49    "a",
50];
51
52/// Configuration for the sanitizer.
53#[derive(Debug, Clone)]
54pub struct Config {
55    /// Max HTML input size in bytes before truncation.
56    pub max_html_bytes: usize,
57    /// Max markdown output length in chars.
58    pub max_md_chars: usize,
59    /// Additional tags to allow beyond the default email set.
60    pub extra_tags: HashSet<String>,
61}
62
63impl Default for Config {
64    fn default() -> Self {
65        Self {
66            max_html_bytes: DEFAULT_MAX_HTML_BYTES,
67            max_md_chars: DEFAULT_MAX_MD_CHARS,
68            extra_tags: HashSet::new(),
69        }
70    }
71}
72
73/// Sanitize untrusted HTML and convert to markdown using the default config.
74///
75/// Strips all tags except semantic content tags (paragraphs, headings, lists,
76/// links, inline formatting). No `<img>`, no `<table>`, no `<style>`, no
77/// `<script>`. Text inside stripped tags is preserved.
78///
79/// # Examples
80///
81/// ```rust
82/// let md = html_safe_md::sanitize_html("<p>Click <a href=\"https://example.com\">here</a></p>");
83/// assert!(md.contains("[here](https://example.com)"));
84/// ```
85pub fn sanitize_html(html: &str) -> String {
86    sanitize_html_with(html, &Config::default())
87}
88
89/// Sanitize untrusted HTML and convert to markdown with a custom config.
90pub fn sanitize_html_with(html: &str, config: &Config) -> String {
91    let html = &html[..html.len().min(config.max_html_bytes)];
92    let clean = clean_html(html, config);
93    let mut md = html2md::parse_html(&clean);
94    md.truncate(config.max_md_chars);
95    md
96}
97
98/// Render an email body as markdown, preferring plain text when available.
99///
100/// Strategy:
101/// 1. If `text_plain` looks like real content, return it as-is.
102/// 2. If `text_plain` is junk (stub/tracker), fall through to HTML.
103/// 3. Sanitize `text_html` via the ammonia → html2md pipeline.
104/// 4. If only junk plain text exists (no HTML), return it anyway.
105///
106/// # Examples
107///
108/// ```rust
109/// // Plain text preferred when it's real content
110/// let md = html_safe_md::render_email(
111///     Some("Hey,\n\nThis is a real email with enough content to not be junk.\n\nCheers"),
112///     Some("<p>HTML version</p>"),
113/// );
114/// assert!(md.contains("real email"));
115///
116/// // Falls back to sanitized HTML when plain is a stub
117/// let md = html_safe_md::render_email(
118///     Some("View online"),
119///     Some("<p>The <strong>actual</strong> newsletter content lives here.</p>"),
120/// );
121/// assert!(md.contains("actual"));
122/// ```
123pub fn render_email(text_plain: Option<&str>, text_html: Option<&str>) -> String {
124    render_email_with(text_plain, text_html, &Config::default())
125}
126
127/// Render an email body as markdown with a custom config.
128pub fn render_email_with(
129    text_plain: Option<&str>,
130    text_html: Option<&str>,
131    config: &Config,
132) -> String {
133    // Prefer plain text when it looks like real content
134    if let Some(plain) = text_plain {
135        if !is_junk_plain(plain) {
136            return plain.to_string();
137        }
138    }
139
140    // Fall back to sanitized HTML → markdown
141    if let Some(html) = text_html {
142        return sanitize_html_with(html, config);
143    }
144
145    // Plain was junk but there's no HTML — show it anyway
146    if let Some(plain) = text_plain {
147        return plain.to_string();
148    }
149
150    "[No displayable content]".to_string()
151}
152
153/// Render an email body as plain text (no markdown formatting).
154///
155/// Prefers `text_plain` when available; falls back to `html2text` conversion.
156pub fn render_email_plain(text_plain: Option<&str>, text_html: Option<&str>) -> String {
157    if let Some(plain) = text_plain {
158        return plain.to_string();
159    }
160
161    if let Some(html) = text_html {
162        return html2text::from_read(html.as_bytes(), 80).unwrap_or_default();
163    }
164
165    "[No displayable content]".to_string()
166}
167
168/// Returns true if the plain-text part looks like a stub or tracking junk
169/// rather than real email content.
170///
171/// Heuristics:
172/// - Empty or whitespace-only
173/// - Under 40 characters
174/// - Two or fewer lines
175pub fn is_junk_plain(s: &str) -> bool {
176    let t = s.trim();
177    t.is_empty() || t.len() < 40 || t.lines().count() <= 2
178}
179
180/// Strip HTML down to semantic content using an allowlist.
181fn clean_html(html: &str, config: &Config) -> String {
182    let mut tags: HashSet<&str> = ALLOWED_TAGS.iter().copied().collect();
183
184    // Extend with any user-configured extra tags
185    // (we need to hold the references, so collect owned strings first)
186    let extras: Vec<&str> = config.extra_tags.iter().map(|s| s.as_str()).collect();
187    tags.extend(extras);
188
189    ammonia::Builder::new().tags(tags).clean(html).to_string()
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    // ── sanitize_html ───────────────────────────────────────────
197
198    #[test]
199    fn strips_script_and_style() {
200        let html = r#"
201            <style>.foo { color: red; }</style>
202            <script>alert('xss')</script>
203            <p>Safe content</p>
204        "#;
205        let result = sanitize_html(html);
206        assert!(result.contains("Safe content"));
207        assert!(!result.contains("color: red"));
208        assert!(!result.contains("alert"));
209    }
210
211    #[test]
212    fn strips_tracking_pixels() {
213        let html = r#"<p>Real content</p><img src="https://track.example.com/open.gif" width="1" height="1">"#;
214        let result = sanitize_html(html);
215        assert!(result.contains("Real content"));
216        assert!(!result.contains("track.example.com"));
217    }
218
219    #[test]
220    fn strips_layout_tables() {
221        let html = r#"
222            <table><tr><td>
223                <p>Actual message</p>
224            </td></tr></table>
225        "#;
226        let result = sanitize_html(html);
227        assert!(result.contains("Actual message"));
228        assert!(!result.contains("|"));
229    }
230
231    #[test]
232    fn preserves_links() {
233        let html = r#"<p>Click <a href="https://example.com">here</a></p>"#;
234        let result = sanitize_html(html);
235        assert!(result.contains("https://example.com"));
236        assert!(result.contains("here"));
237    }
238
239    #[test]
240    fn preserves_formatting() {
241        let html = "<p>This is <strong>bold</strong> and <em>italic</em></p>";
242        let result = sanitize_html(html);
243        assert!(result.contains("**bold**") || result.contains("__bold__"));
244        assert!(result.contains("*italic*") || result.contains("_italic_"));
245    }
246
247    #[test]
248    fn preserves_lists() {
249        let html = "<ul><li>one</li><li>two</li><li>three</li></ul>";
250        let result = sanitize_html(html);
251        assert!(result.contains("one"));
252        assert!(result.contains("two"));
253        assert!(result.contains("three"));
254    }
255
256    #[test]
257    fn preserves_blockquotes() {
258        let html = "<blockquote><p>Quoted text</p></blockquote>";
259        let result = sanitize_html(html);
260        assert!(result.contains("Quoted text"));
261    }
262
263    #[test]
264    fn strips_forms() {
265        let html = r#"<form action="/phish"><input type="text"><button>Submit</button></form><p>Content</p>"#;
266        let result = sanitize_html(html);
267        assert!(result.contains("Content"));
268        assert!(!result.contains("<form"));
269        assert!(!result.contains("<input"));
270    }
271
272    #[test]
273    fn strips_iframes() {
274        let html = r#"<iframe src="https://evil.com"></iframe><p>Content</p>"#;
275        let result = sanitize_html(html);
276        assert!(result.contains("Content"));
277        assert!(!result.contains("evil.com"));
278    }
279
280    #[test]
281    fn truncates_huge_input() {
282        let huge = "<p>".to_string() + &"x".repeat(DEFAULT_MAX_HTML_BYTES + 1000) + "</p>";
283        let result = sanitize_html(&huge);
284        assert!(result.len() <= DEFAULT_MAX_MD_CHARS);
285    }
286
287    #[test]
288    fn empty_html_produces_empty_output() {
289        let result = sanitize_html("");
290        assert!(result.trim().is_empty());
291    }
292
293    // ── sanitize_html_with (custom config) ──────────────────────
294
295    #[test]
296    fn custom_config_extra_tags() {
297        let mut config = Config::default();
298        config.extra_tags.insert("img".to_string());
299        // With img allowed, it should survive (ammonia will still strip src if not in allowed attrs,
300        // but the tag itself won't be stripped)
301        let html = r#"<p>Text</p><img alt="photo">"#;
302        let result = sanitize_html_with(html, &config);
303        // At minimum the tag shouldn't be silently dropped
304        assert!(result.contains("Text"));
305    }
306
307    #[test]
308    fn custom_config_smaller_limits() {
309        let config = Config {
310            max_html_bytes: 100,
311            max_md_chars: 50,
312            extra_tags: HashSet::new(),
313        };
314        let html = "<p>".to_string() + &"word ".repeat(200) + "</p>";
315        let result = sanitize_html_with(&html, &config);
316        assert!(result.len() <= 50);
317    }
318
319    // ── render_email ────────────────────────────────────────────
320
321    #[test]
322    fn prefers_real_plain_text() {
323        let plain = "Hey,\n\nThis is a real email body with enough content to pass the junk filter.\n\nCheers";
324        let html = "<p>HTML version</p>";
325        let result = render_email(Some(plain), Some(html));
326        assert_eq!(result, plain);
327    }
328
329    #[test]
330    fn skips_junk_plain_for_html() {
331        let junk = "View online";
332        let html = "<p>This is the <strong>real</strong> email content right here.</p>";
333        let result = render_email(Some(junk), Some(html));
334        assert_ne!(result, junk);
335        assert!(result.contains("real"));
336    }
337
338    #[test]
339    fn shows_junk_plain_when_no_html() {
340        let junk = "View online";
341        let result = render_email(Some(junk), None);
342        assert_eq!(result, junk);
343    }
344
345    #[test]
346    fn no_content_fallback() {
347        assert_eq!(render_email(None, None), "[No displayable content]");
348    }
349
350    #[test]
351    fn html_only_sanitizes() {
352        let html = r#"<style>evil</style><p>Good <strong>content</strong></p><img src="tracker.gif">"#;
353        let result = render_email(None, Some(html));
354        assert!(result.contains("Good"));
355        assert!(result.contains("**content**") || result.contains("__content__"));
356        assert!(!result.contains("evil"));
357        assert!(!result.contains("tracker"));
358    }
359
360    // ── render_email_plain ──────────────────────────────────────
361
362    #[test]
363    fn plain_text_output_prefers_plain() {
364        let result = render_email_plain(Some("Hello, world"), Some("<p>Hello, world</p>"));
365        assert_eq!(result, "Hello, world");
366    }
367
368    #[test]
369    fn plain_text_falls_back_to_html() {
370        let result = render_email_plain(None, Some("<p>Hello</p>"));
371        assert!(!result.is_empty());
372        assert!(result.contains("Hello"));
373        assert!(!result.contains("<p>"));
374    }
375
376    #[test]
377    fn plain_text_no_content() {
378        assert_eq!(render_email_plain(None, None), "[No displayable content]");
379    }
380
381    // ── is_junk_plain ───────────────────────────────────────────
382
383    #[test]
384    fn empty_is_junk() {
385        assert!(is_junk_plain(""));
386    }
387
388    #[test]
389    fn whitespace_only_is_junk() {
390        assert!(is_junk_plain("   \n\t  \n  "));
391    }
392
393    #[test]
394    fn short_stub_is_junk() {
395        assert!(is_junk_plain("Click here to view"));
396    }
397
398    #[test]
399    fn real_content_not_junk() {
400        let real = "Hey,\n\nJust wanted to follow up on our conversation from yesterday.\n\nLet me know what you think.\n\nThanks";
401        assert!(!is_junk_plain(real));
402    }
403}