Skip to main content

hypermail/
html.rs

1use std::path::PathBuf;
2
3use crate::config::{Config, DELETE_LEAVES_STUBS, DELETE_LEAVES_TEXT};
4use crate::date::{get_date_str, secs_to_iso};
5use crate::error::Result;
6use crate::file_utils::{
7    message_name, message_path as utils_message_path, message_url_str, msg_subdir,
8};
9use crate::headers::decode_mime_words;
10use crate::i18n::I18n;
11use crate::message::EmailInfo;
12use crate::string_utils::{obfuscate_email_address, spamify};
13use crate::structs::EmailStore;
14use crate::templates::{
15    default_article_template, default_footer_template, default_header_template, get_header_cookies,
16    set_cookie, substitute_cookies, substitute_printfile, PrintfileData,
17};
18use crate::txt2html::escape_html;
19
20/// Renders a complete HTML page for a single email message.
21pub fn print_article(email: &EmailInfo, store: &EmailStore, config: &Config) -> Result<String> {
22    // This page is written inside the message's own folder (if any), so
23    // message_url_str() must omit that folder prefix for any link rendered
24    // here (e.g. reply links) — otherwise a reply in the same folder would
25    // link to `folder/0003.html` which 404s as `folder/folder/0003.html`.
26    let config = &with_own_subdir(email, config);
27
28    // If delete_level < DELETE_LEAVES_TEXT, show "Deleted message" stub
29    // If delete_level >= DELETE_LEAVES_TEXT, show the actual message content
30    if email.is_deleted != 0 && config.delete_level < DELETE_LEAVES_TEXT {
31        return print_deleted_article(email, store, config);
32    }
33
34    let article_html = generate_article_email(email, store, config)?;
35
36    render_message_page(email, config, &article_html)
37}
38
39/// Returns a config clone with `current_output_subdir` set to `email`'s own
40/// folder, so `message_url_str()` omits the prefix for links rendered on
41/// `email`'s own article page.
42fn with_own_subdir(email: &EmailInfo, config: &Config) -> Config {
43    let mut config = config.clone();
44    if let Some(sub) = msg_subdir(email, &config) {
45        let subdir = sub.subdir.trim_end_matches('/');
46        if !subdir.is_empty() {
47            config.current_output_subdir = Some(subdir.to_string());
48        }
49    }
50    config
51}
52
53fn load_template_or_default(path: Option<&str>, default: &str) -> String {
54    path.and_then(|p| std::fs::read_to_string(p).ok())
55        .unwrap_or_else(|| default.to_string())
56}
57
58/// Render a complete message HTML page, using external templates (mhtmlheader/mhtmlfooter)
59/// with printfile-style %x substitution when configured, or the default internal templates.
60fn render_message_page(email: &EmailInfo, config: &Config, article_html: &str) -> Result<String> {
61    if config.mhtmlheader.is_some() || config.mhtmlfooter.is_some() {
62        // External templates: use original hypermail printfile-style %x substitution.
63        let header_tpl = config
64            .mhtmlheader
65            .as_deref()
66            .and_then(|p| std::fs::read_to_string(p).ok())
67            .unwrap_or_default();
68        let footer_tpl = config
69            .mhtmlfooter
70            .as_deref()
71            .and_then(|p| std::fs::read_to_string(p).ok())
72            .unwrap_or_default();
73
74        let date_str = if email.date > 0 {
75            secs_to_iso(email.date)
76        } else {
77            String::new()
78        };
79        let display_date_str = if email.date > 0 {
80            get_date_str(
81                email.date,
82                config.dateformat.as_deref(),
83                config.gmtime,
84                config.eurodate,
85                config.isodate,
86                &config.language,
87            )
88        } else {
89            String::new()
90        };
91        let filename = message_url_str(email, config);
92        let i18n = I18n::new(&config.language);
93        let raw_subject = email.subject.as_deref().unwrap_or(i18n.get("no subject"));
94        let decoded_subject = format_subject_for_index(raw_subject, config);
95        let decoded_name = decode_mime_words(email.name.as_deref().unwrap_or(""));
96        let data = PrintfileData {
97            label: config.label.as_deref().unwrap_or(""),
98            subject: &decoded_subject,
99            dir: config.dir.as_deref().unwrap_or("."),
100            name: Some(decoded_name.as_str()),
101            email: email.email_addr.as_deref(),
102            msgid: email.msgid.as_deref(),
103            charset: email.charset.as_deref(),
104            date: if date_str.is_empty() {
105                None
106            } else {
107                Some(date_str.as_str())
108            },
109            display_date: if display_date_str.is_empty() {
110                None
111            } else {
112                Some(display_date_str.as_str())
113            },
114            filename: Some(filename.as_str()),
115            archives: config.archives.as_deref(),
116            about: config.about.as_deref(),
117            mailto: config.mailto.as_deref(),
118            language: &config.language,
119            rel_path_to_top: "",
120        };
121
122        let header_html = substitute_printfile(&header_tpl, &data);
123        let footer_html = substitute_printfile(&footer_tpl, &data);
124        let generator = if config.showgenerator {
125            let i18n = I18n::new(&config.language);
126            let gen_text = crate::txt2html::escape_html(i18n.get("Generated by"));
127            format!(
128                "\n<p class=\"hm-generator\">{} <a href=\"https://hypermail-rs.github.io\">hypermail-rs</a></p>\n",
129                gen_text
130            )
131        } else {
132            String::new()
133        };
134        Ok(format!("{}{}{}{}", header_html, article_html, footer_html, generator))
135    } else {
136        // Internal default templates: use %COOKIE_NAME% substitution.
137        let i18n = I18n::new(&config.language);
138        let subject_raw = email.subject.as_deref().unwrap_or(i18n.get("no subject"));
139        let subject = &format_subject_for_index(subject_raw, config);
140        let mut cookies = get_header_cookies(config, subject);
141        set_cookie(&mut cookies, "ARTICLE", article_html);
142
143        if email.is_deleted != 0 && email.is_deleted & 2 != 0 {
144            set_cookie(&mut cookies, "DELETED_NOTE", i18n.get("Expired message"));
145            set_cookie(&mut cookies, "DELETED_HTML", "");
146        } else if email.is_deleted != 0 {
147            set_cookie(&mut cookies, "DELETED_NOTE", i18n.get("Deleted message"));
148            set_cookie(&mut cookies, "DELETED_HTML", "");
149        }
150
151        let header_template = load_template_or_default(None, default_header_template());
152        let footer_template = load_template_or_default(None, default_footer_template());
153        let article_template = default_article_template();
154
155        let header_html = substitute_cookies(&header_template, &cookies);
156        let article_content = substitute_cookies(article_template, &cookies);
157        let mut nav_cookies = cookies.clone();
158        set_cookie(&mut nav_cookies, "NAVIGATION", "");
159        let footer_html = substitute_cookies(&footer_template, &nav_cookies);
160        Ok(format!("{}{}{}", header_html, article_content, footer_html))
161    }
162}
163
164fn print_deleted_article(
165    email: &EmailInfo,
166    _store: &EmailStore,
167    config: &Config,
168) -> Result<String> {
169    let note = if email.is_deleted & 2 != 0 {
170        let i18n = I18n::new(&config.language);
171        i18n.get("Expired message").to_string()
172    } else {
173        let i18n = I18n::new(&config.language);
174        i18n.get("Deleted message").to_string()
175    };
176    let mut article_html = String::new();
177    article_html.push_str(&format!("<p class=\"hm-deleted\">{}</p>\n", note));
178
179    render_message_page(email, config, &article_html)
180}
181
182fn generate_article_email(
183    email: &EmailInfo,
184    store: &EmailStore,
185    config: &Config,
186) -> Result<String> {
187    let i18n = I18n::new(&config.language);
188    let mut html = String::new();
189
190    html.push_str(&format!(
191        "<article id=\"{}{}\">\n",
192        escape_html(&config.fragment_prefix),
193        email.msgnum
194    ));
195
196    if config.showheaders {
197        html.push_str("<table class=\"hm-msg-header\" aria-label=\"Message headers\">\n<tbody>\n");
198
199        html.push_str(&format!(
200            "<tr><th class=\"hm-hdrlabel\" scope=\"row\">{}</th><td class=\"hm-hdrdata\">{}</td></tr>\n",
201            escape_html(i18n.get("Author")),
202            format_author(email, config)
203        ));
204
205        html.push_str(&format!(
206            "<tr><th class=\"hm-hdrlabel\" scope=\"row\">{}</th><td class=\"hm-hdrdata\">{}</td></tr>\n",
207            escape_html(i18n.get("Date")),
208            format_date(email, config)
209        ));
210
211        let subject = email.subject.as_deref().unwrap_or(i18n.get("no subject"));
212        html.push_str(&format!(
213            "<tr><th class=\"hm-hdrlabel\" scope=\"row\">{}</th><td class=\"hm-hdrdata\">{}</td></tr>\n",
214            escape_html(i18n.get("Subject")),
215            format_subject_text(subject, config)
216        ));
217
218        // Message-ID is kept in HTML comments but not displayed in the visible header table
219        // This reduces clutter while preserving the ID for debugging/threading purposes
220
221        html.push_str("</tbody>\n</table>\n");
222    }
223
224    if config.showreplies {
225        if let Some(reply_html) = format_reply_links(email, store, config) {
226            html.push_str(&reply_html);
227        }
228    }
229
230    html.push_str("<hr class=\"hm-msg-sep\">\n");
231
232    // Only show [Deleted]/[Expired] note if we're not showing the body content
233    // If delete_level >= DELETE_LEAVES_TEXT, we show the body, so no need for the note
234    if email.is_deleted != 0
235        && config.delete_level >= DELETE_LEAVES_STUBS
236        && config.delete_level < DELETE_LEAVES_TEXT
237    {
238        let note = if email.is_deleted & 2 != 0 {
239            i18n.get("[Expired]")
240        } else {
241            i18n.get("[Deleted]")
242        };
243        html.push_str(&format!("<p class=\"hm-deleted\">{}</p>\n", note));
244        if email.bodylist.bodies.is_empty() {
245            html.push_str("</article>\n");
246            return Ok(html);
247        }
248    }
249
250    let body_html = format_body(&email.bodylist, config);
251    html.push_str(&body_html);
252    html.push_str("</article>\n");
253
254    Ok(html)
255}
256
257fn format_author(email: &EmailInfo, config: &Config) -> String {
258    let display_name = decode_mime_words(email.name.as_deref().unwrap_or(""));
259    let display_addr = email.email_addr.as_deref().unwrap_or("unknown");
260
261    let obfuscated_addr = if config.email_address_obfuscation {
262        obfuscate_email_address(display_addr)
263    } else {
264        escape_html(display_addr)
265    };
266
267    let final_addr = spamify(
268        &obfuscated_addr,
269        &config.antispam_at,
270        config.antispamdomain.as_deref(),
271        config.spamprotect,
272        config.spamprotect_id,
273    );
274
275    let escaped_name = escape_html(&display_name);
276
277    let mailto = if let Some(ref hmail) = config.hmail {
278        hmail.replace("$TO", display_addr)
279    } else {
280        format!("mailto:{}", display_addr)
281    };
282
283    if display_name.is_empty() {
284        format!("<a href=\"{}\">{}</a>", escape_html(&mailto), final_addr)
285    } else {
286        format!(
287            "{} &lt;<a href=\"{}\">{}</a>&gt;",
288            escaped_name,
289            escape_html(&mailto),
290            final_addr
291        )
292    }
293}
294
295fn format_date(email: &EmailInfo, config: &Config) -> String {
296    let timestamp = email.date;
297    let date_str = get_date_str(
298        timestamp,
299        config.dateformat.as_deref(),
300        config.gmtime,
301        config.eurodate,
302        config.isodate,
303        &config.language,
304    );
305    let iso_str = secs_to_iso(timestamp);
306    format!("<time datetime=\"{}\">{}</time>", escape_html(&iso_str), escape_html(&date_str))
307}
308
309/// Decode and strip the list tag from a subject, for use in both message and index pages.
310pub fn format_subject_for_index(subject: &str, config: &Config) -> String {
311    let decoded = decode_mime_words(subject);
312    if let Some(ref strip) = config.stripsubject {
313        let trimmed = decoded.strip_prefix(strip.as_str()).map(|s| s.trim());
314        match trimmed {
315            Some(s) if !s.is_empty() => s.to_string(),
316            _ => decoded,
317        }
318    } else {
319        decoded
320    }
321}
322
323fn format_subject_text(subject: &str, config: &Config) -> String {
324    escape_html(&format_subject_for_index(subject, config))
325}
326
327fn format_reply_links(email: &EmailInfo, store: &EmailStore, config: &Config) -> Option<String> {
328    let i18n = I18n::new(&config.language);
329    if store.replylist.is_empty() {
330        return None;
331    }
332
333    let mut reply_indices: Vec<usize> = Vec::new();
334    for reply in &store.replylist {
335        if reply.from_msgnum == email.msgnum {
336            if let Some(idx) = store.find_by_msgnum(reply.msgnum) {
337                reply_indices.push(idx);
338            }
339        }
340    }
341
342    if reply_indices.is_empty() {
343        return None;
344    }
345
346    let mut html = String::from("<ul class=\"hm-reply-list\">\n");
347    for &idx in &reply_indices {
348        let rep = &store.emails[idx];
349        let filename = crate::file_utils::message_url_str(rep, config);
350        let subject = rep.subject.as_deref().unwrap_or(i18n.get("no subject"));
351        let author = decode_mime_words(rep.name.as_deref().unwrap_or(i18n.get("unknown author")));
352        html.push_str(&format!(
353            "  <li><a href=\"{}\">{} by {}</a></li>\n",
354            escape_html(&filename),
355            format_subject_text(subject, config),
356            escape_html(&author)
357        ));
358    }
359    html.push_str("</ul>\n");
360    Some(html)
361}
362
363/// True if `line` is markup produced by our converters (trusted class names only).
364/// Rejects arbitrary `<div onclick=…>` / `<hr onload=…>` that would otherwise
365/// pass through because they start with `<div` / `<hr`.
366fn is_trusted_body_markup(line: &str) -> bool {
367    let s = line.trim_start();
368    if s.starts_with("<hr class=\"hm-sig\">") || s.starts_with("<hr class=\"hm-sig\"") {
369        return true;
370    }
371    if !s.starts_with("<div class=\"") {
372        return false;
373    }
374    // Known classes emitted by txt2html / conv_showhtml
375    const TRUSTED: &[&str] = &[
376        "<div class=\"hm-blank\"",
377        "<div class=\"hm-pg\"",
378        "<div class=\"hm-sig-text\"",
379        "<div class=\"hm-quote-1\"",
380        "<div class=\"hm-quote-2\"",
381        "<div class=\"hm-quote-3\"",
382        "<div class=\"hm-quote-4\"",
383        "<div class=\"hm-quote-5\"",
384        "<div class=\"hm-quote-6\"",
385        "<div class=\"hm-quote-7\"",
386        "<div class=\"hm-quote-8\"",
387        "<div class=\"hm-quote-9\"",
388    ];
389    TRUSTED.iter().any(|p| s.starts_with(p))
390}
391
392fn format_body(body_chain: &crate::message::BodyChain, config: &Config) -> String {
393    let i18n = I18n::new(&config.language);
394    let mut html = String::new();
395    let mut in_attachment = false;
396
397    // Coalescing state: consecutive lines with the same opening tag (e.g. all
398    // `<div class="hm-pg">…</div>`) are merged into ONE block, joined by `\n`.
399    // With `white-space: pre-wrap` in CSS, this renders identically to N
400    // separate divs but eliminates the block-level vertical gap between every
401    // single line — the body reads as one flowing paragraph instead of a
402    // double-spaced list.
403    let mut run_open: Option<String> = None;
404    let mut run_inner = String::new();
405
406    let flush_run = |html: &mut String, run_open: &mut Option<String>, run_inner: &mut String| {
407        if let Some(open) = run_open.take() {
408            html.push_str(&open);
409            html.push_str(run_inner);
410            html.push_str("</div>\n");
411            run_inner.clear();
412        }
413    };
414
415    // Returns the opening `<div …>` tag of a coalesce-eligible line, plus the
416    // inner content. A line is eligible iff it begins with `<div ` and ends
417    // with `</div>\n` (or `</div>`). Anything else (e.g. `<hr …>`,
418    // `<div …><img …></div>` we still merge if same class) breaks the run.
419    fn split_div_line(s: &str) -> Option<(&str, &str)> {
420        let s = s.strip_suffix('\n').unwrap_or(s);
421        let s = s.strip_suffix("</div>")?;
422        if !s.starts_with("<div ") {
423            return None;
424        }
425        let close = s.find('>')?;
426        let open = &s[..=close];
427        let inner = &s[close + 1..];
428        Some((open, inner))
429    }
430
431    for body in &body_chain.bodies {
432        if body.header {
433            continue;
434        }
435
436        if body.attached {
437            flush_run(&mut html, &mut run_open, &mut run_inner);
438            if !in_attachment {
439                html.push_str(&format!(
440                    "<details class=\"hm-attachment\"><summary>{}</summary>\n",
441                    i18n.get("Attachment")
442                ));
443                in_attachment = true;
444            }
445            // Strip the [Attachment: name] wrapper and show the filename cleanly.
446            let filename = body
447                .line
448                .strip_prefix("[Attachment: ")
449                .and_then(|s| s.strip_suffix(']'))
450                .unwrap_or(&body.line);
451            html.push_str(&format!("<p>{}</p>\n", escape_html(filename)));
452        } else {
453            if in_attachment {
454                html.push_str("</details>\n");
455                in_attachment = false;
456            }
457            // conv_showhtml escapes email text before emitting these hm-* wrappers.
458            if body.converted && is_trusted_body_markup(&body.line) {
459                // Blank-line marker: produce a paragraph gap *within* the
460                // current run. Combined with the trailing `\n` already on the
461                // previous line, this gives `pre-wrap` a real empty line.
462                if body.line.starts_with("<div class=\"hm-blank\"") {
463                    if run_open.is_some() {
464                        run_inner.push('\n');
465                    }
466                    continue;
467                }
468                if let Some((open, inner)) = split_div_line(&body.line) {
469                    match &run_open {
470                        Some(cur_open) if cur_open == open => {
471                            // Same class as current run — append with newline.
472                            run_inner.push('\n');
473                            run_inner.push_str(inner);
474                        },
475                        _ => {
476                            flush_run(&mut html, &mut run_open, &mut run_inner);
477                            run_open = Some(open.to_string());
478                            run_inner.push_str(inner);
479                        },
480                    }
481                } else {
482                    // Non-coalescable trusted line (e.g. <hr class="hm-sig">).
483                    flush_run(&mut html, &mut run_open, &mut run_inner);
484                    html.push_str(&body.line);
485                }
486            } else {
487                flush_run(&mut html, &mut run_open, &mut run_inner);
488                html.push_str(&escape_html(&body.line));
489            }
490        }
491    }
492
493    flush_run(&mut html, &mut run_open, &mut run_inner);
494
495    if in_attachment {
496        html.push_str("</details>\n");
497    }
498
499    html
500}
501
502#[cfg(test)]
503fn generate_navigation(email: &EmailInfo, config: &Config) -> Result<String> {
504    let i18n = I18n::new(&config.language);
505    let mut nav = String::from("<nav class=\"hm-nav\" aria-label=\"Message navigation\">\n");
506
507    let filename = crate::file_utils::message_url_str(email, config);
508    nav.push_str(&format!("  <a href=\"{}\">{}</a>\n", filename, i18n.get("Article")));
509
510    if config.show_msg_links > 0 {
511        nav.push_str(&format!(
512            "  <a href=\"index.{}\">{}</a>\n",
513            config.htmlsuffix,
514            i18n.get("Index")
515        ));
516    }
517
518    nav.push_str("</nav>\n");
519    Ok(nav)
520}
521
522/// Returns the HTML filename for a given email message.
523pub fn get_message_filename(email: &EmailInfo, config: &Config) -> String {
524    format!("{}.{}", message_name(email, config), config.htmlsuffix)
525}
526
527/// Returns the full filesystem path for a message's HTML file.
528pub fn get_message_path(email: &EmailInfo, config: &Config) -> PathBuf {
529    utils_message_path(email, config)
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535    use crate::config::Config;
536    use crate::message::{Body, BodyChain, EmailInfo};
537
538    fn make_test_email() -> EmailInfo {
539        EmailInfo {
540            msgnum: 42,
541            date: 1615824000,
542            from_date_str: Some("Mon, 15 Mar 2021 12:00:00 +0000".to_string()),
543            date_str: Some("Mon, 15 Mar 2021 12:00:00 +0000".to_string()),
544            name: Some("Alice".to_string()),
545            email_addr: Some("alice@example.com".to_string()),
546            subject: Some("Test Message".to_string()),
547            msgid: Some("<abc123@example.com>".to_string()),
548            charset: Some("utf-8".to_string()),
549            inreplyto: Some("<parent@example.com>".to_string()),
550            bodylist: BodyChain {
551                bodies: vec![Body {
552                    line: "Hello World".to_string(),
553                    html: false,
554                    header: false,
555                    parsed_header: false,
556                    attached: false,
557                    demimed: false,
558                    converted: false,
559                    msgnum: 0,
560                }],
561            },
562            ..Default::default()
563        }
564    }
565
566    #[test]
567    fn test_html_body_cannot_impersonate_converter_markup() {
568        for showhtml in 0..=4 {
569            for is_html in [false, true] {
570                let config = Config { showhtml, ..Default::default() };
571                let mut email = make_test_email();
572                email.bodylist.bodies[0].html = is_html;
573                email.bodylist.bodies[0].line =
574                    "<div class=\"hm-pg\"><img src=x onerror=alert(1)></div>".to_string();
575                crate::txt2html::conv_showhtml(&mut email.bodylist, &config);
576                let output = format_body(&email.bodylist, &config);
577                assert!(!output.contains("<img"), "showhtml={showhtml}, html={is_html}: {output}");
578                assert!(output.contains("&lt;img"));
579            }
580        }
581    }
582
583    #[test]
584    fn test_unconverted_body_prefix_is_not_trusted() {
585        let config = Config::default();
586        let mut email = make_test_email();
587        email.bodylist.bodies[0].line = "<hr class=\"hm-sig\" onmouseover=alert(1)>".to_string();
588        let output = print_article(&email, &EmailStore::new(), &config).unwrap();
589        assert!(!output.contains("<hr class=\"hm-sig\" onmouseover="));
590        assert!(output.contains("&lt;hr"));
591    }
592
593    #[test]
594    fn test_format_author() {
595        let email = make_test_email();
596        let config = Config::default();
597        let result = format_author(&email, &config);
598        assert!(result.contains("Alice"));
599        assert!(result.contains("alice@example.com"));
600    }
601
602    #[test]
603    fn test_format_subject() {
604        let config = Config::default();
605        let result = format_subject_text("Test Message", &config);
606        assert_eq!(result, "Test Message");
607    }
608
609    #[test]
610    fn test_format_subject_stripsubject() {
611        let mut config = Config::default();
612        config.stripsubject = Some("[mylist] ".to_string());
613
614        assert_eq!(format_subject_text("[mylist] Hello", &config), "Hello");
615        assert_eq!(format_subject_text("[mylist]  Hello", &config), "Hello"); // double space trimmed
616        assert_eq!(format_subject_text("No prefix here", &config), "No prefix here");
617    }
618
619    #[test]
620    fn test_format_subject_stripsubject_no_trailing_space() {
621        // stripsubject without trailing space (e.g. "JotD..."):
622        // "JotD... The joke" → strip "JotD..." → " The joke" → trim → "The joke"
623        let mut config = Config::default();
624        config.stripsubject = Some("JotD...".to_string());
625
626        assert_eq!(format_subject_text("JotD... The joke", &config), "The joke");
627        assert_eq!(format_subject_text("JotD...  Spaces  ", &config), "Spaces"); // trim both ends
628        assert_eq!(format_subject_text("JotD...", &config), "JotD..."); // empty after strip → keep original
629        assert_eq!(format_subject_text("Other subject", &config), "Other subject");
630    }
631
632    #[test]
633    fn test_get_message_filename() {
634        let mut config = Config::default();
635        let mut email = make_test_email();
636        assert_eq!(get_message_filename(&email, &config), "0042.html");
637        config.nonsequential = true;
638        email.from_date = 1615824000;
639        let name = get_message_filename(&email, &config);
640        assert_eq!(name.len(), 21); // 16 hex + ".html"
641    }
642
643    #[test]
644    fn test_format_date() {
645        let email = make_test_email();
646        let config = Config::default();
647        let result = format_date(&email, &config);
648        assert!(!result.is_empty());
649    }
650
651    #[test]
652    fn test_deleted_article_stub() {
653        let mut email = make_test_email();
654        email.is_deleted = 1;
655        let config = Config::default();
656        let result = print_article(&email, &crate::structs::EmailStore::new(), &config).unwrap();
657        assert!(result.contains("Deleted") || result.contains("deleted"));
658    }
659
660    /// Regression test: a message page rendered inside a `folder_by_date`
661    /// subdirectory must link to a reply in the SAME folder as `0043.html`,
662    /// not `2021/0043.html` — the latter 404s as `2021/2021/0043.html` once
663    /// resolved relative to the page it's rendered on (`2021/0042.html`).
664    #[test]
665    fn test_reply_link_omits_own_folder_prefix() {
666        let parent = make_test_email(); // msgnum 42, date 1615824000 (2021-03-15)
667        let mut reply = make_test_email();
668        reply.msgnum = 43;
669        reply.msgid = Some("<reply@example.com>".to_string());
670        reply.subject = Some("Re: Test Message".to_string());
671
672        let mut store = crate::structs::EmailStore::new();
673        store.add_email(parent.clone());
674        store.add_email(reply);
675        crate::structs::link_reply(&mut store.replylist, 42, 43, None, false);
676
677        let mut config = Config::default();
678        config.folder_by_date = Some("%Y".to_string());
679        config.gmtime = true;
680
681        let html = print_article(&parent, &store, &config).unwrap();
682        assert!(
683            html.contains("href=\"0043.html\""),
684            "reply link should be filename-only: {}",
685            html
686        );
687        assert!(
688            !html.contains("href=\"2021/0043.html\""),
689            "reply link must not repeat the folder prefix: {}",
690            html
691        );
692    }
693
694    #[test]
695    fn test_format_body_escapes_raw_text() {
696        let mut chain = BodyChain { bodies: Vec::new() };
697        chain.bodies.push(Body {
698            line: "<script>alert('xss')</script>".to_string(),
699            html: false,
700            header: false,
701            parsed_header: false,
702            attached: false,
703            demimed: false,
704            converted: false,
705            msgnum: 1,
706        });
707        let config = Config::default();
708        let result = format_body(&chain, &config);
709        assert!(result.contains("&lt;script&gt;"));
710        assert!(!result.contains("<script>"));
711    }
712
713    #[test]
714    fn test_format_body_passes_div_through() {
715        let mut chain = BodyChain { bodies: Vec::new() };
716        chain.bodies.push(Body {
717            line: "safe".to_string(),
718            html: false,
719            header: false,
720            parsed_header: false,
721            attached: false,
722            demimed: false,
723            converted: false,
724            msgnum: 1,
725        });
726        let config = Config::default();
727        crate::txt2html::conv_showhtml(&mut chain, &config);
728        let result = format_body(&chain, &config);
729        assert!(result.contains("<div class=\"hm-pg\">safe</div>"));
730    }
731
732    #[test]
733    fn test_message_id_spam_protected() {
734        let email = make_test_email();
735        let mut config = Config::default();
736        config.spamprotect_id = true;
737        config.antispam_at = " at ".to_string();
738        let store = crate::structs::EmailStore::new();
739        let result = print_article(&email, &store, &config).unwrap();
740        assert!(result.contains(" at "));
741        assert!(!result.contains("abc123@example.com"));
742    }
743
744    #[test]
745    fn test_nonsequential_navigation_link() {
746        let email = make_test_email();
747        let mut config = Config::default();
748        config.nonsequential = true;
749        let result = generate_navigation(&email, &config).unwrap();
750        // Link should be hex hash based, not msgnum
751        assert!(!result.contains("0042.html"));
752        assert!(result.contains(".html"));
753    }
754
755    #[test]
756    fn test_format_author_no_double_mailto() {
757        let email = make_test_email();
758        let config = Config::default();
759        let result = format_author(&email, &config);
760        // href should contain exactly one mailto: prefix, not mailto:mailto:
761        assert!(result.contains("href=\"mailto:"), "should have mailto: link");
762        assert!(!result.contains("mailto:mailto:"), "should NOT have double mailto: prefix");
763    }
764
765    #[test]
766    fn test_format_author_with_hmail_no_double_mailto() {
767        let email = make_test_email();
768        let mut config = Config::default();
769        config.hmail = Some("mailto:$TO?subject=test".to_string());
770        let result = format_author(&email, &config);
771        assert!(
772            !result.contains("mailto:mailto:"),
773            "hmail substitution should NOT produce double mailto:"
774        );
775    }
776
777    #[test]
778    fn test_article_uses_id_not_a_name() {
779        let email = make_test_email();
780        let store = crate::structs::EmailStore::new();
781        let config = Config::default();
782        let result = print_article(&email, &store, &config).unwrap();
783        // Should use <article id="..."> not <a name="...">
784        assert!(result.contains("<article id=\""), "should use <article id=>");
785        assert!(!result.contains("<a name=\""), "should NOT use deprecated <a name=>");
786    }
787
788    #[test]
789    fn test_subject_xss_escaped_in_title() {
790        let mut email = make_test_email();
791        email.subject = Some("</title><script>alert(1)</script>".to_string());
792        let store = crate::structs::EmailStore::new();
793        let config = Config::default();
794        let result = print_article(&email, &store, &config).unwrap();
795        assert!(!result.contains("<script>alert(1)</script>"), "raw script in subject");
796        assert!(result.contains("&lt;script&gt;") || result.contains("&lt;/title&gt;"));
797    }
798
799    #[test]
800    fn test_inline_image_xss_in_body_not_emitted() {
801        let mut email = make_test_email();
802        email.bodylist = BodyChain {
803            bodies: vec![Body {
804                line: r#"[INLINE_IMAGE:image/png:x" onerror="alert(1)]"#.to_string(),
805                html: false,
806                header: false,
807                parsed_header: false,
808                attached: false,
809                demimed: false,
810                converted: false,
811                msgnum: 42,
812            }],
813        };
814        let store = crate::structs::EmailStore::new();
815        let config = Config::default();
816        // process like main does
817        let mut store_email = email.clone();
818        crate::txt2html::conv_showhtml(&mut store_email.bodylist, &config);
819        let result = print_article(&store_email, &store, &config).unwrap();
820        assert!(
821            !result.contains("<img"),
822            "malicious INLINE_IMAGE must not become img: {}",
823            result
824        );
825        assert!(
826            !result.contains(r#"onerror=""#),
827            "must not create onerror attribute: {}",
828            result
829        );
830    }
831}