Skip to content

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

14.1 KB
Raw Blame
//! Spam warnings: notices when what RustCord sends looks like a spam bot or
//! an automated account to Discord's anti-abuse (bursts of messages, the
//! same text over and over, mass mentions, invite links spread across chats,
//! mass friend-list changes, many new DMs or server joins, heavy API use,
//! "too many requests" answers). Discord suspends
//! accounts for these patterns even when no single request is over a limit.
//!
//! Every API request is noted here (a few timestamps per kind, cheap); a
//! pattern over its threshold queues a [`Warning`] for the app to show. Each
//! kind warns at most once every few minutes.

use reqwest::Method;
use serde_json::Value;
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
    ApiBurst,
    RateLimited,
    Messages,
    SameMessage,
    Mentions,
    InviteLinks,
    Reactions,
    Deletes,
    FriendList,
    NewDms,
    Joins,
    Creates,
}

/// A pattern crossed its threshold: what to tell the person.
#[derive(Clone, Debug)]
pub struct Warning {
    pub kind: Kind,
    pub title: &'static str,
    pub text: String,
}

/// (kind, window, how many in it trip the warning).
const RULES: &[(Kind, Duration, usize)] = &[
    (Kind::ApiBurst, Duration::from_secs(10), 40),
    (Kind::RateLimited, Duration::from_secs(60), 2),
    (Kind::Messages, Duration::from_secs(10), 6),
    (Kind::Mentions, Duration::from_secs(600), 2),
    (Kind::Reactions, Duration::from_secs(30), 15),
    (Kind::Deletes, Duration::from_secs(60), 10),
    (Kind::FriendList, Duration::from_secs(600), 5),
    (Kind::NewDms, Duration::from_secs(600), 5),
    (Kind::Joins, Duration::from_secs(600), 3),
    (Kind::Creates, Duration::from_secs(3600), 3),
];

/// The same text this many times within [`SAME_WINDOW`] trips SameMessage.
const SAME_LIMIT: usize = 3;
const SAME_WINDOW: Duration = Duration::from_secs(60);
/// A message pinging at least this many people (or everyone) counts as Mentions.
const MASS_MENTIONS: usize = 5;
/// Invite links posted in this many different chats within [`INVITE_WINDOW`]
/// trip InviteLinks.
const INVITE_CHATS: usize = 3;
const INVITE_WINDOW: Duration = Duration::from_secs(600);
/// A kind warns again only after this long.
const COOLDOWN: Duration = Duration::from_secs(180);

#[derive(Default)]
struct State {
    seen: HashMap<Kind, VecDeque<Instant>>,
    /// Recent message texts (hashed) and when each was sent.
    texts: VecDeque<(u64, Instant)>,
    /// Chats an invite link was posted in, and when.
    invites: VecDeque<(String, Instant)>,
    warned: HashMap<Kind, Instant>,
    pending: Vec<Warning>,
}

static STATE: LazyLock<Mutex<State>> = LazyLock::new(Default::default);
static PENDING: AtomicBool = AtomicBool::new(false);

/// What kinds an API request counts as (besides ApiBurst, which every one is).
fn kinds(method: &Method, path: &str) -> Vec<Kind> {
    let path = path.split('?').next().unwrap_or(path);
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    let mut out = Vec::new();
    match (method.as_str(), segs.as_slice()) {
        ("POST", ["channels", _, "messages"]) => out.push(Kind::Messages),
        ("PUT", ["channels", _, "messages", _, "reactions", ..]) => out.push(Kind::Reactions),
        ("DELETE", ["channels", _, "messages", _]) => out.push(Kind::Deletes),
        ("PUT" | "POST" | "DELETE", ["users", "@me", "relationships", ..]) => out.push(Kind::FriendList),
        ("POST", ["users", "@me", "channels"]) => out.push(Kind::NewDms),
        ("POST", ["invites", _]) => out.push(Kind::Joins),
        ("POST", ["guilds"]) | ("POST", ["guilds", "templates", _]) => out.push(Kind::Creates),
        _ => {}
    }
    out
}

/// The message pings many people, or everyone.
fn mass_mention(text: &str) -> bool {
    if text.contains("@everyone") || text.contains("@here") {
        return true;
    }
    let mut ids: Vec<&str> = text
        .split("<@")
        .skip(1)
        .filter_map(|rest| {
            let rest = rest.strip_prefix('!').unwrap_or(rest);
            let id = &rest[..rest.find('>')?];
            (!id.is_empty() && id.bytes().all(|b| b.is_ascii_digit())).then_some(id)
        })
        .collect();
    ids.sort_unstable();
    ids.dedup();
    ids.len() >= MASS_MENTIONS
}

/// The message carries a server invite.
fn has_invite(text: &str) -> bool {
    let text = text.to_ascii_lowercase();
    ["discord.gg/", "discord.com/invite/", "discordapp.com/invite/", "dsc.gg/"].iter().any(|p| text.contains(p))
}

fn text_hash(s: &str) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    s.trim().to_lowercase().hash(&mut h);
    h.finish()
}

/// The warning for `kind` having happened `n` times.
pub fn warning(kind: Kind, n: usize) -> Warning {
    let (title, text) = match kind {
        Kind::ApiBurst => ("RustCord is talking to Discord a lot", format!("{n} requests in 10 seconds. If you're clicking through many channels, profiles or servers quickly, slow down a little: unusually heavy use is something Discord's anti-abuse notices.")),
        Kind::RateLimited => ("Discord asked RustCord to slow down", format!("Discord answered \"too many requests\" {n} times in the last minute. RustCord waits as asked, but take a break from whatever you're doing quickly.")),
        Kind::Messages => ("You're sending messages very fast", format!("{n} messages in 10 seconds. Discord's spam filter watches for accounts that post this quickly, and can lock or suspend them. Give it a moment.")),
        Kind::Mentions => ("Mentioning lots of people", format!("{n} messages in 10 minutes pinged {MASS_MENTIONS} or more people, or everyone. Mass mentions are one of the patterns Discord's spam filter and AutoMod act on.")),
        Kind::InviteLinks => ("Posting invite links around", format!("You've posted server invites in {n} different chats in 10 minutes. Spreading invite links across chats and DMs is the classic spam-bot pattern, and Discord suspends accounts for it.")),
        Kind::SameMessage => ("Same message, over and over", format!("You've sent the same text {n} times in a minute. Repeating a message, especially across chats, is what spam bots do, and Discord's filter looks for it.")),
        Kind::Reactions => ("Lots of reactions at once", format!("{n} reactions in 30 seconds. Reacting this fast is a common bot pattern.")),
        Kind::Deletes => ("Deleting messages quickly", format!("{n} messages deleted in a minute. Bulk deleting at this pace looks automated to Discord.")),
        Kind::FriendList => ("Many friend requests", format!("{n} friend-list changes (requests sent, accepted or removed) in 10 minutes. Discord has locked accounts for this; RustCord already spaces them out, but slow down.")),
        Kind::NewDms => ("Messaging lots of people", format!("You've opened {n} DMs in 10 minutes. Messaging many people one after another is one of the main things Discord's anti-spam watches for.")),
        Kind::Joins => ("Joining many servers", format!("{n} servers joined in 10 minutes. Joining servers in quick succession is a common sign of a bot account.")),
        Kind::Creates => ("Creating many servers", format!("{n} servers created in an hour. Making servers in bulk is something Discord's anti-abuse flags.")),
    };
    Warning { kind, title, text }
}

impl State {
    /// Count one `kind` now; queue a warning if that crosses its threshold.
    fn count(&mut self, kind: Kind, now: Instant) {
        let Some(&(_, window, limit)) = RULES.iter().find(|r| r.0 == kind) else { return };
        let q = self.seen.entry(kind).or_default();
        q.push_back(now);
        while q.front().is_some_and(|t| now.duration_since(*t) > window) {
            q.pop_front();
        }
        let n = q.len();
        if n >= limit {
            self.warn(kind, n, now);
        }
    }

    fn warn(&mut self, kind: Kind, n: usize, now: Instant) {
        if self.warned.get(&kind).is_some_and(|t| now.duration_since(*t) < COOLDOWN) {
            return;
        }
        self.warned.insert(kind, now);
        log::warn!("spam guard: {kind:?} ({n})");
        self.pending.push(warning(kind, n));
        PENDING.store(true, Ordering::Relaxed);
    }

    /// An invite link was posted in `chat`.
    fn invite(&mut self, chat: &str, now: Instant) {
        self.invites.push_back((chat.to_owned(), now));
        while self.invites.front().is_some_and(|(_, t)| now.duration_since(*t) > INVITE_WINDOW) {
            self.invites.pop_front();
        }
        let mut chats: Vec<&str> = self.invites.iter().map(|(c, _)| c.as_str()).collect();
        chats.sort_unstable();
        chats.dedup();
        let n = chats.len();
        if n >= INVITE_CHATS {
            self.warn(Kind::InviteLinks, n, now);
        }
    }

    fn message_text(&mut self, chat: &str, text: &str, now: Instant) {
        if text.trim().is_empty() {
            return;
        }
        if mass_mention(text) {
            self.count(Kind::Mentions, now);
        }
        if has_invite(text) {
            self.invite(chat, now);
        }
        let h = text_hash(text);
        self.texts.push_back((h, now));
        while self.texts.front().is_some_and(|(_, t)| now.duration_since(*t) > SAME_WINDOW) {
            self.texts.pop_front();
        }
        let n = self.texts.iter().filter(|(x, _)| *x == h).count();
        if n >= SAME_LIMIT {
            self.warn(Kind::SameMessage, n, now);
        }
    }
}

/// An API request is about to go out (once per request, not per retry).
pub fn note(method: &Method, path: &str, body: Option<&Value>) {
    note_at(method, path, body, Instant::now());
}

fn note_at(method: &Method, path: &str, body: Option<&Value>, now: Instant) {
    let Ok(mut st) = STATE.lock() else { return };
    st.count(Kind::ApiBurst, now);
    for kind in kinds(method, path) {
        st.count(kind, now);
        if kind == Kind::Messages {
            if let Some(text) = body.and_then(|b| b["content"].as_str()) {
                let chat = path.split('/').filter(|s| !s.is_empty()).nth(1).unwrap_or_default();
                st.message_text(chat, text, now);
            }
        }
    }
}

/// Discord answered 429.
pub fn rate_limited() {
    if let Ok(mut st) = STATE.lock() {
        st.count(Kind::RateLimited, Instant::now());
    }
}

/// Warnings waiting to be shown (cheap when there are none).
pub fn take() -> Vec<Warning> {
    if !PENDING.swap(false, Ordering::Relaxed) {
        return Vec::new();
    }
    STATE.lock().map(|mut st| std::mem::take(&mut st.pending)).unwrap_or_default()
}

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

    #[test]
    fn requests_count_as_the_right_kinds() {
        assert_eq!(kinds(&Method::POST, "/channels/1/messages"), vec![Kind::Messages]);
        assert_eq!(kinds(&Method::PUT, "/channels/1/messages/2/reactions/%F0%9F%91%8D/@me"), vec![Kind::Reactions]);
        assert_eq!(kinds(&Method::POST, "/invites/abc"), vec![Kind::Joins]);
        assert_eq!(kinds(&Method::PUT, "/users/@me/relationships/5"), vec![Kind::FriendList]);
        assert!(kinds(&Method::GET, "/channels/1/messages?limit=50").is_empty());
    }

    #[test]
    fn a_burst_warns_once_then_cools_down() {
        let mut st = State::default();
        let t0 = Instant::now();
        for i in 0..12 {
            st.count(Kind::Messages, t0 + Duration::from_millis(i * 300));
        }
        assert_eq!(st.pending.len(), 1);
        assert!(st.pending[0].text.starts_with("6 messages"));
    }

    #[test]
    fn spaced_out_messages_never_warn() {
        let mut st = State::default();
        let t0 = Instant::now();
        for i in 0..30 {
            st.count(Kind::Messages, t0 + Duration::from_secs(i * 3));
        }
        assert!(st.pending.is_empty());
    }

    #[test]
    fn the_same_text_three_times_warns() {
        let mut st = State::default();
        let t0 = Instant::now();
        for (i, text) in ["hi", "join my server", "JOIN my server ", "ok", "join my server"].iter().enumerate() {
            st.message_text("1", text, t0 + Duration::from_secs(i as u64 * 5));
        }
        assert_eq!(st.pending.len(), 1);
        assert_eq!(st.pending[0].kind, Kind::SameMessage);
    }

    #[test]
    fn mass_mentions_are_told_apart_from_a_few_pings() {
        assert!(!mass_mention("hey <@1> and <@!2>, look"));
        assert!(!mass_mention("<@1> <@1> <@1> <@1> <@1> <@1>"));
        assert!(mass_mention("<@1> <@2> <@!3> <@4> <@5>"));
        assert!(mass_mention("free nitro @everyone"));
        assert!(!mass_mention("<@&123> <@&124> <#5> <:a:6> <@x>"));
        let mut st = State::default();
        let t0 = Instant::now();
        st.message_text("1", "@here meeting", t0);
        assert!(st.pending.is_empty());
        st.message_text("2", "<@1> <@2> <@3> <@4> <@5> gg", t0 + Duration::from_secs(60));
        assert_eq!(st.pending[0].kind, Kind::Mentions);
    }

    #[test]
    fn one_invite_link_in_many_chats_warns() {
        assert!(has_invite("join https://Discord.gg/abc"));
        assert!(!has_invite("https://discord.com/channels/1/2"));
        let mut st = State::default();
        let t0 = Instant::now();
        // The same chat over and over is someone sharing their server.
        for i in 0..4 {
            st.message_text("10", &format!("discord.gg/abc #{i}"), t0 + Duration::from_secs(i * 30));
        }
        assert!(st.pending.is_empty());
        st.message_text("11", "come: discord.gg/abc", t0 + Duration::from_secs(150));
        st.message_text("12", "hey, discord.gg/abc", t0 + Duration::from_secs(180));
        assert_eq!(st.pending.len(), 1);
        assert_eq!(st.pending[0].kind, Kind::InviteLinks);
        assert!(st.pending[0].text.contains("3 different chats"));
    }

    #[test]
    fn a_message_body_counts_its_text() {
        let body = json!({ "content": "same" });
        let t0 = Instant::now() + Duration::from_secs(3600);
        for i in 0..3 {
            note_at(&Method::POST, "/channels/9/messages", Some(&body), t0 + Duration::from_secs(i * 20));
        }
        assert!(take().iter().any(|w| w.kind == Kind::SameMessage));
    }
}