//! Post's accounts and How mail arrives (CONTRACT row 11; DECISIONS "How mail arrives"). //! //! ```text //! mail.accounts → { title, rows: [{ id, address, tag, way, status }], add, kinds } //! mail.account.plan { kind } → { kind, provider, fields, steps, note?, ways: [Way], chosen } //! mail.account.add { kind, address, way, password?, host?, smtp_host?, name?, tag? } → mail.account //! mail.account { id } → { id, address, way, ways: [Way], status, password?, signature, name, tag } //! mail.account.way { id, way, password? } → mail.account //! mail.account.set { id, name?, signature?, tag? } → mail.account //! mail.account.forget { id } → { line, provider_page, next: mail.account } Remove password //! mail.account.remove { id, count? } → { ask } until `count` is the mails here, then { line } //! ``` //! //! A Way is `{ id, title, line, could?, kept?, logged?, chosen }`, the honest words for each choice before he //! makes it. `email_account` never holds a password: with This phone fetches the phone keeps it in its own key store, //! with This Mac fetches the Mac's keychain, with Cotton fetches the object, locked with a key only the server holds //! (`POST /v1/mail/fetch`, keyed by the account's id; Worker row 13). For a new person This phone fetches is chosen first; for his own //! account Cotton fetches is (owner, 25 Nov 2026) once it is proven on dev. use cotton_tools::mcp::handlers::tables; use super::super::writing::is_address; use super::super::*; use super::p; use cotton_core::rules::mail_predicate; const ACCOUNTS: &str = "email_account"; const KINDS: [&str; 6] = ["gmail", "icloud", "fastmail", "yahoo", "imap", "domain"]; const WAYS: [&str; 3] = ["phone", "mac", "cotton"]; fn object(value: Value) -> Map { value.as_object().cloned().unwrap_or_default() } fn provider(kind: &str) -> String { match kind { "gmail" => "Gmail", "icloud" => "iCloud Mail", "fastmail" => "Fastmail", "yahoo" => "Yahoo Mail", "domain" => "your domain", _ => "your mail server", } .to_string() } fn way_json(id: &str, kind: &str, chosen: &str, platform: &str) -> Value { let prov = provider(kind); let mut way = json!({ "id": id, "title": p(&format!("way.{id}.title"), &[]), "line": p(&format!("way.{id}.line"), &[]), "chosen": id == chosen }); match id { "phone" => way["more"] = json!(p(if platform == "ios" { "way.phone.iphone" } else { "way.phone.android" }, &[])), "mac" => way["kept"] = json!(p("way.mac.kept", &[])), "cotton" => { way["could"] = json!(p("way.cotton.could", &[("provider", &prov)])); way["kept"] = json!(p("way.cotton.kept", &[])); way["logged"] = json!(p("way.cotton.logged", &[])); } _ => {} } way } fn ways(kind: &str, chosen: &str, platform: &str) -> Vec { if kind == "domain" { return vec![json!({ "id": "arrives", "title": p("way.arrives.title", &[]), "line": p("way.arrives.line", &[]), "chosen": true })]; } WAYS.iter().map(|w| way_json(w, kind, chosen, platform)).collect() } fn status(way: &str, kind: &str) -> Value { let (line, state) = match way { "cotton" => (p("status.cotton_unknown", &[]), "unknown"), "mac" => (p("status.mac", &[]), "live"), "phone" => (p("status.phone_here", &[]), "live"), "arrives" => (p("status.arrives", &[]), "live"), _ => (p("status.stopped", &[("why", &p("status.no_way", &[]))]), "stopped"), }; let _ = kind; json!({ "line": line, "state": state }) } fn accounts_of(ctx: &mut Ctx<'_>) -> Vec> { let mut all = super::accounts(ctx); all.sort_by(|a, b| a.get("position").and_then(Value::as_i64).unwrap_or(0).cmp(&b.get("position").and_then(Value::as_i64).unwrap_or(0))); all } fn get(a: &Map, k: &str) -> String { a.get(k).and_then(Value::as_str).unwrap_or_default().to_string() } pub(super) fn list(client: &ClientController) -> Result { let all = read(client, "mail.accounts", |ctx| Ok(accounts_of(ctx)))?; Ok(json!({ "title": p("account.title", &[]), "rows": all.iter().map(|a| { let status = if get(a, "way") == "cotton" { let (state, log) = fetched(client, &get(a, "id")); cotton_status(&provider(&get(a, "kind")), state.as_deref(), &log) } else { status(&get(a, "way"), &get(a, "kind")) }; json!({ "id": get(a, "id"), "address": get(a, "address"), "tag": a.get("tag"), "kind": get(a, "kind"), "way": get(a, "way"), "status": status }) }).collect::>(), "add": p("account.add", &[]), "kinds": KINDS.iter().map(|k| json!({ "kind": k, "label": provider(k) })).collect::>(), "empty": all.is_empty().then(|| p("account.none", &[])), })) } pub(super) fn plan(request: &Value) -> Result { let kind = cotton_chat::text(request, "kind")?.to_string(); if !KINDS.contains(&kind.as_str()) { return Err(bad("kind", "gmail, icloud, fastmail, yahoo, imap or domain")); } let platform = request.get("platform").and_then(Value::as_str).unwrap_or("ios"); let prov = provider(&kind); let steps: Vec = super::post().value(&format!("account.steps.{kind}")).and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default(); let mut fields = vec![json!({ "id": "address", "label": p("account.address", &[]) })]; if kind != "domain" { fields.push(json!({ "id": "password", "label": p("account.password", &[]), "hint": p("account.password_hint", &[("provider", &prov)]), "secret": true })); } if kind == "imap" { fields.push(json!({ "id": "host", "label": p("account.host", &[]) })); fields.push(json!({ "id": "smtp_host", "label": p("account.smtp_host", &[]) })); } Ok(json!({ "kind": kind, "provider": prov, "title": p("way.title", &[]), "line": p("way.line", &[]), "fields": fields, "how": (!steps.is_empty()).then(|| p("account.how", &[])), "steps": steps, "note": (kind == "gmail").then(|| p("account.workspace", &[])), "ways": ways(&kind, if kind == "domain" { "arrives" } else { "phone" }, platform), "chosen": if kind == "domain" { "arrives" } else { "phone" }, })) } /// The IMAP server for an account kind. fn imap_host(kind: &str, host: Option<&str>) -> Option { match kind { "gmail" => Some("imap.gmail.com".into()), "icloud" => Some("imap.mail.me.com".into()), "fastmail" => Some("imap.fastmail.com".into()), "yahoo" => Some("imap.mail.yahoo.com".into()), _ => host.map(str::to_string), } } /// Hand the app password to the object for Cotton fetches (`POST /v1/mail/fetch`, Worker row 13), keyed by the /// account's id. Refused in words when the phone is offline or the object can't take it. fn give_password(client: &ClientController, id: &str, address: &str, kind: &str, password: &str, host: Option<&str>) -> Result<(), MethodError> { let door = client.object_door().ok_or_else(|| MethodError::new("offline", p("account.cotton_offline", &[])))?; let ask = json!({ "account": id, "address": address, "password": password, "host": imap_host(kind, host) }); let answer = door.send("POST", "/v1/mail/fetch", Some(&ask)).map_err(|e| if e.code.starts_with("bad_") { e } else { MethodError::new("not_ready", p("account.cotton_not_ready", &[])) })?; match answer["state"].as_str() { Some("refused") => Err(MethodError::new("wrong_password", p("account.wrong", &[("provider", &provider(kind))]))), Some(_) => Ok(()), None => Err(MethodError::new("not_ready", p("account.cotton_not_ready", &[]))), } } pub(super) fn add(client: &ClientController, request: &Value) -> Result { let kind = cotton_chat::text(request, "kind")?.to_string(); if !KINDS.contains(&kind.as_str()) { return Err(bad("kind", "gmail, icloud, fastmail, yahoo, imap or domain")); } let address = cotton_chat::text(request, "address")?.trim().to_lowercase(); if !is_address(&address) { return Err(MethodError::new("bad_address", p("write.bad_address", &[("address", &address)]))); } let way = if kind == "domain" { "arrives".to_string() } else { request.get("way").and_then(Value::as_str).unwrap_or("phone").to_string() }; if kind != "domain" && !WAYS.contains(&way.as_str()) { return Err(bad("way", "phone, mac or cotton")); } let field = |k: &str| request.get(k).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); if kind == "imap" && field("host").is_none() { return Err(bad("host", "the mail server's name")); } let password = field("password"); if way == "cotton" && password.is_none() { return Err(MethodError::new("needs_password", p("account.password_hint", &[("provider", &provider(&kind))]))); } let now = Clock::of(client).now_iso(); let id = write(client, "mail.account.add", |ctx| { let all = accounts_of(ctx); if all.iter().any(|a| get(a, "address") == address) { return Err(format!("held:{}", p("account.held", &[("address", &address)]))); } let mut data = object(json!({ "address": address, "kind": kind, "way": way, "position": all.len(), "added_at": now })); for k in ["host", "smtp_host", "name", "tag", "phone_device"] { if let Some(v) = field(k) { data.insert(k.into(), json!(v)); } } let made = tables::create_produced_record(ctx, &object(json!({ "table": ACCOUNTS, "data": Value::Object(data) }))).map_err(|f| f.to_string())?; made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| "no id for the new account".to_string()) }) .map_err(|e| match e.message.strip_prefix("held:") { Some(words) => MethodError::new("held", words.to_string()), None => e, })?; if way == "cotton" { if let Err(refused) = give_password(client, &id, &address, &kind, password.as_deref().unwrap_or_default(), field("host").as_deref()) { // Not taken: the account is not added half-way. write(client, "mail.account.add", |ctx| tables::delete_record(ctx, &object(json!({ "table": ACCOUNTS, "id": id }))).map(|_| ()).map_err(|f| f.to_string()))?; return Err(refused); } } page(client, &json!({ "id": id })) } fn one_account(client: &ClientController, id: &str) -> Result, MethodError> { let id = id.to_string(); read(client, "mail.account", |ctx| Ok(accounts_of(ctx).into_iter().find(|a| get(a, "id") == id)))?.ok_or_else(|| MethodError::new("not_found", p("act.gone", &[]))) } pub(super) fn page(client: &ClientController, request: &Value) -> Result { let id = cotton_chat::text(request, "id")?.to_string(); let platform = request.get("platform").and_then(Value::as_str).unwrap_or("ios"); let a = one_account(client, &id)?; let (kind, way, address) = (get(&a, "kind"), get(&a, "way"), get(&a, "address")); let prov = provider(&kind); let password = match way.as_str() { "cotton" => Some(json!({ "kept": p("way.cotton.kept", &[]), "logged": p("way.cotton.logged", &[]), "forget": p("way.forget.title", &[]) })), "mac" => Some(json!({ "kept": p("way.mac.kept", &[]) })), "phone" => Some(json!({ "kept": p("way.phone.line", &[]) })), _ => None, }; let (fetch_state, log) = if way == "cotton" { fetched(client, &id) } else { (None, Vec::new()) }; let mails = read(client, "mail.account", |ctx| Ok(one(ctx, &format!("SELECT count(*) AS n FROM {EMAILS} WHERE workspace_id = ? AND lower(coalesce(account, gmail_account, '')) = ? AND {live_mail}", live_mail = mail_predicate::live("")), &[ws(ctx), text(address.clone())])?.and_then(|r| r.get("n").and_then(Value::as_i64)).unwrap_or(0)))?; Ok(json!({ "id": id, "address": address, "kind": kind, "provider": prov, "title": p("account.how_mail_arrives", &[]), "way": way, "ways": ways(&kind, &way, platform), "status": if way == "cotton" { cotton_status(&prov, fetch_state.as_deref(), &log) } else { status(&way, &kind) }, "password": password, "log": (way == "cotton").then(|| json!({ "title": p("account.log", &[]), "rows": log })), "name": { "label": p("account.name", &[]), "value": a.get("name") }, "signature": { "label": p("account.signature", &[]), "value": a.get("signature") }, "tag": { "label": p("account.tag", &[]), "value": a.get("tag") }, "remove": { "label": p("account.remove", &[]), "line": super::counted("account.remove_line", mails as usize), "count": mails }, })) } /// Cotton's fetcher for this account, as the object says it: its state, and its log in words (newest first). fn fetched(client: &ClientController, id: &str) -> (Option, Vec) { let Some(door) = client.object_door() else { return (None, Vec::new()) }; let state = door.send("GET", &format!("/v1/mail/fetch/state?account={id}"), None).ok().and_then(|v| v["state"].as_str().map(str::to_string)); let (state, log) = (state, fetch_log(client, &door, id)); (state, log) } /// What Cotton fetches says of an account, from the object's own state and log, never assumed: no round yet says so, /// and a round that failed says why (seen on dev, 25 Nov 2026: a server that does not exist read "new mail in seconds"). fn cotton_status(prov: &str, state: Option<&str>, log: &[Value]) -> Value { let newest = log.first(); match state { Some("refused") => json!({ "line": p("status.refused", &[("provider", prov)]), "state": "refused" }), Some("stopped") => json!({ "line": p("status.stopped", &[("why", &p("status.cotton_stopped", &[]))]), "state": "stopped" }), Some(_) if newest.is_none() => json!({ "line": p("status.cotton_first", &[]), "state": "waiting" }), Some(_) if newest.and_then(|l| l["failed"].as_bool()) == Some(true) => { json!({ "line": p("status.cotton_failed", &[("why", newest.and_then(|l| l["why"].as_str()).unwrap_or_default())]), "state": "failed" }) } Some(_) => json!({ "line": p("status.cotton", &[]), "state": "live" }), None => json!({ "line": p("status.cotton_unknown", &[]), "state": "unknown" }), } } fn fetch_log(client: &ClientController, door: &crate::phone::personal_object::ObjectDoor, id: &str) -> Vec { let clock = Clock::of(client); let log = door .send("GET", &format!("/v1/mail/fetch/log?account={id}&limit=20"), None) .ok() .and_then(|v| v["log"].as_array().cloned()) .unwrap_or_default() .iter() .map(|l| { let at = l["at"].as_str().unwrap_or_default(); let n = l["count"].as_i64().unwrap_or(0).to_string(); let line = match l["kind"].as_str() { Some("fetched") => super::counted("account.log_fetched", n.parse().unwrap_or(0)), Some("stopped") => p("account.log_stopped", &[]), _ => p("account.log_failed", &[("code", &failure(l["code"].as_str().unwrap_or_default()))]), }; json!({ "at": at, "when": clock.recent(at), "line": line, "failed": !matches!(l["kind"].as_str(), Some("fetched") | Some("stopped")), "why": failure(l["code"].as_str().unwrap_or_default()) }) }) .collect(); log } pub(super) fn set_way(client: &ClientController, request: &Value) -> Result { let id = cotton_chat::text(request, "id")?.to_string(); let way = cotton_chat::text(request, "way")?.to_string(); if !WAYS.contains(&way.as_str()) { return Err(bad("way", "phone, mac or cotton")); } let a = one_account(client, &id)?; if get(&a, "kind") == "domain" { return Err(MethodError::new("refused", p("account.domain_way", &[]))); } if way == "cotton" && get(&a, "way") != "cotton" { let password = request.get("password").and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty()).ok_or_else(|| MethodError::new("needs_password", p("account.password_hint", &[("provider", &provider(&get(&a, "kind")))])))?; give_password(client, &id, &get(&a, "address"), &get(&a, "kind"), password, a.get("host").and_then(Value::as_str))?; } if get(&a, "way") == "cotton" && way != "cotton" { forget_password(client, &id); } patch(client, &id, json!({ "way": way }))?; page(client, &json!({ "id": id })) } fn patch(client: &ClientController, id: &str, patch: Value) -> Result<(), MethodError> { write(client, "mail.account", |ctx| tables::update_produced_record(ctx, &object(json!({ "table": ACCOUNTS, "id": id, "patch": patch }))).map(|_| ()).map_err(|f| f.to_string())) } pub(super) fn set(client: &ClientController, request: &Value) -> Result { let id = cotton_chat::text(request, "id")?.to_string(); one_account(client, &id)?; let mut changes = Map::new(); for k in ["name", "signature", "tag"] { if let Some(v) = request.get(k) { changes.insert(k.into(), if v.as_str().is_some_and(|s| s.trim().is_empty()) { Value::Null } else { v.clone() }); } } if changes.is_empty() { return Err(bad("name", "name, signature or tag")); } patch(client, &id, Value::Object(changes))?; page(client, &json!({ "id": id })) } /// Ask the object to delete the password now; a phone offline or a Worker without the route leaves nothing to do /// here, and the page says the password is no longer used. fn forget_password(client: &ClientController, id: &str) { if let Some(door) = client.object_door() { let _ = door.send("DELETE", "/v1/mail/fetch", Some(&json!({ "account": id }))); } } pub(super) fn forget(client: &ClientController, request: &Value) -> Result { let id = cotton_chat::text(request, "id")?.to_string(); let a = one_account(client, &id)?; if get(&a, "way") != "cotton" { return Err(MethodError::new("refused", p("account.no_password_held", &[]))); } forget_password(client, &id); // Nobody fetches until he picks again: the object now says `stopped` for the account, and its page says so. // `way` stays: the object's table requires it (seen on dev, 25 Nov 2026). let prov = provider(&get(&a, "kind")); Ok(json!({ "line": p("way.forget.line", &[("provider", &prov)]), "provider_page": { "label": p("way.forget.provider_page", &[("provider", &prov)]), "url": (get(&a, "kind") == "gmail").then_some("https://myaccount.google.com/apppasswords") }, "next": { "title": p("way.forget.next", &[]), "account": page(client, &json!({ "id": id }))? }, })) } pub(super) fn remove(client: &ClientController, request: &Value) -> Result { let id = cotton_chat::text(request, "id")?.to_string(); let a = one_account(client, &id)?; let shown = page(client, &json!({ "id": id }))?; let count = shown["remove"]["count"].as_i64().unwrap_or(0); if request.get("count").and_then(Value::as_i64) != Some(count) { return Ok(json!({ "ask": { "title": p("account.remove", &[]), "line": super::counted("account.remove_line", count as usize), "go": p("account.remove", &[]), "cancel": p("ask.cancel", &[]), "count": count } })); } if get(&a, "way") == "cotton" { forget_password(client, &id); } write(client, "mail.account.remove", |ctx| tables::delete_record(ctx, &object(json!({ "table": ACCOUNTS, "id": id }))).map(|_| ()).map_err(|f| f.to_string()))?; Ok(json!({ "line": p("account.removed", &[("address", &get(&a, "address"))]) })) } /// A failed round's code from the object's log (`src/mail/fetcher.ts`), in words. fn failure(code: &str) -> String { match code { "refused" => p("fail.refused", &[]), "closed" | "bye" => p("fail.closed", &[]), "no" | "bad" | "protocol" => p("fail.said_no", &[]), _ => p("fail.unreachable", &[]), } }