1use std::collections::HashSet;
30
31const DEFAULT_MAX_HTML_BYTES: usize = 512 * 1024;
33
34const DEFAULT_MAX_MD_CHARS: usize = 200_000;
36
37const ALLOWED_TAGS: &[&str] = &[
40 "p", "br", "hr", "blockquote", "pre",
42 "h1", "h2", "h3", "h4", "h5", "h6",
44 "b", "strong", "i", "em", "code", "s", "del", "u", "small", "sub", "sup",
46 "ul", "ol", "li",
48 "a",
50];
51
52#[derive(Debug, Clone)]
54pub struct Config {
55 pub max_html_bytes: usize,
57 pub max_md_chars: usize,
59 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
73pub fn sanitize_html(html: &str) -> String {
86 sanitize_html_with(html, &Config::default())
87}
88
89pub 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
98pub fn render_email(text_plain: Option<&str>, text_html: Option<&str>) -> String {
124 render_email_with(text_plain, text_html, &Config::default())
125}
126
127pub fn render_email_with(
129 text_plain: Option<&str>,
130 text_html: Option<&str>,
131 config: &Config,
132) -> String {
133 if let Some(plain) = text_plain {
135 if !is_junk_plain(plain) {
136 return plain.to_string();
137 }
138 }
139
140 if let Some(html) = text_html {
142 return sanitize_html_with(html, config);
143 }
144
145 if let Some(plain) = text_plain {
147 return plain.to_string();
148 }
149
150 "[No displayable content]".to_string()
151}
152
153pub 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
168pub 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
180fn clean_html(html: &str, config: &Config) -> String {
182 let mut tags: HashSet<&str> = ALLOWED_TAGS.iter().copied().collect();
183
184 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 #[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 #[test]
296 fn custom_config_extra_tags() {
297 let mut config = Config::default();
298 config.extra_tags.insert("img".to_string());
299 let html = r#"<p>Text</p><img alt="photo">"#;
302 let result = sanitize_html_with(html, &config);
303 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 #[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 #[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 #[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}