mailcycle 0.3.0

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for events.
Documentation
//! Tracker stripping.
//!
//! Opening an email should not tell the sender that you opened it. Most HTML
//! mail carries at least one remote resource whose only job is to report back:
//! a 1x1 image on a per-recipient URL. Loading it leaks the open, the time,
//! the approximate location and, across devices, how many devices you read on.
//!
//! Mailcycle's rule is absolute and needs no per-message decision from the
//! reader: remote content in mail is never fetched. [`Message::safe_html`] is
//! the body with everything remote removed, and [`Message::blocked`] is what
//! was taken out.
//!
//! A remote resource hides in more than `<img src>`: `srcset`, CSS
//! `background-image: url(...)` in a style attribute or a `<style>` block, SVG
//! `<image href>`/`<use href>`, `<video poster>`,
//! `<iframe>`/`<object>`/`<embed>`, and a scheme obfuscated with HTML entities
//! (`&#104;ttps://...`) all fetch. Every one of them is covered. An `<a href>`
//! is left alone, because it loads only when the reader clicks it.
//!
//! This is a port of `src/privacy/trackers.ts`, kept behaviour-for-behaviour
//! with it so the same message reads the same way here as in the app. Rust's
//! regular expressions have no backreferences, so the one JavaScript pattern
//! that used one is written as an alternation below; the differential test
//! runs both implementations over the same markup and requires identical
//! output.
//!
//! [`Message::safe_html`]: crate::models::Message::safe_html
//! [`Message::blocked`]: crate::models::Message::blocked

use std::collections::HashMap;
use std::sync::OnceLock;

use regex::{Captures, Regex};

/// One remote resource that was removed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockedTracker {
    pub url: String,
    pub host: String,
    /// `pixel`, `image` or `link`.
    pub kind: String,
}

/// What [`strip_remote_content`] produced.
#[derive(Debug, Clone)]
pub struct StripResult {
    pub html: String,
    pub blocked: Vec<BlockedTracker>,
}

/// Which attributes fetch a remote resource, per element. `href` is listed
/// only for SVG `<image>`/`<use>`: an `<a href>` is a click, not an automatic
/// load.
fn resource_attrs(tag: &str) -> &'static [&'static str] {
    match tag {
        "img" => &["src", "srcset", "lowsrc"],
        "source" => &["src", "srcset"],
        "image" | "use" => &["xlink:href", "href"],
        "video" => &["src", "poster"],
        "audio" | "track" | "iframe" | "embed" | "input" => &["src"],
        "object" => &["data"],
        "body" | "table" | "td" | "th" | "tr" => &["background"],
        _ => &[],
    }
}

/// Elements that exist only to load their remote resource: drop them whole.
fn drops_whole(tag: &str) -> bool {
    tag == "img" || tag == "source"
}

/// Hosts whose presence in mail is tracking and nothing else.
const TRACKER_HINTS: [&str; 14] = [
    "open.",
    "track.",
    "trk.",
    "click.",
    "email.",
    "mailstat",
    "pixel",
    "beacon",
    "sendgrid.net",
    "mailchimp",
    "list-manage",
    "hubspot",
    "mktoresp",
    "omtrdc",
];

struct Patterns {
    dimension: Regex,
    remote: Regex,
    css_url: Regex,
    style_block: Regex,
    tag: Regex,
    host: Regex,
    entity_hex: Regex,
    entity_dec: Regex,
    entity_named: Regex,
    ignorable: Regex,
    www: Regex,
    link: Regex,
    attrs: HashMap<&'static str, Regex>,
}

fn attr_regex(attr: &str) -> Regex {
    // A leading boundary (start, whitespace or quote) keeps `href` from
    // matching inside `xlink:href`.
    Regex::new(&format!(r#"(?i)(^|[\s"'])({})\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))"#, regex::escape(attr)))
        .expect("a valid attribute pattern")
}

fn patterns() -> &'static Patterns {
    static CELL: OnceLock<Patterns> = OnceLock::new();
    CELL.get_or_init(|| {
        let mut attrs = HashMap::new();
        for attr in ["src", "srcset", "lowsrc", "xlink:href", "href", "poster", "data", "background", "style"]
        {
            attrs.insert(attr, attr_regex(attr));
        }
        Patterns {
            dimension: Regex::new(r#"(?i)\b(width|height)\s*=\s*["']?\s*([0-9]+)"#).unwrap(),
            remote: Regex::new(r"(?i)^(https?:)?//").unwrap(),
            // The JavaScript is `url\(\s*(['"]?)([^'")]+)\1\s*\)`, which needs
            // a backreference. Written here as the three cases it can be, in
            // the order that keeps a quoted value from matching the bare one.
            css_url: Regex::new(r#"(?i)url\(\s*(?:"([^'")]+)"|'([^'")]+)'|([^'")]+))\s*\)"#).unwrap(),
            style_block: Regex::new(r"(?is)<style\b[^>]*>(.*?)</style>").unwrap(),
            // The attributes group tolerates quoted values that contain `>`.
            tag: Regex::new(r#"<([a-zA-Z][A-Za-z0-9_:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>"#).unwrap(),
            host: Regex::new(r"(?i)^(?:https?:)?//([^/?#]+)").unwrap(),
            entity_hex: Regex::new(r"(?i)&#x([0-9a-f]+);?").unwrap(),
            entity_dec: Regex::new(r"&#([0-9]+);?").unwrap(),
            entity_named: Regex::new(r"(?i)&(amp|colon|sol|NewLine|Tab);").unwrap(),
            ignorable: Regex::new(r"[\s-]+").unwrap(),
            www: Regex::new(r"(?i)^www\.").unwrap(),
            link: Regex::new(r#"(?i)https?://[^\s<>"')]+"#).unwrap(),
            attrs,
        }
    })
}

fn code_point(value: u32) -> String {
    char::from_u32(value).map(String::from).unwrap_or_default()
}

/// Collapses HTML entities and ignorable characters.
///
/// Used only to decide remoteness, so a scheme a renderer would resolve is
/// judged by what it resolves to rather than by how it was spelled. The
/// original text is what gets removed.
fn canonical(value: &str) -> String {
    let p = patterns();
    let mut current = value.to_string();
    for _ in 0..3 {
        let step = p.entity_hex.replace_all(&current, |caps: &Captures| {
            u32::from_str_radix(&caps[1], 16).map(code_point).unwrap_or_default()
        });
        let step = p
            .entity_dec
            .replace_all(&step, |caps: &Captures| caps[1].parse::<u32>().map(code_point).unwrap_or_default());
        let step =
            p.entity_named.replace_all(&step, |caps: &Captures| match caps[1].to_lowercase().as_str() {
                "amp" => "&",
                "colon" => ":",
                "sol" => "/",
                _ => "",
            });
        if step == current {
            break;
        }
        current = step.into_owned();
    }
    p.ignorable.replace_all(&current, "").into_owned()
}

/// The host of a URL, lowercased and without a leading `www.`.
pub fn host_of(url: &str) -> String {
    let p = patterns();
    let canonical = canonical(url);
    match p.host.captures(canonical.trim()) {
        Some(caps) => p.www.replace(&caps[1], "").to_lowercase(),
        None => String::new(),
    }
}

fn is_remote(url: &str) -> bool {
    patterns().remote.is_match(&canonical(url))
}

/// The URLs inside a `srcset`: each candidate is `url [descriptor]`.
fn srcset_urls(value: &str) -> Vec<&str> {
    value
        .split(',')
        .filter_map(|candidate| candidate.split_whitespace().next())
        .filter(|url| !url.is_empty())
        .collect()
}

fn attr_value(attrs: &str, attr: &str) -> Option<String> {
    let regex = patterns().attrs.get(attr)?;
    let caps = regex.captures(attrs)?;
    Some(
        caps.get(4)
            .or_else(|| caps.get(5))
            .or_else(|| caps.get(6))
            .map(|m| m.as_str().to_string())
            .unwrap_or_default(),
    )
}

fn remove_attr(attrs: &str, attr: &str) -> String {
    match patterns().attrs.get(attr) {
        Some(regex) => regex.replace(attrs, "$1").into_owned(),
        None => attrs.to_string(),
    }
}

fn set_attr(attrs: &str, attr: &str, value: &str) -> String {
    let quoted = value.replace('"', "&quot;");
    match patterns().attrs.get(attr) {
        Some(regex) => {
            regex.replace(attrs, |caps: &Captures| format!("{}{attr}=\"{quoted}\"", &caps[1])).into_owned()
        }
        None => attrs.to_string(),
    }
}

/// Pixel or ordinary blocked imagery.
///
/// The distinction only affects wording; both are blocked identically.
fn classify(tag: &str, url: &str) -> String {
    let smallest =
        patterns().dimension.captures_iter(tag).filter_map(|caps| caps[2].parse::<u64>().ok()).min();
    if smallest.is_some_and(|value| value <= 3) {
        return "pixel".into();
    }
    let host = host_of(url);
    if TRACKER_HINTS.iter().any(|hint| host.contains(hint)) {
        "pixel".into()
    } else {
        "image".into()
    }
}

/// Removes every remote resource from an HTML body.
///
/// Inline `cid:` and `data:` references are left alone; they travel inside the
/// message and fetch nothing. Everything remote goes, tracker or not, because
/// "block only the ones that look like trackers" is a game the sender wins.
pub fn strip_remote_content(html: &str) -> StripResult {
    let p = patterns();
    let mut blocked: Vec<BlockedTracker> = Vec::new();
    let mut seen: Vec<String> = Vec::new();

    let record = |url: &str, tag: &str, blocked: &mut Vec<BlockedTracker>, seen: &mut Vec<String>| {
        if seen.iter().any(|already| already == url) {
            return;
        }
        seen.push(url.to_string());
        blocked.push(BlockedTracker { url: url.to_string(), host: host_of(url), kind: classify(tag, url) });
    };

    let strip_css_urls = |css: &str, blocked: &mut Vec<BlockedTracker>, seen: &mut Vec<String>| -> String {
        p.css_url
            .replace_all(css, |caps: &Captures| {
                let url = caps
                    .get(1)
                    .or_else(|| caps.get(2))
                    .or_else(|| caps.get(3))
                    .map(|m| m.as_str())
                    .unwrap_or_default();
                if !is_remote(url) {
                    return caps[0].to_string();
                }
                record(url, "", blocked, seen);
                "url()".to_string()
            })
            .into_owned()
    };

    // 1) CSS url(...) inside <style> blocks.
    let mut out = String::new();
    let mut last = 0;
    for caps in p.style_block.captures_iter(html) {
        let whole = caps.get(0).unwrap();
        let css = caps.get(1).unwrap().as_str();
        let cleaned = strip_css_urls(css, &mut blocked, &mut seen);
        out.push_str(&html[last..whole.start()]);
        out.push_str(&whole.as_str().replacen(css, &cleaned, 1));
        last = whole.end();
    }
    out.push_str(&html[last..]);

    // 2) Every tag: drop remote <img>/<source>, strip remote URL attributes on
    //    other elements, and neutralize remote url() in any style attribute.
    let stage = out;
    let mut result = String::new();
    let mut last = 0;
    for caps in p.tag.captures_iter(&stage) {
        let whole = caps.get(0).unwrap();
        let name = caps.get(1).unwrap().as_str();
        let attrs = caps.get(2).unwrap().as_str();
        let lower = name.to_lowercase();

        result.push_str(&stage[last..whole.start()]);
        last = whole.end();

        let mut next_attrs = attrs.to_string();
        let mut dropped = false;

        for attr in resource_attrs(&lower) {
            let Some(value) = attr_value(&next_attrs, attr) else { continue };
            let candidates: Vec<String> = if *attr == "srcset" {
                srcset_urls(&value).into_iter().map(str::to_string).collect()
            } else {
                vec![value.clone()]
            };
            let Some(remote) = candidates.into_iter().find(|url| is_remote(url)) else { continue };

            record(&remote, whole.as_str(), &mut blocked, &mut seen);
            if drops_whole(&lower) {
                // A src-less <img> is pointless, and a permissive renderer
                // cannot re-add a URL that is not there.
                dropped = true;
                break;
            }
            next_attrs = remove_attr(&next_attrs, attr);
        }
        if dropped {
            continue;
        }

        if let Some(style) = attr_value(&next_attrs, "style").filter(|s| !s.is_empty()) {
            let cleaned = strip_css_urls(&style, &mut blocked, &mut seen);
            if cleaned != style {
                next_attrs = set_attr(&next_attrs, "style", &cleaned);
            }
        }

        if next_attrs == attrs {
            result.push_str(whole.as_str());
        } else {
            result.push('<');
            result.push_str(name);
            result.push_str(&next_attrs);
            result.push('>');
        }
    }
    result.push_str(&stage[last..]);

    StripResult { html: result, blocked }
}

/// Plain-text bodies carry trackers too, as one-pixel-equivalent link opens.
pub fn find_tracking_links(text: &str) -> Vec<BlockedTracker> {
    let mut out = Vec::new();
    let mut seen: Vec<String> = Vec::new();
    for found in patterns().link.find_iter(text) {
        let url = found.as_str();
        let host = host_of(url);
        if seen.iter().any(|already| already == url) {
            continue;
        }
        if !TRACKER_HINTS.iter().any(|hint| host.contains(hint)) {
            continue;
        }
        seen.push(url.to_string());
        out.push(BlockedTracker { url: url.to_string(), host, kind: "link".into() });
    }
    out
}

/// A one-line summary, as the app shows above a message.
pub fn summarize_blocked(blocked: &[BlockedTracker]) -> String {
    if blocked.is_empty() {
        return "No trackers in this message.".into();
    }
    let mut hosts: Vec<&str> = Vec::new();
    for tracker in blocked {
        if !tracker.host.is_empty() && !hosts.contains(&tracker.host.as_str()) {
            hosts.push(&tracker.host);
        }
    }
    let noun = if blocked.len() == 1 { "tracker" } else { "trackers" };
    match hosts.len() {
        0 => format!("{} {noun} blocked.", blocked.len()),
        1 => format!("{} {noun} blocked from {}.", blocked.len(), hosts[0]),
        n => format!("{} {noun} blocked from {n} hosts.", blocked.len()),
    }
}