Cotton code
357 lines · 11.9 KB · RustRaw
//! A sign-in code in a text message, as two typed facts: the `code`, and//! `code_for` — the service the text names, else the sender.//!//! WHY IT IS AN ENGINE'S FACT AND NOT A SENTENCE. iOS lets no app read SMS, so//! the serving Mac's reader is the only way a code a service texts the owner//! reaches Cotton; an engine signing in for the owner asks for the newest code//! for one service inside a window of time ([`newest_for`]) and reads the//! columns. Nothing here writes words about the code.//!//! WHY IT IS WITHHELD. A sign-in code is a credential for the minutes it//! lives. No MCP read lists one: [`withhold`] is what the assistant door runs//! over every answer that read chats, and the `code` column is filled by//! nothing an assistant can call.//!//! The reading is deliberately narrow. A code is a run of four to eight//! digits (or two runs of three, `123-456`, or Google's `G-123456`) near a//! word that says it is one — "code", "OTP", "verification", "password" — and//! never an amount, a date, a masked account (`XX1234`) or part of a longer//! number. A text that is not plainly a code reads as none.use std::borrow::Cow;use std::sync::LazyLock;use regex::Regex;/// What the reading found.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SignInCode {    /// The code as it is typed: its digits, and the `G-` a few services put    /// in front of them dropped.    pub code: String,    /// The service the text names, else the sender's name; none when neither    /// says anything.    pub code_for: Option<String>,}/// The words that say a number is a code. Matched as whole words, so/// "pincode" and "shipping" are not "pin".const KEYWORDS: [&str; 20] = [    "otp",    "code",    "passcode",    "password",    "pin",    "verification",    "verify",    "one-time",    "one time",    "2fa",    "two-factor",    "login",    "log in",    "log-in",    "sign in",    "sign-in",    "signin",    "authentication",    "authenticate",    "security",];/// How far a code may sit from the word that calls it one, in bytes.const NEAR: usize = 60;/// What a withheld code reads as.pub const WITHHELD: &str = "••••••";/// The code in `body`, and what it is for; `sender` is the sender's name or/// handle, used when the text names no service.pub fn read(body: &str, sender: Option<&str>) -> Option<SignInCode> {    let found = find(body)?;    let code_for = service(body).or_else(|| sender.and_then(sender_name));    Some(SignInCode {        code: found.code,        code_for,    })}/// `text` with every sign-in code in it withheld.pub fn withhold(text: &str) -> Cow<'_, str> {    match find(text) {        Some(found) => Cow::Owned(withhold_codes(text, std::slice::from_ref(&found.code))),        None => Cow::Borrowed(text),    }}/// `text` with every whole-token occurrence of each of `codes` withheld —/// for a line too short to say it is a code (a cut preview, a search/// snippet) whose code was found in a longer line beside it.pub fn withhold_codes(text: &str, codes: &[String]) -> String {    let mut out = String::with_capacity(text.len());    let mut rest = 0;    for token in tokens(text) {        if codes.iter().any(|code| *code == token.code) {            out.push_str(&text[rest..token.start]);            out.push_str(WITHHELD);            rest = token.end;        }    }    out.push_str(&text[rest..]);    out}/// The newest code for `service` among `rows` (body, sender, sent at), sent/// at or after `since` — the read the sign-in engine makes. `service`/// matches `code_for` either way round, ignoring case ("Google" finds/// "Google Account").pub fn newest_for<'a>(    rows: impl IntoIterator<Item = (&'a str, Option<&'a str>, &'a str)>,    service: &str,    since: &str,) -> Option<SignInCode> {    let wanted = service.trim().to_lowercase();    if wanted.is_empty() {        return None;    }    let mut best: Option<(&str, SignInCode)> = None;    for (body, sender, sent_at) in rows {        if sent_at < since || best.as_ref().is_some_and(|(at, _)| sent_at <= *at) {            continue;        }        let Some(code) = read(body, sender) else {            continue;        };        let names = code            .code_for            .as_deref()            .map(str::to_lowercase)            .unwrap_or_default();        if !names.is_empty() && (names.contains(&wanted) || wanted.contains(&names)) {            best = Some((sent_at, code));        }    }    best.map(|(_, code)| code)}struct Found {    code: String,}/// A digit token: where it stands, and its digits.struct Token {    start: usize,    end: usize,    code: String,}fn find(text: &str) -> Option<Found> {    if !text.bytes().any(|byte| byte.is_ascii_digit()) {        return None;    }    // ASCII lowering keeps every byte offset where it was.    let lower = text.to_ascii_lowercase();    let words = keyword_positions(&lower);    if words.is_empty() {        return None;    }    let mut best: Option<(usize, Token)> = None;    for token in tokens(text) {        let distance = words            .iter()            .map(|&(start, end)| {                if token.end <= start {                    start - token.end                } else if end <= token.start {                    token.start - end                } else {                    0                }            })            .min()            .unwrap_or(usize::MAX);        if distance <= NEAR && best.as_ref().is_none_or(|(near, _)| distance < *near) {            best = Some((distance, token));        }    }    best.map(|(_, token)| Found { code: token.code })}fn keyword_positions(lower: &str) -> Vec<(usize, usize)> {    let bytes = lower.as_bytes();    let mut found = Vec::new();    for word in KEYWORDS {        let mut from = 0;        while let Some(at) = lower[from..].find(word) {            let start = from + at;            let end = start + word.len();            let before = start.checked_sub(1).map(|index| bytes[index]);            let after = bytes.get(end).copied();            let alone = !before.is_some_and(|byte| byte.is_ascii_alphanumeric())                && !after.is_some_and(|byte| byte.is_ascii_alphanumeric());            if alone {                found.push((start, end));            }            from = end;        }    }    found}/// Every run of digits in `text` that could be a code.fn tokens(text: &str) -> Vec<Token> {    let bytes = text.as_bytes();    let digit = |index: usize| bytes.get(index).is_some_and(u8::is_ascii_digit);    let mut out = Vec::new();    let mut index = 0;    while index < bytes.len() {        if !digit(index) {            index += 1;            continue;        }        let start = index;        while digit(index) {            index += 1;        }        let mut end = index;        let mut code = text[start..end].to_string();        // `123-456` and `123 456`: two runs of three are one code.        if end - start == 3            && matches!(bytes.get(end), Some(b'-' | b' '))            && (1..=3).all(|step| digit(end + step))            && !digit(end + 4)        {            code.push_str(&text[end + 1..end + 4]);            end += 4;            index = end;        }        if let Some(token) = judged(text, start, end, code) {            out.push(token);        }    }    out}/// A run of digits that is a code's shape and is not an amount, a date, a/// masked account or a piece of a longer number.fn judged(text: &str, start: usize, end: usize, code: String) -> Option<Token> {    if !(4..=8).contains(&code.len()) {        return None;    }    let bytes = text.as_bytes();    let at = |index: Option<usize>| index.and_then(|index| bytes.get(index).copied());    let before = at(start.checked_sub(1));    let after = at(Some(end));    let mut start = start;    // Google's `G-123456`: the `G-` is part of the token, not of a word.    if before == Some(b'-') && at(start.checked_sub(2)) == Some(b'G') {        let lead = at(start.checked_sub(3));        if !lead.is_some_and(|byte| byte.is_ascii_alphanumeric()) {            start -= 2;        }    } else if before.is_some_and(|byte| byte.is_ascii_alphanumeric()) {        // XX1234, A/c1234, ID9876: a number glued to a word is not a code.        return None;    }    if after.is_some_and(|byte| byte.is_ascii_alphanumeric() || byte == b'%') {        return None;    }    // 12-10-2026, 5,000.00, 10:45, 192.168…: a run joined to another by a    // separator is a piece of something else.    let joined = |separator: Option<u8>, next: Option<u8>| {        matches!(separator, Some(b'-' | b'/' | b'.' | b',' | b':'))            && next.is_some_and(|byte| byte.is_ascii_digit())    };    if joined(before, at(start.checked_sub(2))) || joined(after, at(Some(end + 1))) {        return None;    }    // An amount: a currency within a few characters in front of it.    let lead = text[..start].trim_end().to_ascii_lowercase();    let lead = lead.trim_end_matches(['.', ':']).trim_end();    const CURRENCIES: [&str; 12] = [        "rs", "inr", "₹", "$", "€", "£", "usd", "eur", "gbp", "aed", "amt", "amount",    ];    if CURRENCIES.iter().any(|currency| lead.ends_with(currency)) {        return None;    }    Some(Token { start, end, code })}/// The service a text names: "Your Google verification code", "Amazon: …",/// "OTP for Rivermark Bank NetBanking".fn service(body: &str) -> Option<String> {    static YOUR: LazyLock<Regex> = LazyLock::new(|| {        Regex::new(            r"(?i:\byour)\s+([A-Z0-9][\w&'’]*(?:\.[\w&'’]+)*(?:\s+[A-Z0-9][\w&'’]*(?:\.[\w&'’]+)*){0,3})\s+(?i:(?:verification|login|log-in|sign-in|security|one-time|account|access)\s+)*(?i:code|otp|pin|passcode|password)\b",        )        .expect("the pattern")    });    static LEAD: LazyLock<Regex> = LazyLock::new(|| {        Regex::new(r"^\s*(?:\[#\]|<#>)?\s*([A-Z][\w&'’]*(?:\.[\w&'’]+)*(?:\s+[A-Z][\w&'’]*(?:\.[\w&'’]+)*){0,2})\s*:\s").expect("the pattern")    });    static FOR: LazyLock<Regex> = LazyLock::new(|| {        Regex::new(r"\b(?i:for|to|on|into|at|from)\s+(?:(?i:your)\s+)?([A-Z][\w&'’]*(?:\.[\w&'’]+)*(?:\s+[A-Z][\w&'’]*(?:\.[\w&'’]+)*){0,3})")            .expect("the pattern")    });    const NOT_A_SERVICE: [&str; 16] = [        "otp",        "code",        "rs",        "inr",        "do",        "never",        "please",        "the",        "this",        "you",        "your",        "it",        "verification",        "one-time",        "security",        "pin",    ];    let plausible = |name: &str| {        let name = name.trim().trim_end_matches(['.', ',', '’', '\'']);        let first = name            .split_whitespace()            .next()            .unwrap_or_default()            .to_lowercase();        (!name.is_empty() && !NOT_A_SERVICE.contains(&first.as_str())).then(|| name.to_string())    };    for pattern in [&*YOUR, &*LEAD, &*FOR] {        for found in pattern.captures_iter(body) {            if let Some(name) = found.get(1).and_then(|name| plausible(name.as_str())) {                return Some(name);            }        }    }    None}/// The sender as a name: a business header's own part (`AX-RVMKBK-S` reads/// `RVMKBK`), a name as it is, and a bare number as nothing.fn sender_name(sender: &str) -> Option<String> {    static HEADER: LazyLock<Regex> = LazyLock::new(|| {        Regex::new(r"^[A-Za-z]{2}-([A-Za-z0-9]{3,9})(?:-[A-Za-z])?$").expect("the pattern")    });    let sender = sender.trim();    if sender.is_empty()        || sender            .chars()            .all(|char| char.is_ascii_digit() || "+-() ".contains(char))    {        return None;    }    Some(        match HEADER.captures(sender).and_then(|found| found.get(1)) {            Some(own) => own.as_str().to_string(),            None => sender.to_string(),        },    )}#[cfg(test)]#[path = "sign_in_tests.rs"]mod tests;