Cotton code
237 lines · 10.1 KB · RustRaw
//! MAIL THAT ARRIVES ON A PERSON'S OWN DOMAIN (22 Nov 2026;//! assets/design/chat/OWN-MAIL.md): the raw message Cloudflare's Email//! Routing hands the Worker → the very rows the Mac would write for it, so a//! message that reaches Cotton by both roads (the domain, and the Gmail box it//! is still forwarded to) lands on one `email` row.//!//! The Worker runs this as WASM (`mail_arrive`, `mail_attachment` in//! cotton-rules-wasm), and the phone's core runs it for a message the Worker//! kept only raw. Nothing here reads a clock or a database: the Worker hands//! in the time it received the message.//!//! What it answers://!//! ```json//! { "email": { "id": "…", "data": { …the email row… } },//!   "thread": { "id": "…", "key": "imap:root@example.org", "data": { …a new thread's row… } },//!   "participants": [{ "id": "…", "data": { "thread_id", "email", "display_name", "role" } }],//!   "messageId": "<abc@example.org>", "inReplyTo": "<…>" | null, "references": ["<…>"],//!   "attachments": [{ "index": 0, "name": "menu.pdf", "mime": "application/pdf", "size": 7 }],//!   "auth": { "spf": "pass", "dkim": "pass", "dmarc": "pass" } | null,//!   "from": "ada@example.org", "subject": "Re: Lunch" }//! ```use mail_parser::{HeaderValue, MessageParser};use serde_json::{json, Map, Value};use super::map::{Ids, Page};use super::mime::{decode, GmailFacts, MailFlags, Skip};use crate::fingerprint::email::strip_reply_prefixes;use crate::js;/// The authserv-id of the `Authentication-Results` Cloudflare prepends: only/// the first such header, from this id, is Cloudflare's own verdict.pub const CLOUDFLARE_AUTHSERV: &str = "mx.cloudflare.net";/// What one arrival is about.#[derive(Debug, Clone)]pub struct Arriving<'a> {    /// The person's database id: the namespace every mail id is made under.    pub database: &'a str,    /// The address it was delivered to (the envelope's RCPT TO), lower-cased.    pub account: &'a str,    /// When the Worker received it, in milliseconds: its date when the    /// `Date` header is not believable.    pub received: Option<i64>,    /// What an IMAP read said of it, when Cotton fetched it from a mailbox (Post CONTRACT row 13) rather than    /// receiving it on the person's own domain: its labels and flags then say its state, as the Mac's rows do.    pub fetched: Option<Fetched>,}/// One message as Cotton's fetcher read it over IMAP: Gmail's ids and labels when the server is Gmail, its flags.#[derive(Debug, Clone, Default)]pub struct Fetched {    pub msgid: Option<u64>,    pub thrid: Option<u64>,    /// `X-GM-LABELS` as IMAP spells them (`\Inbox`, `Receipts`); empty on a server without them.    pub gm_labels: Vec<String>,    /// `FLAGS` (`\Seen`, `\Flagged`).    pub flags: Vec<String>,    /// Whether it was read from the Inbox (a server without Gmail's labels).    pub in_inbox: bool,}/// Why a message was kept aside unread, as a code the raw-mail list stores/// beside it (`/v1/mail/raw`): `refused:<label>`, `not_mail`, `no_date` (no/// believable Date header and no time it was received) or `no_sender`.fn skip_words(skip: Skip) -> String {    match skip {        Skip::Refused(label) => format!("refused:{label}"),        Skip::Missing => "not_mail".to_string(),        Skip::NoDate => "no_date".to_string(),        Skip::NoSender => "no_sender".to_string(),    }}/// Message ids as their header's text says them, each in angle brackets.fn ids_of(value: &HeaderValue<'_>) -> Vec<String> {    value        .as_text_list()        .map(|ids| ids.iter().map(|id| format!("<{id}>")).collect())        .unwrap_or_default()}/// Cloudflare's own SPF, DKIM and DMARC results: the FIRST/// `Authentication-Results` header, and only when Cloudflare wrote it (any/// later one may be the sender's own, Email handler › Authentication results).pub fn cloudflare_auth(raw: &[u8]) -> Option<Value> {    let message = MessageParser::default().parse_headers(raw)?;    let first = message        .headers()        .iter()        .find(|h| h.name().eq_ignore_ascii_case("Authentication-Results"))?;    let text = match first.value() {        HeaderValue::Text(text) => text.to_string(),        HeaderValue::TextList(list) => list.join(" "),        _ => std::str::from_utf8(&raw[first.offset_start() as usize..first.offset_end() as usize]).ok()?.to_string(),    };    let text = text.replace(['\r', '\n'], " ");    let authserv = text.split(';').next()?.trim().split_whitespace().next()?.to_ascii_lowercase();    if authserv != CLOUDFLARE_AUTHSERV {        return None;    }    let mut out = Map::new();    for method in ["spf", "dkim", "dmarc"] {        let result = text            .split(';')            .skip(1)            .map(str::trim)            .find_map(|part| {                let (name, rest) = part.split_once('=')?;                (name.trim().eq_ignore_ascii_case(method)).then(|| rest.split_whitespace().next().unwrap_or("").to_ascii_lowercase())            })            .unwrap_or_else(|| "none".to_string());        out.insert(method.to_string(), Value::from(result));    }    Some(Value::Object(out))}/// The raw message → its rows, as the module's head says.pub fn arrive(raw: &[u8], at: &Arriving<'_>) -> Result<Value, String> {    let account = at.account.trim().to_lowercase();    let gmail = at.fetched.as_ref().filter(|f| f.msgid.is_some());    let labels = gmail.map(|f| super::labels::api_labels(&f.gm_labels, &f.flags)).unwrap_or_default();    let facts = GmailFacts { received: at.received, msgid: gmail.and_then(|f| f.msgid), thrid: gmail.and_then(|f| f.thrid), labels: labels.clone() };    let mut decoded = decode(raw, &account, &facts).map_err(skip_words)?;    // New mail on the domain is unread (nothing has read it yet); fetched mail says its own state, as its flags do.    decoded.flags = Some(match &at.fetched {        Some(f) => MailFlags::of(&f.flags),        None => MailFlags { unread: true, starred: false },    });    let ids = Ids::new(at.database);    let row = Page::new().email(&ids, &decoded)?;    let mut data = match row.data {        Value::Object(map) => map,        _ => return Err("mapper_no_row".to_string()),    };    match &at.fetched {        // Gmail: the mapper wrote labels, unread, starred and in_inbox from the labels; sent mail is the person's own.        Some(_) if gmail.is_some() => {            data.insert("direction".into(), Value::from(if labels.iter().any(|l| l == "SENT") { "out" } else { "in" }));        }        Some(f) => {            data.insert("direction".into(), Value::from("in"));            data.insert("in_inbox".into(), Value::from(f.in_inbox));        }        None => {            data.insert("direction".into(), Value::from("in"));            data.insert("in_inbox".into(), Value::from(true));        }    }    let message = MessageParser::default().parse(raw).ok_or("not_mail")?;    let in_reply_to = ids_of(message.in_reply_to()).into_iter().next();    let references = ids_of(message.references());    // What a reply from Comms needs to thread (In-Reply-To, References): the header's own ids.    data.insert("message_id".into(), decoded.message_id.clone().map_or(Value::Null, Value::from));    data.insert("message_refs".into(), if references.is_empty() { Value::Null } else { Value::from(references.join(" ")) });    // A new conversation's row; for one already held only `last_at` moves    // (its clear column), which the Worker does itself.    let thread = json!({        "id": row.thread_id,        "key": row.thread_key,        "data": {            "external_key": row.thread_key,            "subject": if row.thread_subject.is_empty() { Value::Null } else { Value::from(row.thread_subject.clone()) },            "first_at": row.sent_at,            "last_at": row.sent_at,            "email_count": 1,            "sender_address": data.get("from_email").cloned().unwrap_or(Value::Null),        },    });    // Each address once, its first role (from, then to, then cc), as the    // Mac's fold starts a thread.    let mut seen: Vec<String> = Vec::new();    let mut participants = Vec::new();    for (address, name, role) in &row.addresses {        if address.is_empty() || seen.contains(address) {            continue;        }        seen.push(address.clone());        participants.push(json!({            "id": ids.participant(&row.thread_id, address),            "data": { "thread_id": row.thread_id, "email": address, "display_name": name, "role": role },        }));    }    let attachments: Vec<Value> = decoded        .attachments        .iter()        .enumerate()        .map(|(index, a)| json!({ "index": index, "name": a.name, "mime": a.mime, "size": a.size }))        .collect();    Ok(json!({        "email": { "id": row.id, "data": Value::Object(data) },        "thread": thread,        "participants": participants,        "messageId": decoded.message_id,        "inReplyTo": in_reply_to,        "references": references,        "attachments": attachments,        "auth": cloudflare_auth(raw),        "from": decoded.from.email.to_lowercase(),        "subject": decoded.subject,        "subjectRoot": strip_reply_prefixes(&decoded.subject),        "sentAt": row.sent_at,        "sentMs": js::parse_date_ms(&row.sent_at),    }))}/// The decoded bytes of the `index`th attachment, in the order [`arrive`]/// lists them; `None` past the last.pub fn attachment(raw: &[u8], index: usize) -> Option<Vec<u8>> {    let message = MessageParser::default().parse(raw)?;    let part = message.attachments().nth(index)?;    Some(part.contents().to_vec())}/// The kinds of file Cotton never opens for the person (OWN-MAIL.md,/// "Spam and viruses"): they run code. Offered only to Save.pub const RUNS_CODE: &[&str] = &[    "exe", "scr", "js", "vbs", "bat", "cmd", "msi", "jar", "apk", "com", "pif", "ps1", "docm", "xlsm", "pptm",];/// Whether an attachment named `name` is of a kind that runs code.pub fn runs_code(name: &str) -> bool {    name.rsplit_once('.')        .map(|(_, ext)| RUNS_CODE.contains(&ext.to_ascii_lowercase().as_str()))        .unwrap_or(false)}#[cfg(test)]#[path = "arrive_tests.rs"]mod tests;