Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

9.7 KB
Raw Blame
use lazy_static::lazy_static;
use regex::Regex;

#[cfg(test)]
mod test;

lazy_static! {
    static ref HEX_PATTERN: Regex = Regex::new(r"^[a-f0-9\-]{20,}$").unwrap();
    static ref UUID_PATTERN: Regex =
        Regex::new(r"^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$").unwrap();
}

/// Checks if an email address is likely a generic/automated system email
///
/// This function identifies common patterns in email addresses that typically
/// indicate automated senders rather than individual users.
pub fn is_generic_email(email: &str) -> bool {
    let email_lower = email.to_lowercase();

    // Split into local part and domain
    let (local_part, domain) = match email_lower.split_once('@') {
        Some(parts) => parts,
        None => return false, // Invalid email
    };

    // Check for automated email service domains first (most definitive)
    if is_automated_domain(domain) {
        return true;
    }

    // Check for obvious automated patterns in local part
    if contains_automated_keyword(local_part) {
        return true;
    }

    // Check if local part starts with automated prefix
    if starts_with_automated_prefix(local_part) {
        return true;
    }

    // Check for auto-generated local parts (numbers, UUIDs, hex strings)
    if is_autogenerated_local_part(local_part) {
        return true;
    }

    false
}

fn is_automated_domain(domain: &str) -> bool {
    const SYSTEM_DOMAINS: &[&str] = &[
        // Email service providers
        "sendgrid.net",
        "sendgrid.com",
        "mailchimp.com",
        "amazonses.com",
        "email.amazonses.com",
        "bounce.amazonses.com",
        "sparkpost.com",
        "mailgun.org",
        "mg.mailgun.org",
        "em.mailgun.org",
        "mailjet.com",
        "mandrillapp.com",
        "postmarkapp.com",
        "sendinblue.com",
        "klaviyo.com",
        "constantcontact.com",
        // CRM/Marketing platforms
        "salesforce.com",
        "salesforceiq.com",
        "hubspot.com",
        "marketo.com",
        "intercom.io",
        "intercom-mail.com",
        "campaign-archive.com",
        // Support platforms
        "zendesk.com",
        "freshdesk.com",
        "freshservice.com",
        // Google
        "notifications.google.com",
        "bounces.google.com",
        // ESP sending/bounce domains
        "mcsv.net",
        "mcdlv.net",
        "customeriomail.com",
        "sparkpostmail.com",
        "mtasv.net",
        "pipedrivemail.com",
        "mailersend.net",
        "mailerlite.com",
        "activehosted.com",
        "sailthru.com",
        "exacttarget.com",
        "smtp2go.com",
        "elasticemail.com",
        "sendpulse.com",
        "getresponse.com",
        "aweber.com",
        // Product notification domains (no human senders)
        "facebookmail.com",
        "docusign.net",
        "atlassian.net",
        "qemailserver.com",
    ];

    SYSTEM_DOMAINS
        .iter()
        .any(|d| domain == *d || domain.ends_with(&format!(".{}", d)))
}

fn contains_automated_keyword(local_part: &str) -> bool {
    // Keywords that strongly indicate automation when present anywhere
    const STRONG_KEYWORDS: &[&str] = &[
        "noreply",
        "no-reply",
        "no.reply",
        "no_reply",
        "donotreply",
        "do-not-reply",
        "do.not.reply",
        "do_not_reply",
        "unsubscribe",
        "unsub",
        "automated",
        "mailer-daemon",
        "postmaster",
        "notification",
        "newsletter",
        "invitation",
        "donotrespond",
        "do-not-respond",
        "do.not.respond",
        "do_not_respond",
    ];

    STRONG_KEYWORDS.iter().any(|kw| local_part.contains(kw))
}

fn starts_with_automated_prefix(local_part: &str) -> bool {
    const AUTOMATED_PREFIXES: &[&str] = &[
        // Reply/No-reply variants
        "reply",
        "noreply",
        "no-reply",
        "no.reply",
        "no_reply",
        "donotreply",
        "do-not-reply",
        "do.not.reply",
        "do_not_reply",
        // System/Auto
        "auto",
        "automated",
        "system",
        "daemon",
        "cron",
        "scheduler",
        "robot",
        "bot",
        // Notifications/Alerts
        "alert",
        "alerts",
        "notification",
        "notifications",
        "notify",
        "digest",
        "bulletin",
        "announcements",
        "weekly",
        "daily",
        "monthly",
        "reminder",
        "reminders",
        "message",
        "messages",
        // Calendar/Scheduling
        "calendar",
        "invite",
        "invites",
        "appointment",
        "appointments",
        "meeting",
        "meetings",
        // Support/Service
        "support",
        "help",
        "helpdesk",
        "service",
        "services",
        "customercare",
        "customer-care",
        "customer.care",
        "customerservice",
        "customer-service",
        "customer.service",
        // Admin/System
        "admin",
        "administrator",
        "webmaster",
        "postmaster",
        "sysadmin",
        "root",
        "ops",
        "devops",
        "monitor",
        "monitoring",
        "status",
        "logs",
        "error",
        "errors",
        // Accounts/Auth
        "account",
        "accounts",
        "activation",
        "registration",
        "registrations",
        "membership",
        "members",
        "fraud",
        "auth",
        "authentication",
        "login",
        "signin",
        "password",
        "reset",
        "otp",
        "2fa",
        "mfa",
        "token",
        "verify",
        "verification",
        "confirm",
        "confirmation",
        "security",
        "secure",
        // Billing/Transactions
        "billing",
        "invoice",
        "invoices",
        "payment",
        "payments",
        "transaction",
        "transactions",
        "refund",
        "subscription",
        "subscriptions",
        "renewal",
        "receipt",
        "receipts",
        "order",
        "orders",
        "statement",
        "statements",
        "payroll",
        "expense",
        "expenses",
        "rewards",
        "loyalty",
        "donation",
        "donations",
        // Shipping/Delivery
        "shipping",
        "delivery",
        "track",
        "tracking",
        "booking",
        "bookings",
        "reservation",
        "reservations",
        "ticket",
        "tickets",
        // Marketing/Comms
        "marketing",
        "promo",
        "promotions",
        "offers",
        "deals",
        "news",
        "newsletter",
        "updates",
        "update",
        "info",
        "information",
        "feedback",
        "survey",
        "surveys",
        "webinar",
        "webinars",
        "community",
        "onboarding",
        // Business departments
        "sales",
        "hr",
        "legal",
        "finance",
        "press",
        "media",
        "partnerships",
        "partners",
        "affiliates",
        "careers",
        "jobs",
        "applications",
        "events",
        "recruiting",
        "recruitment",
        "concierge",
        "report",
        "reports",
        // Dev/API
        "dev",
        "developer",
        "api",
        "test",
        "testing",
        "mailer",
        "mail",
        "bounce",
        "bounces",
        // Generic contact
        "contact",
        "team",
        "hello",
        "hi",
        "welcome",
    ];

    // Check if local part starts with prefix followed by a delimiter or end
    for prefix in AUTOMATED_PREFIXES {
        if local_part == *prefix {
            return true;
        }
        if let Some(remainder) = local_part.strip_prefix(prefix)
            && let Some(first_char) = remainder.chars().next()
            && matches!(first_char, '@' | '-' | '.' | '+' | '=' | '_' | '0'..='9')
        {
            // Must be followed by a delimiter, not a letter (to avoid matching "support" in "supportive")
            return true;
        }
    }

    false
}

fn is_autogenerated_local_part(local_part: &str) -> bool {
    // Too long - likely autogenerated
    if local_part.len() > 50 {
        return true;
    }

    // UUID pattern
    if UUID_PATTERN.is_match(local_part) {
        return true;
    }

    // Long hex string pattern
    if HEX_PATTERN.is_match(local_part) {
        return true;
    }

    // Purely numeric with delimiters (e.g., "123456", "123-456-789")
    if !local_part.is_empty()
        && local_part
            .chars()
            .all(|c| c.is_ascii_digit() || c == '.' || c == '-' || c == '_')
        && local_part.chars().any(|c| c.is_ascii_digit())
    {
        return true;
    }

    // Starts with "id" followed by only numbers (e.g., "id12345")
    if local_part.starts_with("id")
        && local_part.len() > 2
        && local_part[2..].chars().all(|c| c.is_ascii_digit())
    {
        return true;
    }

    // Starts with numbers followed by random-looking characters (e.g., "0000012345abcdef")
    let digit_prefix_count = local_part
        .chars()
        .take_while(|c| c.is_ascii_digit())
        .count();
    if digit_prefix_count >= 6 {
        return true;
    }

    false
}

/// Deduplicates a list of email addresses by normalizing them (removing + aliases)
pub fn dedupe_emails(emails: Vec<String>) -> Vec<String> {
    emails
        .into_iter()
        .map(|mut email| {
            // Remove everything from + to @ if + exists
            if let (Some(plus_pos), Some(at_pos)) = (email.find('+'), email.find('@'))
                && plus_pos < at_pos
            {
                email.drain(plus_pos..at_pos);
            }

            email
        })
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect()
}