html-safe-md 0.0.1

Convert untrusted HTML to safe markdown. No remote fetches, no scripts, no tracking pixels.
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
//! # html-safe-md
//!
//! Convert untrusted HTML into safe, readable markdown.
//!
//! Built for email but useful anywhere you need to render HTML from an
//! untrusted source without a webview, remote fetches, or JavaScript execution.
//!
//! ## Pipeline
//!
//! ```text
//! untrusted HTML → ammonia (allowlist sanitizer) → html2md (markdown conversion) → safe string
//! ```
//!
//! ## Quick Start
//!
//! ```rust
//! // Sanitize HTML to markdown with default email-tuned config
//! let md = html_safe_md::sanitize_html("<p>Hello <strong>world</strong></p>");
//! assert!(md.contains("**world**"));
//!
//! // Render an email body (prefers plain text, falls back to sanitized HTML)
//! let md = html_safe_md::render_email(
//!     Some("Hey, just following up on our conversation from yesterday.\n\nLet me know."),
//!     Some("<p>HTML version</p>"),
//! );
//! assert!(md.contains("following up"));
//! ```

use std::collections::HashSet;

/// Max HTML input size before truncation (512 KB).
const DEFAULT_MAX_HTML_BYTES: usize = 512 * 1024;

/// Max markdown output length in chars.
const DEFAULT_MAX_MD_CHARS: usize = 200_000;

/// Tags that produce meaningful markdown. Everything else is stripped.
/// Text content inside stripped tags is preserved — only the tags are removed.
const ALLOWED_TAGS: &[&str] = &[
    // Block content
    "p", "br", "hr", "blockquote", "pre",
    // Headings
    "h1", "h2", "h3", "h4", "h5", "h6",
    // Inline formatting
    "b", "strong", "i", "em", "code", "s", "del", "u", "small", "sub", "sup",
    // Lists
    "ul", "ol", "li",
    // Links (ammonia sanitizes href — no javascript: URIs)
    "a",
];

/// Configuration for the sanitizer.
#[derive(Debug, Clone)]
pub struct Config {
    /// Max HTML input size in bytes before truncation.
    pub max_html_bytes: usize,
    /// Max markdown output length in chars.
    pub max_md_chars: usize,
    /// Additional tags to allow beyond the default email set.
    pub extra_tags: HashSet<String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            max_html_bytes: DEFAULT_MAX_HTML_BYTES,
            max_md_chars: DEFAULT_MAX_MD_CHARS,
            extra_tags: HashSet::new(),
        }
    }
}

/// Sanitize untrusted HTML and convert to markdown using the default config.
///
/// Strips all tags except semantic content tags (paragraphs, headings, lists,
/// links, inline formatting). No `<img>`, no `<table>`, no `<style>`, no
/// `<script>`. Text inside stripped tags is preserved.
///
/// # Examples
///
/// ```rust
/// let md = html_safe_md::sanitize_html("<p>Click <a href=\"https://example.com\">here</a></p>");
/// assert!(md.contains("[here](https://example.com)"));
/// ```
pub fn sanitize_html(html: &str) -> String {
    sanitize_html_with(html, &Config::default())
}

/// Sanitize untrusted HTML and convert to markdown with a custom config.
pub fn sanitize_html_with(html: &str, config: &Config) -> String {
    let html = &html[..html.len().min(config.max_html_bytes)];
    let clean = clean_html(html, config);
    let mut md = html2md::parse_html(&clean);
    md.truncate(config.max_md_chars);
    md
}

/// Render an email body as markdown, preferring plain text when available.
///
/// Strategy:
/// 1. If `text_plain` looks like real content, return it as-is.
/// 2. If `text_plain` is junk (stub/tracker), fall through to HTML.
/// 3. Sanitize `text_html` via the ammonia → html2md pipeline.
/// 4. If only junk plain text exists (no HTML), return it anyway.
///
/// # Examples
///
/// ```rust
/// // Plain text preferred when it's real content
/// let md = html_safe_md::render_email(
///     Some("Hey,\n\nThis is a real email with enough content to not be junk.\n\nCheers"),
///     Some("<p>HTML version</p>"),
/// );
/// assert!(md.contains("real email"));
///
/// // Falls back to sanitized HTML when plain is a stub
/// let md = html_safe_md::render_email(
///     Some("View online"),
///     Some("<p>The <strong>actual</strong> newsletter content lives here.</p>"),
/// );
/// assert!(md.contains("actual"));
/// ```
pub fn render_email(text_plain: Option<&str>, text_html: Option<&str>) -> String {
    render_email_with(text_plain, text_html, &Config::default())
}

/// Render an email body as markdown with a custom config.
pub fn render_email_with(
    text_plain: Option<&str>,
    text_html: Option<&str>,
    config: &Config,
) -> String {
    // Prefer plain text when it looks like real content
    if let Some(plain) = text_plain {
        if !is_junk_plain(plain) {
            return plain.to_string();
        }
    }

    // Fall back to sanitized HTML → markdown
    if let Some(html) = text_html {
        return sanitize_html_with(html, config);
    }

    // Plain was junk but there's no HTML — show it anyway
    if let Some(plain) = text_plain {
        return plain.to_string();
    }

    "[No displayable content]".to_string()
}

/// Render an email body as plain text (no markdown formatting).
///
/// Prefers `text_plain` when available; falls back to `html2text` conversion.
pub fn render_email_plain(text_plain: Option<&str>, text_html: Option<&str>) -> String {
    if let Some(plain) = text_plain {
        return plain.to_string();
    }

    if let Some(html) = text_html {
        return html2text::from_read(html.as_bytes(), 80).unwrap_or_default();
    }

    "[No displayable content]".to_string()
}

/// Returns true if the plain-text part looks like a stub or tracking junk
/// rather than real email content.
///
/// Heuristics:
/// - Empty or whitespace-only
/// - Under 40 characters
/// - Two or fewer lines
pub fn is_junk_plain(s: &str) -> bool {
    let t = s.trim();
    t.is_empty() || t.len() < 40 || t.lines().count() <= 2
}

/// Strip HTML down to semantic content using an allowlist.
fn clean_html(html: &str, config: &Config) -> String {
    let mut tags: HashSet<&str> = ALLOWED_TAGS.iter().copied().collect();

    // Extend with any user-configured extra tags
    // (we need to hold the references, so collect owned strings first)
    let extras: Vec<&str> = config.extra_tags.iter().map(|s| s.as_str()).collect();
    tags.extend(extras);

    ammonia::Builder::new().tags(tags).clean(html).to_string()
}

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

    // ── sanitize_html ───────────────────────────────────────────

    #[test]
    fn strips_script_and_style() {
        let html = r#"
            <style>.foo { color: red; }</style>
            <script>alert('xss')</script>
            <p>Safe content</p>
        "#;
        let result = sanitize_html(html);
        assert!(result.contains("Safe content"));
        assert!(!result.contains("color: red"));
        assert!(!result.contains("alert"));
    }

    #[test]
    fn strips_tracking_pixels() {
        let html = r#"<p>Real content</p><img src="https://track.example.com/open.gif" width="1" height="1">"#;
        let result = sanitize_html(html);
        assert!(result.contains("Real content"));
        assert!(!result.contains("track.example.com"));
    }

    #[test]
    fn strips_layout_tables() {
        let html = r#"
            <table><tr><td>
                <p>Actual message</p>
            </td></tr></table>
        "#;
        let result = sanitize_html(html);
        assert!(result.contains("Actual message"));
        assert!(!result.contains("|"));
    }

    #[test]
    fn preserves_links() {
        let html = r#"<p>Click <a href="https://example.com">here</a></p>"#;
        let result = sanitize_html(html);
        assert!(result.contains("https://example.com"));
        assert!(result.contains("here"));
    }

    #[test]
    fn preserves_formatting() {
        let html = "<p>This is <strong>bold</strong> and <em>italic</em></p>";
        let result = sanitize_html(html);
        assert!(result.contains("**bold**") || result.contains("__bold__"));
        assert!(result.contains("*italic*") || result.contains("_italic_"));
    }

    #[test]
    fn preserves_lists() {
        let html = "<ul><li>one</li><li>two</li><li>three</li></ul>";
        let result = sanitize_html(html);
        assert!(result.contains("one"));
        assert!(result.contains("two"));
        assert!(result.contains("three"));
    }

    #[test]
    fn preserves_blockquotes() {
        let html = "<blockquote><p>Quoted text</p></blockquote>";
        let result = sanitize_html(html);
        assert!(result.contains("Quoted text"));
    }

    #[test]
    fn strips_forms() {
        let html = r#"<form action="/phish"><input type="text"><button>Submit</button></form><p>Content</p>"#;
        let result = sanitize_html(html);
        assert!(result.contains("Content"));
        assert!(!result.contains("<form"));
        assert!(!result.contains("<input"));
    }

    #[test]
    fn strips_iframes() {
        let html = r#"<iframe src="https://evil.com"></iframe><p>Content</p>"#;
        let result = sanitize_html(html);
        assert!(result.contains("Content"));
        assert!(!result.contains("evil.com"));
    }

    #[test]
    fn truncates_huge_input() {
        let huge = "<p>".to_string() + &"x".repeat(DEFAULT_MAX_HTML_BYTES + 1000) + "</p>";
        let result = sanitize_html(&huge);
        assert!(result.len() <= DEFAULT_MAX_MD_CHARS);
    }

    #[test]
    fn empty_html_produces_empty_output() {
        let result = sanitize_html("");
        assert!(result.trim().is_empty());
    }

    // ── sanitize_html_with (custom config) ──────────────────────

    #[test]
    fn custom_config_extra_tags() {
        let mut config = Config::default();
        config.extra_tags.insert("img".to_string());
        // With img allowed, it should survive (ammonia will still strip src if not in allowed attrs,
        // but the tag itself won't be stripped)
        let html = r#"<p>Text</p><img alt="photo">"#;
        let result = sanitize_html_with(html, &config);
        // At minimum the tag shouldn't be silently dropped
        assert!(result.contains("Text"));
    }

    #[test]
    fn custom_config_smaller_limits() {
        let config = Config {
            max_html_bytes: 100,
            max_md_chars: 50,
            extra_tags: HashSet::new(),
        };
        let html = "<p>".to_string() + &"word ".repeat(200) + "</p>";
        let result = sanitize_html_with(&html, &config);
        assert!(result.len() <= 50);
    }

    // ── render_email ────────────────────────────────────────────

    #[test]
    fn prefers_real_plain_text() {
        let plain = "Hey,\n\nThis is a real email body with enough content to pass the junk filter.\n\nCheers";
        let html = "<p>HTML version</p>";
        let result = render_email(Some(plain), Some(html));
        assert_eq!(result, plain);
    }

    #[test]
    fn skips_junk_plain_for_html() {
        let junk = "View online";
        let html = "<p>This is the <strong>real</strong> email content right here.</p>";
        let result = render_email(Some(junk), Some(html));
        assert_ne!(result, junk);
        assert!(result.contains("real"));
    }

    #[test]
    fn shows_junk_plain_when_no_html() {
        let junk = "View online";
        let result = render_email(Some(junk), None);
        assert_eq!(result, junk);
    }

    #[test]
    fn no_content_fallback() {
        assert_eq!(render_email(None, None), "[No displayable content]");
    }

    #[test]
    fn html_only_sanitizes() {
        let html = r#"<style>evil</style><p>Good <strong>content</strong></p><img src="tracker.gif">"#;
        let result = render_email(None, Some(html));
        assert!(result.contains("Good"));
        assert!(result.contains("**content**") || result.contains("__content__"));
        assert!(!result.contains("evil"));
        assert!(!result.contains("tracker"));
    }

    // ── render_email_plain ──────────────────────────────────────

    #[test]
    fn plain_text_output_prefers_plain() {
        let result = render_email_plain(Some("Hello, world"), Some("<p>Hello, world</p>"));
        assert_eq!(result, "Hello, world");
    }

    #[test]
    fn plain_text_falls_back_to_html() {
        let result = render_email_plain(None, Some("<p>Hello</p>"));
        assert!(!result.is_empty());
        assert!(result.contains("Hello"));
        assert!(!result.contains("<p>"));
    }

    #[test]
    fn plain_text_no_content() {
        assert_eq!(render_email_plain(None, None), "[No displayable content]");
    }

    // ── is_junk_plain ───────────────────────────────────────────

    #[test]
    fn empty_is_junk() {
        assert!(is_junk_plain(""));
    }

    #[test]
    fn whitespace_only_is_junk() {
        assert!(is_junk_plain("   \n\t  \n  "));
    }

    #[test]
    fn short_stub_is_junk() {
        assert!(is_junk_plain("Click here to view"));
    }

    #[test]
    fn real_content_not_junk() {
        let real = "Hey,\n\nJust wanted to follow up on our conversation from yesterday.\n\nLet me know what you think.\n\nThanks";
        assert!(!is_junk_plain(real));
    }
}