Cotton code
383 lines · 14.6 KB · RustRaw
//! One way of reaching somebody, normalised: the person-handle kinds and//! their matching form (`cotton_store::protocol::person_handles` re-exports//! them), and a message contact's handle (`cotton_core::messages:://! resolve_contact` re-exports that half). No lookup, clock or mutation. The//! Worker asks through the boundary (`handles.normalize`, `handles.social`,//! `handles.from`).use crate::js::{js_trim, truthy_str};use crate::phone::Region;/// Mirrors `cotton_person_handles.kind` and `cotton_msg_contact_handles.kind`/// (less `cotton`, which is a Cotton account, not a way a person is reached).#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "snake_case")]pub enum HandleKind {    Phone,    Email,    Instagram,    Facebook,    Linkedin,}impl HandleKind {    pub const ALL: [HandleKind; 5] = [        HandleKind::Phone,        HandleKind::Email,        HandleKind::Instagram,        HandleKind::Facebook,        HandleKind::Linkedin,    ];    pub const fn as_str(self) -> &'static str {        match self {            HandleKind::Phone => "phone",            HandleKind::Email => "email",            HandleKind::Instagram => "instagram",            HandleKind::Facebook => "facebook",            HandleKind::Linkedin => "linkedin",        }    }    pub fn parse(kind: &str) -> Option<HandleKind> {        HandleKind::ALL.into_iter().find(|candidate| candidate.as_str() == kind)    }    /// A handle on a social site — a sender there has no phone.    pub const fn is_social(self) -> bool {        matches!(self, HandleKind::Instagram | HandleKind::Facebook | HandleKind::Linkedin)    }}impl std::fmt::Display for HandleKind {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(self.as_str())    }}/// Mirrors `cotton_person_handles.source` — where a handle came from.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum HandleSource {    /// Typed by the owner or an assistant on the person.    Manual,    /// The phone's contacts (or a contacts import).    Contacts,    /// Another import (a vCard, an export).    Import,    /// The owner confirmed a suggestion: this sender is this person.    Suggestion,    Whatsapp,    Instagram,    Facebook,    Linkedin,}impl HandleSource {    pub const fn as_str(self) -> &'static str {        match self {            HandleSource::Manual => "manual",            HandleSource::Contacts => "contacts",            HandleSource::Import => "import",            HandleSource::Suggestion => "suggestion",            HandleSource::Whatsapp => "whatsapp",            HandleSource::Instagram => "instagram",            HandleSource::Facebook => "facebook",            HandleSource::Linkedin => "linkedin",        }    }}/// The form a person's handle is stored and matched by, or `None` when there/// is nothing to keep (blank, or a social handle that is not one).////// ONE normaliser (PEOPLE BUILD 1): where [`normalize_contact_handle_in`] — the/// rule every chat contact's handle is made by — reads a value, a person's/// handle is exactly that value, so the two can only meet on the same string./// Where it does not, the handle is still kept as written, so nothing typed is/// lost: a short code or an extension an address book holds ("100", "x12")/// lower-cased and without spaces, an email that is not one ("asha", "a b@x")/// trimmed and lower-cased. A kept form never matches anybody ([`matchable`]).pub fn normalise_handle(kind: HandleKind, raw: &str) -> Option<String> {    normalise_handle_in(kind, raw, None)}/// [`normalise_handle`], with a phone written without its code read in the/// owner's `region` ([`crate::phone::normalize_phone_in`]).pub fn normalise_handle_in(kind: HandleKind, raw: &str, region: Option<Region>) -> Option<String> {    let trimmed = raw.trim();    if trimmed.is_empty() {        return None;    }    if let Some(handle) = normalize_contact_handle_in(kind, trimmed, region) {        return Some(handle.value);    }    match kind {        HandleKind::Phone => Some(without_spaces(&trimmed.to_lowercase())),        HandleKind::Email => Some(trimmed.to_lowercase()),        _ => None,    }}/// Whether a stored normalised handle is one a match may be made on: the one/// rule reads it as itself. A form kept only so it is not lost ("100", an/// email with no `@`) is not, so `who` never answers a person for it.pub fn matchable(kind: HandleKind, normalised: &str) -> bool {    normalize_contact_handle_in(kind, normalised, None).is_some_and(|handle| handle.value == normalised)}fn without_spaces(text: &str) -> String {    text.chars().filter(|ch| !ch.is_whitespace()).collect()}/// The site's own name for an account, from whatever a person pasted:/// `@Asha.Rao`, `instagram.com/asha.rao/`, `https://www.linkedin.com/in/asha-rao?trk=x`/// and `asha.rao` are each one handle. Lower-cased, the profile URL and a/// leading `@` stripped, and only the characters the site allows in a name —/// anything else is `None`, because a guessed handle could link the wrong/// person's messages.////// Idempotent: a normalised handle normalises to itself.pub fn social_handle(kind: HandleKind, raw: &str) -> Option<String> {    let mut text = raw.trim().to_lowercase();    for scheme in ["https://", "http://"] {        if let Some(rest) = text.strip_prefix(scheme) {            text = rest.to_string();        }    }    for host in ["www.", "m.", "mobile."] {        if let Some(rest) = text.strip_prefix(host) {            text = rest.to_string();        }    }    let hosts: &[&str] = match kind {        HandleKind::Instagram => &["instagram.com/", "instagr.am/"],        HandleKind::Facebook => &["facebook.com/", "fb.com/", "fb.me/"],        HandleKind::Linkedin => &["linkedin.com/in/", "linkedin.com/"],        HandleKind::Phone | HandleKind::Email => return None,    };    for host in hosts {        if let Some(rest) = text.strip_prefix(host) {            text = rest.to_string();            break;        }    }    // Facebook's numeric profile link names the account by its id.    if kind == HandleKind::Facebook {        if let Some(query) = text.strip_prefix("profile.php?") {            text = query                .split('&')                .find_map(|pair| pair.strip_prefix("id="))                .unwrap_or_default()                .to_string();        }    }    let text = text.split(['?', '#']).next().unwrap_or_default();    let text = text.trim_start_matches('@');    let name = text.split('/').next().unwrap_or_default();    let allowed = |ch: char| match kind {        HandleKind::Instagram => ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '.' || ch == '_',        HandleKind::Facebook => ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '.',        _ => ch.is_alphanumeric() || ch == '-' || ch == '_' || ch == '%',    };    let longest = match kind {        HandleKind::Instagram => 30,        HandleKind::Facebook => 50,        _ => 100,    };    if name.is_empty() || name.chars().count() > longest || !name.chars().all(allowed) {        return None;    }    Some(name.to_string())}/// One way of reaching somebody, NORMALISED — never as a source spelled it.#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]pub struct ContactHandle {    pub kind: HandleKind,    pub value: String,}/// A raw handle in the form the column's CHECKs accept, or `None`.////// A phone becomes digits — [`crate::phone::normalize_phone`], which is/// the port of the shared `normalizeContactPhone`, so a handle and `phone_e164`/// can never disagree about what a number is. An email is trimmed and/// lower-cased, and must contain an `@` with something either side — the same/// shape the CHECK asks for, asked here so a bad handle is a `None` a caller can/// decide about rather than a constraint failure mid-batch.////// Deliberately NOT a validator of deliverability: `x@y` is a legal handle and so/// is an Apple ID nobody can send mail to. The question this answers is "can this/// string be an identity in this file", not "is this a real mailbox".pub fn normalize_contact_handle(kind: HandleKind, raw: &str) -> Option<ContactHandle> {    normalize_contact_handle_in(kind, raw, None)}/// [`normalize_contact_handle`], with a phone written WITHOUT a code read in/// `region` — the owner's own number's country/// (`cotton_store::phone_fold::region_hint`), so an export's "098765 43210"/// is the contact an "+91 98765 43210" handle already is. With no region, as/// typed.pub fn normalize_contact_handle_in(    kind: HandleKind,    raw: &str,    region: Option<Region>,) -> Option<ContactHandle> {    if kind == HandleKind::Phone {        return crate::phone::normalize_phone_in(raw, region)            .map(|value| ContactHandle { kind, value });    }    if kind.is_social() {        return social_handle(kind, raw)            .map(|value| ContactHandle { kind, value });    }    // `trim()` is ECMAScript's whitespace class and `toLowerCase()` is the    // Unicode default case conversion — the same fold Rust's `to_lowercase`    // performs, final sigma included.    let value = js_trim(raw).to_lowercase();    if value        .chars()        .any(crate::js::is_js_whitespace)    {        return None;    }    let at = value.find('@')?;    if at == 0 || at == value.len() - 1 {        return None;    }    // One `@`, so a handle can never be ambiguous about which part is the domain.    if value[at + 1..].contains('@') {        return None;    }    Some(ContactHandle { kind, value })}/// The map key a handle uses — `kind:value`, so a number and an address never/// collide.pub fn handle_key(handle: &ContactHandle) -> String {    format!("{}:{}", handle.kind, handle.value)}/// The two ways a source may name somebody.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct ContactSource<'a> {    pub phone: Option<&'a str>,    pub email: Option<&'a str>,}/// The handle a caller's `{ phone?, email? }` names, phone first.////// Phone first because it is the identity every other part of the file already/// keys on — receipts, the guest path, the live socket — so a counterpart the/// source gave us both ways becomes the contact the rest of Cotton can already/// reach. The email is not lost: [`resolve_contact`] writes it as a second handle/// on the same contact the moment it is passed on its own./// A phone without a code is read in `region` ([`normalize_contact_handle_in`]).pub fn handle_from(source: &ContactSource<'_>, region: Option<Region>) -> Option<ContactHandle> {    // `if (source.phone)` is truthiness, so an empty string names nothing.    if let Some(raw) = truthy_str(source.phone) {        if let Some(phone) = normalize_contact_handle_in(HandleKind::Phone, raw, region) {            return Some(phone);        }    }    if let Some(raw) = truthy_str(source.email) {        if let Some(email) = normalize_contact_handle(HandleKind::Email, raw) {            return Some(email);        }    }    None}/// Every handle a source named, in the order [`handle_from`] prefers them.pub fn handles_from(source: &ContactSource<'_>, region: Option<Region>) -> Vec<ContactHandle> {    let mut out = Vec::new();    if let Some(phone) = truthy_str(source.phone)        .and_then(|raw| normalize_contact_handle_in(HandleKind::Phone, raw, region))    {        out.push(phone);    }    if let Some(email) = truthy_str(source.email)        .and_then(|raw| normalize_contact_handle(HandleKind::Email, raw))    {        out.push(email);    }    out}/// A batch that names no counterpart at all — the import engine's guard.////// The TypeScript throws an `AppError`; a pure Rust library returns, and `Display`/// is the thrown sentence VERBATIM so a handler can pass it to the error envelope/// unchanged.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]#[error(    "An imported message arrived with no usable phone or email and the batch names no counterpart")]pub struct NoUsableHandle;impl NoUsableHandle {    /// The `AppError` code the TypeScript raises, so a handler that already    /// switches on those strings keeps working.    pub const fn code(&self) -> &'static str {        "IMPORT_SHAPE"    }}/// A handle a caller insists on, or a loud refusal.pub fn require_handle(    source: &ContactSource<'_>,    region: Option<Region>,) -> Result<ContactHandle, NoUsableHandle> {    handle_from(source, region).ok_or(NoUsableHandle)}#[cfg(test)]mod tests {    use super::{matchable, normalise_handle, normalize_contact_handle, HandleKind};    /// RULE (PEOPLE BUILD 1, one normaliser): a person's handle and a chat    /// contact's handle have ONE match form. Where the contact rule reads a    /// value, the person rule stores exactly that; where it does not (a short    /// code, an email with no `@` or an inner space), the person keeps what was    /// typed, and that kept form never matches anybody.    #[test]    fn a_person_handle_and_a_contact_handle_have_one_match_form() {        let cases = [            (HandleKind::Phone, "+91 98765 43210"),            (HandleKind::Phone, "0091 98765 43210"),            (HandleKind::Phone, "100"),            (HandleKind::Phone, "x12"),            (HandleKind::Email, "  Asha@Example.COM "),            (HandleKind::Email, "asha"),            (HandleKind::Email, "a sha@example.com"),            (HandleKind::Email, "@example.com"),            (HandleKind::Email, "a@b@c"),            (HandleKind::Instagram, "@Asha.Rao"),        ];        for (kind, raw) in cases {            let person = normalise_handle(kind, raw);            match normalize_contact_handle(kind, raw) {                Some(contact) => {                    assert_eq!(person.as_deref(), Some(contact.value.as_str()), "{kind} {raw:?}");                    assert!(matchable(kind, &contact.value), "{kind} {raw:?}");                }                None => {                    if let Some(kept) = person {                        assert!(!matchable(kind, &kept), "{kind} {raw:?} kept as {kept:?} must never match");                    }                }            }        }    }/// RULE: A handle's wire kind and stored kind are the same identity; unknown kinds refuse instead of becoming a name-based membership guess.    #[test]fn a_handle_wire_kind_is_its_stored_kind() {    for kind in HandleKind::ALL {        let wire=serde_json::to_value(kind).unwrap();        assert_eq!(wire.as_str(),Some(kind.as_str()));        assert_eq!(serde_json::from_value::<HandleKind>(wire).unwrap(),kind);    }    assert!(serde_json::from_value::<HandleKind>(serde_json::json!("display_name")).is_err());}}