//! The owner's acts on his mail from Comms, done in his mailbox by this Mac (chat CONTRACT "Senders 3: what the Mac //! keeps, and the mail acts it carries out" and "Senders 3, step 5"; coordinator, 24 Nov 2026: "build the Mac half //! after MAIL HISTORY, never EXPUNGE"). //! //! The phone files one `mail` outbox row per act, drained with Mail to Trash's ([`super::trash::drain`]): //! //! | kind | the row names | what the Mac does | //! |---|---|---| //! | `mark_read`, `mark_unread` | `target`: the mail's `external_id` | set or clear `\Seen` | //! | `archive` | `target` | Gmail: clear the `\Inbox` label (it stays in All Mail); another server: move it to its `\Archive` | //! | `trash` | `target` | move it to the account's Trash | //! | `unsubscribe` | `target`, `to`: the sender | RFC 8058's one-click POST when the mail offers it; else the sender joins this Mac's own list and what arrives from them goes to Trash from then on | //! | `sender_archive` | `to` | every message from `to` out of the Inbox; answers `moved` | //! //! A mail is found by what the person's database keeps of it ([`Mail`]): Gmail's own id (`X-GM-MSGID`), else its //! Message-ID. One the mailbox no longer has fails in the contract's words, [`GONE`]. //! //! What it writes: `\Seen`, Gmail's `\Inbox` label ([`super::client::Mark`] can say nothing else), and a move to //! Trash or the Archive. Never `\Deleted`, never EXPUNGE: what goes to Trash stays there for the provider's own time //! (Gmail: 30 days) and the owner can take it back there. Tests run against fake servers on this machine's loopback. use std::time::Duration; use serde_json::{Map, Value}; use super::client::{ImapClient, Mark}; use super::proto::quote; use super::tally::Tally; use super::trash::{address_of, matching, matching_from, place, Counted, TrashError, BATCH}; pub const MARK_READ: &str = "mark_read"; pub const MARK_UNREAD: &str = "mark_unread"; pub const ARCHIVE: &str = "archive"; pub const TRASH: &str = "trash"; pub const UNSUBSCRIBE: &str = "unsubscribe"; pub const SENDER_ARCHIVE: &str = "sender_archive"; /// Bring a mail's designed page and its attachments ([`super::page`]), asked when he opens it on a phone. pub const MAIL_PAGE: &str = "mail_page"; /// The kinds of one mail, named by `target`. pub const ONE_MAIL: [&str; 4] = [MARK_READ, MARK_UNREAD, ARCHIVE, TRASH]; /// The contract's words for a mail the mailbox no longer has. pub const GONE: &str = "This email is no longer in your mail."; /// What an unsubscribe answers in `sent_external_id`. pub const ONE_CLICK: &str = "one_click"; pub const TRASH_ON_ARRIVAL: &str = "trash_on_arrival"; /// How long a one-click POST may take. const POST_WAIT: Duration = Duration::from_secs(20); /// A mail as the person's database keeps it, as much as finding it and unsubscribing need. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Mail { /// Gmail's id, as the Gmail API spells it (hex of `X-GM-MSGID`). pub gmail_id: Option, pub message_id: Option, pub list_unsubscribe: Option, pub list_unsubscribe_post: Option, } impl Mail { pub fn of_row(row: &Map) -> Mail { let text = |key: &str| row.get(key).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); Mail { gmail_id: text("gmail_id"), message_id: text("message_id"), list_unsubscribe: text("list_unsubscribe"), list_unsubscribe_post: text("list_unsubscribe_post"), } } } /// What the drain is lent for these acts. pub struct Helps<'a> { /// The mail an act names (its `external_id`), as the person's database holds it. pub mail: &'a dyn Fn(&str) -> Option, /// RFC 8058's POST to a List-Unsubscribe https link: [`post_one_click`], a loopback fake in tests. pub post: &'a dyn Fn(&str) -> Result<(), String>, /// This Mac's own list of senders whose arrivals go to Trash. pub listed: Option<&'a Tally>, /// Lands a mail's page and attachments from its whole message (the `mail_page` act): the mail's `external_id` /// and the message's bytes. Answers what it kept, as the row's answer says it. pub land_page: &'a dyn Fn(&str, &[u8]) -> Result, /// Erases the person's email rows of these mails, which a sender's Delete everything just moved to Trash (DELETE /// FAST question 2), and a conversation left with none. Answers how many rows went. pub erase: &'a dyn Fn(&[super::trash::GoneMail]) -> Result, /// Take up again the rows of these kinds a Mac before this one failed ([`OLD_REFUSALS`]); the app asks it on its /// first mail run after a launch. pub retry_failed: bool, } /// What a Mac before build 8 answered for the acts it could not do yet: "Count first, then move." for a /// `sender_trash` with no count, and "Not something mail can do." for every other kind here. This Mac never says /// the first, and says the second only of a kind it does not take, so a row failed so is taken up again once. pub const OLD_REFUSALS: [&str; 2] = ["Count first, then move.", "Not something mail can do."]; /// Where the mail an act names is looked for. struct Spot { gmail: bool, mailbox: String, archive: Option, } fn spot(client: &mut ImapClient) -> Result { let gmail = client.can("X-GM-EXT-1"); let uses = client.special_use()?; let mailbox = if gmail { uses.all.clone().unwrap_or_else(|| "INBOX".to_string()) } else { "INBOX".to_string() }; Ok(Spot { gmail, mailbox, archive: uses.archive }) } /// The UID of `mail` in the mailbox [`spot`] names, opened to be written. fn locate(client: &mut ImapClient, spot: &Spot, mail: &Mail) -> Result { client.select(&spot.mailbox)?; let gmail_id = mail.gmail_id.as_deref().filter(|_| spot.gmail).and_then(|hex| u64::from_str_radix(hex, 16).ok()); let hits = match (gmail_id, mail.message_id.as_deref()) { (Some(id), _) => client.uid_search(&format!("X-GM-MSGID {id}"))?, (None, Some(message_id)) => { let bare = message_id.trim().trim_start_matches('<').trim_end_matches('>'); match quote(bare).filter(|_| !bare.is_empty()) { Some(quoted) => client.uid_search(&format!("HEADER Message-ID {quoted}"))?, None => Vec::new(), } } (None, None) => Vec::new(), }; hits.into_iter().max().ok_or(TrashError::Gone) } /// One of [`ONE_MAIL`] on `mail`. pub fn one(client: &mut ImapClient, kind: &str, mail: &Mail) -> Result<(), TrashError> { if kind == TRASH { let place = place(client)?; let spot = Spot { gmail: client.can("X-GM-EXT-1"), mailbox: place.mailbox.clone(), archive: None }; let uid = locate(client, &spot, mail)?; return Ok(client.uid_move(&uid.to_string(), &place.trash, place.copy)?); } let spot = spot(client)?; if kind == ARCHIVE && !spot.gmail { // Checked before anything is opened to be written. let Some(archive) = spot.archive.clone() else { return Err(TrashError::NoArchive) }; if !client.can("MOVE") { return Err(TrashError::CannotMove); } let uid = locate(client, &spot, mail)?; return Ok(client.uid_move(&uid.to_string(), &archive, false)?); } let uid = locate(client, &spot, mail)?; match kind { MARK_READ => client.uid_store(&uid.to_string(), Mark::Seen, true)?, MARK_UNREAD => client.uid_store(&uid.to_string(), Mark::Seen, false)?, ARCHIVE => { // Taken off in All Mail (`spot`), then read back by its labels (SENDERS TRUE). client.uid_store(&uid.to_string(), Mark::Inbox, false)?; if !labelled_inbox(client, &[uid])?.is_empty() { return Err(TrashError::KeptIt); } } _ => return Err(TrashError::NotAnAct(kind.to_string())), } Ok(()) } /// The whole message of `mail`, read without marking it read; refused over [`super::page::MESSAGE_MAX`]. pub fn whole(client: &mut ImapClient, mail: &Mail) -> Result, TrashError> { let spot = spot(client)?; let uid = locate(client, &spot, mail)?; let sized = client.uid_fetch(&uid.to_string(), "UID RFC822.SIZE", None)?; if sized.iter().find(|f| f.uid == uid).and_then(|f| f.size).is_some_and(|size| size > super::page::MESSAGE_MAX) { return Err(TrashError::TooBig); } let fetched = client.uid_fetch(&uid.to_string(), "UID BODY.PEEK[]", None)?; fetched.into_iter().find(|f| f.uid == uid).and_then(|f| f.body).ok_or(TrashError::Gone) } /// What a sender's archive answers in `sent_external_id` once it read the Inbox back (SENDERS TRUE). pub const READ_BACK: &str = "read_back"; /// Of `uids` in the Gmail mailbox open now, those that carry the Inbox label, by their labels (exact at once, unlike /// Gmail's search). fn labelled_inbox(client: &mut ImapClient, uids: &[u32]) -> Result, TrashError> { let mut out = Vec::new(); for batch in uids.chunks(BATCH) { let set: Vec = batch.iter().map(u32::to_string).collect(); for fetched in client.uid_fetch(&set.join(","), "UID X-GM-LABELS", None)? { if batch.contains(&fetched.uid) && fetched.gm_labels.iter().any(|l| l.trim_start_matches('\\').eq_ignore_ascii_case("inbox")) { out.push(fetched.uid); } } } out.sort_unstable(); out.dedup(); Ok(out) } /// `address`'s mail in the Inbox below `below` (all, at 0), in the mailbox [`spot`] names, open now. fn in_inbox(client: &mut ImapClient, spot: &Spot, address: &str, below: u32) -> Result, TrashError> { let theirs = matching(client, address, below)?; if spot.gmail { labelled_inbox(client, &theirs) } else { Ok(theirs) } } /// Where a sender's mail in the Inbox is read and archived: Gmail's All Mail, where the Inbox label can be taken off /// (in INBOX itself Gmail answers OK and keeps it: build 8 archived nothing so, ACTS-CHECK 24 Nov 2026); any other /// server's INBOX, moved to its `\Archive`. Checked before anything is opened. fn inbox_spot(client: &mut ImapClient) -> Result<(Spot, String), TrashError> { let spot = spot(client)?; if spot.gmail { let mailbox = spot.mailbox.clone(); return Ok((spot, mailbox)); } if spot.archive.is_none() { return Err(TrashError::NoArchive); } if !client.can("MOVE") { return Err(TrashError::CannotMove); } Ok((spot, "INBOX".to_string())) } /// Count `address`'s mail in the Inbox, read only (EXAMINE): what Archive everything would take. pub fn inbox_of(client: &mut ImapClient, address: &str) -> Result { let address = address_of(address)?; let (spot, mailbox) = inbox_spot(client)?; let state = client.examine(&mailbox)?; let uids = in_inbox(client, &spot, &address, 0)?; Ok(Counted { mailbox, uid_validity: state.uid_validity, uid_below: state.uid_next, uids }) } /// What a sender's archive did, read back. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Archived { /// Left the Inbox. pub moved: usize, /// Still in the Inbox after it was asked. pub kept: usize, } /// Take out of the Inbox the set [`inbox_of`] fixed (`uid_validity`, `uid_below`; at most `at_most`, the count he /// was told), [`BATCH`] at a time, then read the Inbox back: what truly left it, and what Gmail kept. pub fn sender_archive(client: &mut ImapClient, address: &str, uid_validity: u32, uid_below: u32, at_most: Option) -> Result { let address = address_of(address)?; let (spot, mailbox) = inbox_spot(client)?; let state = client.select(&mailbox)?; if state.uid_validity != uid_validity { return Err(TrashError::Renumbered); } let uids = in_inbox(client, &spot, &address, uid_below)?; if at_most.is_some_and(|most| uids.len() > most) { return Err(TrashError::MoreThanCounted); } for batch in uids.chunks(BATCH) { let set: Vec = batch.iter().map(u32::to_string).collect(); match &spot.archive { Some(archive) if !spot.gmail => client.uid_move(&set.join(","), archive, false)?, _ => client.uid_store(&set.join(","), Mark::Inbox, false)?, } } // What the server holds now, not what it answered. let kept = in_inbox(client, &spot, &address, uid_below)?.into_iter().filter(|uid| uids.contains(uid)).count(); Ok(Archived { moved: uids.len() - kept, kept }) } /// The https link of a mail that offers RFC 8058's one-click: `List-Unsubscribe-Post: List-Unsubscribe=One-Click` /// beside a `List-Unsubscribe` with an ``. pub fn one_click_link(mail: &Mail) -> Option { let offered = mail.list_unsubscribe_post.as_deref()?.to_ascii_lowercase().replace(' ', "").contains("list-unsubscribe=one-click"); if !offered { return None; } mail.list_unsubscribe.as_deref()?.split(',').filter_map(|part| { let part = part.trim(); let inner = part.strip_prefix('<')?.strip_suffix('>')?.trim(); let url = url::Url::parse(inner).ok()?; (url.scheme() == "https" && url.host_str().is_some()).then(|| inner.to_string()) }).next() } /// RFC 8058's one-click: a POST of `List-Unsubscribe=One-Click` to the https link, no cookies, nothing of his. pub fn post_one_click(link: &str) -> Result<(), String> { post_click(link, "https") } /// [`post_one_click`] from a client `builder` of the caller's: the Mac passes a fresh one; tests/mail_acts_edges.rs /// one that also trusts its loopback server's own certificate (`add_root_certificate`, never anything looser). pub fn post_one_click_with(builder: reqwest::blocking::ClientBuilder, link: &str) -> Result<(), String> { post_click_with(builder, link, "https") } /// Whether a redirect of the one-click POST is followed. Only 307 and 308 keep the method and the body: a 301, /// 302 or 303 is followed as a GET with no body, which unsubscribes no one, and its page's 200 would read as done /// (FAKES AUDIT, 24 Nov 2026: the test's closure always said OK). Such a redirect is a click not taken, and his /// word falls back to Trash on arrival. Followed only to the same scheme, at most five. fn follows(status: u16, scheme: &str, wanted: &str, hops: usize) -> Result<(), &'static str> { if status != 307 && status != 308 { Err("the sender's server redirected the click to a page, so it was not taken") } else if scheme != wanted { Err("a redirect away from https") } else if hops >= 5 { Err("too many redirects") } else { Ok(()) } } fn post_click(link: &str, scheme: &'static str) -> Result<(), String> { post_click_with(reqwest::blocking::Client::builder(), link, scheme) } fn post_click_with(builder: reqwest::blocking::ClientBuilder, link: &str, scheme: &'static str) -> Result<(), String> { let url = url::Url::parse(link).map_err(|e| e.to_string())?; if url.scheme() != scheme { return Err("not an https link".to_string()); } let client = builder .timeout(POST_WAIT) .redirect(reqwest::redirect::Policy::custom(move |attempt| match follows(attempt.status().as_u16(), attempt.url().scheme(), scheme, attempt.previous().len()) { Ok(()) => attempt.follow(), Err(why) => attempt.error(why), })) .user_agent("Cotton") .build() .map_err(|e| e.to_string())?; let answer = client .post(url) .header(reqwest::header::CONTENT_TYPE, "application/x-www-form-urlencoded") .body("List-Unsubscribe=One-Click") .send() .map_err(|e| { // reqwest's own words hide the reason a redirect was refused: say the whole chain. let mut said = e.to_string(); let mut source = std::error::Error::source(&e); while let Some(cause) = source { said.push_str(&format!(": {cause}")); source = cause.source(); } said })?; if answer.status().is_success() { Ok(()) } else { Err(format!("the sender's server answered {}", answer.status().as_u16())) } } /// An unsubscribe: one click where the mail offers it and the sender's server takes it; else `to` joins this Mac's /// list from the mailbox's next UID on. Answers [`ONE_CLICK`] or [`TRASH_ON_ARRIVAL`], with why the sender's server /// did not take the click when it was tried (`post_one_click`'s words; CONTRACT "ARCHIVE COUNT", for site-words). pub fn unsubscribe(client: &mut ImapClient, helps: &Helps<'_>, account: &str, target: &str, to: &str) -> Result<(&'static str, Option), TrashError> { let mail = (!target.is_empty()).then(|| (helps.mail)(target)).flatten(); let mut refused = None; if let Some(link) = mail.as_ref().and_then(one_click_link) { match (helps.post)(&link) { Ok(()) => return Ok((ONE_CLICK, None)), // A refused or unreachable link: his word still stands, so their mail goes to Trash from now on. Err(why) => refused = Some(why), } } let address = address_of(to)?; let Some(listed) = helps.listed else { return Err(TrashError::NoList) }; let place = place(client)?; let state = client.examine(&place.mailbox)?; listed.listen(account, &address, state.uid_validity, state.uid_next).map_err(|_| TrashError::NoList)?; Ok((TRASH_ON_ARRIVAL, refused)) } /// Mail that arrived from a listed sender since the last look, to Trash. Answers how many moved. pub fn sweep(client: &mut ImapClient, listed: &Tally, account: &str) -> Result { let senders = listed.listened(account).map_err(|_| TrashError::NoList)?; if senders.is_empty() { return Ok(0); } let place = place(client)?; let mut moved = 0; for (address, validity, since) in senders { let state = client.select(&place.mailbox)?; if state.uid_validity != validity { // Renumbered: what came before cannot be told apart, so the list starts again from now. listed.listen(account, &address, state.uid_validity, state.uid_next).map_err(|_| TrashError::NoList)?; continue; } let uids = matching_from(client, &address, since.max(1), 0)?; for batch in uids.chunks(BATCH) { let set: Vec = batch.iter().map(u32::to_string).collect(); client.uid_move(&set.join(","), &place.trash, place.copy)?; } moved += uids.len(); listed.listen(account, &address, validity, state.uid_next.max(since)).map_err(|_| TrashError::NoList)?; } Ok(moved) } /// Whether `kind` is one this module does. pub fn takes(kind: &str) -> bool { ONE_MAIL.contains(&kind) || kind == UNSUBSCRIBE || kind == SENDER_ARCHIVE || kind == MAIL_PAGE } #[cfg(test)] mod tests { use super::*; #[test] fn one_click_needs_the_post_header_and_an_https_link() { let mail = |unsub: &str, post: Option<&str>| Mail { list_unsubscribe: Some(unsub.into()), list_unsubscribe_post: post.map(str::to_string), ..Mail::default() }; assert_eq!( one_click_link(&mail(", ", Some("List-Unsubscribe=One-Click"))).as_deref(), Some("https://shop.invented/u/1?x=2") ); assert_eq!(one_click_link(&mail("", None)), None, "no one-click without its header"); assert_eq!(one_click_link(&mail("", Some("List-Unsubscribe=One-Click"))), None, "https only"); assert_eq!(one_click_link(&mail("", Some("List-Unsubscribe=One-Click"))), None); assert!(post_one_click("http://shop.invented/u/1").is_err(), "never a plain http POST"); } } #[cfg(test)] mod one_click_tests { //! The one-click POST against a real local server (plain http here, the only difference from a sender's https), //! which answers as senders do: taken, or redirected. use std::io::{BufRead, BufReader, Read, Write}; use std::net::TcpListener; use std::sync::{Arc, Mutex}; /// A server answering each request with the next of `answers` (a status and a Location), recording each /// request's method, path and body. fn server(answers: Vec<(u16, Option<&'static str>)>) -> (String, Arc>>) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); let heard = Arc::new(Mutex::new(Vec::new())); let kept = heard.clone(); let here = base.clone(); std::thread::spawn(move || { for (stream, (status, location)) in listener.incoming().zip(answers) { let mut stream = stream.unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut line = String::new(); reader.read_line(&mut line).unwrap(); let mut words = line.split_whitespace(); let (method, path) = (words.next().unwrap_or("").to_string(), words.next().unwrap_or("").to_string()); let mut length = 0usize; loop { let mut header = String::new(); reader.read_line(&mut header).unwrap(); if header.trim().is_empty() { break; } if let Some(v) = header.to_ascii_lowercase().strip_prefix("content-length:") { length = v.trim().parse().unwrap_or(0); } } let mut body = vec![0u8; length]; reader.read_exact(&mut body).unwrap(); kept.lock().unwrap().push((method, path, String::from_utf8_lossy(&body).into_owned())); let location = location.map(|l| format!("Location: {here}{l}\r\n")).unwrap_or_default(); write!(stream, "HTTP/1.1 {status} X\r\n{location}Content-Length: 0\r\nConnection: close\r\n\r\n").unwrap(); } }); (base, heard) } #[test] fn a_click_taken_is_one_post_of_the_one_click_body() { let (base, heard) = server(vec![(200, None)]); super::post_click(&format!("{base}/u/1"), "http").expect("taken"); assert_eq!(heard.lock().unwrap().as_slice(), [("POST".to_string(), "/u/1".to_string(), "List-Unsubscribe=One-Click".to_string())]); } /// RULE: a 302 (or 301, 303) would be followed as a GET with no body, unsubscribing no one, its page's 200 /// read as done. It is a click not taken; nothing else is asked. #[test] fn a_redirect_to_a_page_is_a_click_not_taken() { for status in [301, 302, 303] { let (base, heard) = server(vec![(status, Some("/thanks")), (200, None)]); let said = super::post_click(&format!("{base}/u/2"), "http").expect_err("not taken"); assert!(said.contains("redirected the click"), "{status}: {said}"); assert_eq!(heard.lock().unwrap().len(), 1, "{status}: the page was asked for as if the click were taken"); } } /// 307 and 308 keep the POST and its body, so they are followed. #[test] fn a_redirect_that_keeps_the_post_is_followed() { let (base, heard) = server(vec![(307, Some("/u/real")), (200, None)]); super::post_click(&format!("{base}/u/3"), "http").expect("taken at the second"); let heard = heard.lock().unwrap(); assert_eq!(heard.len(), 2); assert_eq!(heard[1], ("POST".to_string(), "/u/real".to_string(), "List-Unsubscribe=One-Click".to_string())); } #[test] fn the_policy_follows_only_method_keeping_redirects_on_the_same_scheme() { assert!(super::follows(307, "https", "https", 0).is_ok()); assert!(super::follows(308, "https", "https", 4).is_ok()); assert!(super::follows(302, "https", "https", 0).is_err()); assert!(super::follows(307, "http", "https", 0).is_err()); assert!(super::follows(307, "https", "https", 5).is_err()); } }