Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

9.5 KB
Raw Blame
//! Port of Vencord's ClearURLs: strips tracking parameters from links in
//! messages before they're sent (and when editing).

use crate::{Cx, Plugin, PluginMeta, SettingDef};
use discord::model::{Id, OutgoingMessage};
use regex::Regex;
use std::sync::OnceLock;
use url::Url;

pub struct ClearUrls;

/// `param` applies everywhere, `param@domain` only on that domain (and its
/// subdomains). `*` at the end of a param is a prefix wildcard; `domain.*`
/// matches any TLD.
const DEFAULT_RULES: &[&str] = &[
    // Generic campaign / click trackers
    "utm_*", "fbclid", "gclid", "gclsrc", "dclid", "gbraid", "wbraid", "msclkid", "yclid",
    "mc_cid", "mc_eid", "_openstat", "igshid", "igsh", "mkt_tok", "trk", "trkCampaign",
    "sc_campaign", "_hsenc", "_hsmi", "__hssc", "__hstc", "__hsfp", "hsCtaTracking",
    "oly_anon_id", "oly_enc_id", "vero_id", "vero_conv", "wickedid", "rb_clickid", "s_cid",
    "_ga", "_gl", "ga_*", "ttclid", "twclid", "li_fat_id", "srsltid", "_branch_match_id",
    "_branch_referrer",
    // YouTube / Spotify share ids
    "[email protected]", "[email protected]", "[email protected]", "[email protected]",
    "[email protected]", "[email protected]",
    // Twitter / X
    "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]",
    "[email protected]", "[email protected]", "[email protected]",
    // Reddit
    "[email protected]", "[email protected]", "[email protected]",
    // Amazon
    "pd_rd_*@amazon.*", "pf_rd_*@amazon.*", "ref@amazon.*", "ref_@amazon.*", "_encoding@amazon.*",
    "psc@amazon.*", "content-id@amazon.*", "crid@amazon.*", "sprefix@amazon.*", "dib@amazon.*",
    "dib_tag@amazon.*", "qid@amazon.*", "sr@amazon.*", "th@amazon.*", "linkCode@amazon.*",
    // AliExpress
    "[email protected]", "[email protected]", "algo_*@aliexpress.com", "aff_*@aliexpress.com",
    // Google search result links
    "ved@google.*", "ei@google.*", "sca_esv@google.*", "sxsrf@google.*", "gs_lcrp@google.*",
    "sourceid@google.*", "aqs@google.*", "uact@google.*", "oq@google.*",
    // TikTok / Facebook / Instagram / LinkedIn
    "[email protected]", "[email protected]", "[email protected]", "[email protected]",
    "[email protected]", "[email protected]", "[email protected]", "[email protected]",
    "[email protected]", "[email protected]", "[email protected]", "[email protected]",
    "[email protected]",
    // News sites
    "[email protected]", "[email protected]",
];

struct Rule {
    param: String,
    prefix: bool,
    domain: Option<String>,
}

impl Rule {
    fn parse(raw: &str) -> Option<Self> {
        let raw = raw.trim();
        if raw.is_empty() || raw.starts_with("//") {
            return None;
        }
        let (param, domain) = match raw.split_once('@') {
            Some((p, d)) => (p, Some(d.trim().to_ascii_lowercase())),
            None => (raw, None),
        };
        let (param, prefix) = match param.strip_suffix('*') {
            Some(p) => (p, true),
            None => (param, false),
        };
        Some(Rule { param: param.to_string(), prefix, domain })
    }

    fn matches(&self, host: &str, key: &str) -> bool {
        let key_ok = if self.prefix { key.starts_with(&self.param) } else { key == self.param };
        key_ok && self.domain.as_deref().map_or(true, |d| domain_matches(host, d))
    }
}

fn domain_matches(host: &str, pattern: &str) -> bool {
    let pattern = pattern.trim_start_matches("*.");
    if pattern == "*" {
        return true;
    }
    if let Some(base) = pattern.strip_suffix(".*") {
        return host.starts_with(&format!("{base}.")) || host.contains(&format!(".{base}."));
    }
    host == pattern || host.ends_with(&format!(".{pattern}"))
}

fn url_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"https?://[^\s<>]+").expect("valid regex"))
}

fn rules(cx: &Cx) -> Vec<Rule> {
    let custom = cx.settings.text("customRules");
    DEFAULT_RULES
        .iter()
        .copied()
        .chain(custom.lines())
        .filter_map(Rule::parse)
        .collect()
}

/// Remove tracking parameters from a single URL. `None` if nothing changed.
fn clean_url(raw: &str, rules: &[Rule]) -> Option<String> {
    let mut url = Url::parse(raw).ok()?;
    let host = url.host_str()?.to_ascii_lowercase();
    let host = host.trim_start_matches("www.").to_string();

    // The parameters that stay are kept exactly as written (their encoding
    // can matter: signed links), so the query is cut up by hand.
    let query = url.query().unwrap_or("").to_string();
    let tracked = |segment: &str| {
        let name = segment.split('=').next().unwrap_or(segment);
        let name = url::form_urlencoded::parse(name.as_bytes()).next().map(|(k, _)| k.into_owned()).unwrap_or_default();
        rules.iter().any(|r| r.matches(&host, &name))
    };
    let segments: Vec<&str> = query.split('&').collect();
    let kept: Vec<&str> = segments.iter().copied().filter(|s| !tracked(s)).collect();
    let mut changed = kept.len() != segments.len();

    if changed {
        if kept.iter().all(|s| s.is_empty()) {
            url.set_query(None);
        } else {
            url.set_query(Some(&kept.join("&")));
        }
    }

    // Amazon puts tracking in the path too: /dp/B000/ref=sr_1_1
    if domain_matches(&host, "amazon.*") {
        let path = url.path().to_string();
        if let Some(idx) = path.find("/ref=") {
            url.set_path(&path[..idx]);
            changed = true;
        }
    }

    changed.then(|| url.to_string())
}

/// Clean every URL in `text`, leaving everything else untouched.
fn clean_text(text: &str, rules: &[Rule]) -> String {
    url_regex()
        .replace_all(text, |caps: &regex::Captures| {
            let full = &caps[0];
            // Leave trailing punctuation (and unbalanced ')') out of the URL.
            let mut end = full.len();
            while end > 0 {
                let c = full[..end].chars().last().unwrap_or(' ');
                let strip = match c {
                    '.' | ',' | '!' | '?' | ':' | ';' | '\'' | '"' | ']' => true,
                    // Markdown closing around the link: ||spoiler||, **bold**, `code`.
                    '|' | '*' | '~' | '`' => true,
                    ')' => full[..end].matches('(').count() < full[..end].matches(')').count(),
                    _ => false,
                };
                if !strip {
                    break;
                }
                end -= c.len_utf8();
            }
            let (url, tail) = full.split_at(end);
            match clean_url(url, rules) {
                Some(cleaned) => format!("{cleaned}{tail}"),
                None => full.to_string(),
            }
        })
        .into_owned()
}

impl Plugin for ClearUrls {
    fn meta(&self) -> PluginMeta {
        PluginMeta {
            id: "ClearURLs",
            name: "ClearURLs",
            description: "Removes tracking parameters (utm_*, fbclid, si, …) from links in your messages before they're sent.",
            authors: &["RustCord"],
            vencord_equivalent: Some("ClearURLs"),
            default_enabled: true,
        }
    }

    fn settings(&self) -> Vec<SettingDef> {
        vec![
            SettingDef::bool("cleanEdits", "Clean edited messages", "Also clean links when you edit a message.", true),
            SettingDef::text(
                "customRules",
                "Extra rules",
                "One per line: `param`, `[email protected]`, `prefix_*`, or `param@site.*` for any TLD.",
                "[email protected]",
                true,
            ),
        ]
    }

    fn before_send(&mut self, cx: &Cx, msg: &mut OutgoingMessage) -> bool {
        msg.content = clean_text(&msg.content, &rules(cx));
        true
    }

    fn before_edit(&mut self, cx: &Cx, _channel: Id, content: &mut String) -> bool {
        if cx.settings.bool("cleanEdits") {
            *content = clean_text(content, &rules(cx));
        }
        true
    }
}

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

    fn defaults() -> Vec<Rule> {
        DEFAULT_RULES.iter().copied().filter_map(Rule::parse).collect()
    }

    #[test]
    fn strips_utm_and_fbclid() {
        let out = clean_text(
            "look https://example.com/page?id=42&utm_source=news&fbclid=abc.",
            &defaults(),
        );
        assert_eq!(out, "look https://example.com/page?id=42.");
    }

    #[test]
    fn removes_query_entirely() {
        let out = clean_text("https://youtu.be/dQw4w9WgXcQ?si=xyz", &defaults());
        assert_eq!(out, "https://youtu.be/dQw4w9WgXcQ");
    }

    #[test]
    fn domain_specific_rule_does_not_leak() {
        let out = clean_text("https://example.com/?si=1", &defaults());
        assert_eq!(out, "https://example.com/?si=1");
    }

    #[test]
    fn amazon_path_ref() {
        let out = clean_text("https://www.amazon.co.uk/dp/B000/ref=sr_1_1?qid=1&keywords=x", &defaults());
        assert_eq!(out, "https://www.amazon.co.uk/dp/B000?keywords=x");
    }

    #[test]
    fn markdown_around_a_link_survives() {
        let out = clean_text("||https://youtu.be/x?si=abc|| and **https://example.com/?utm_source=a**", &defaults());
        assert_eq!(out, "||https://youtu.be/x|| and **https://example.com/**");
    }

    #[test]
    fn kept_parameters_are_not_rewritten() {
        let out = clean_text("https://example.com/p?sig=a%20b%2F&flag&utm_source=x&q=c+d", &defaults());
        assert_eq!(out, "https://example.com/p?sig=a%20b%2F&flag&q=c+d");
    }

    #[test]
    fn untouched_text_is_identical() {
        let s = "no links (here) at all https://rust-lang.org)";
        assert_eq!(clean_text(s, &defaults()), s);
    }
}