Cotton code
248 lines · 12.8 KB · RustRaw
//! DELETING THE ACCOUNT (owner, 22 Nov 2026: the stores' blocker). The//! Worker's half is `apps/business/src/account_delete.ts`; every word is//! `kits/shell/lines/signin.json` `delete.*`. Settings › Account › Delete//! account, in every app://!//! ```text//! account.deletePage { app } → { row, heading, whatGoes, whatStays, undo, otherApps, send, codeLabel, confirm, cancel, working }//! account.deleteCode {} → { challengeId, sent }                 a code to the account's number//! account.delete { challengeId, code, app } → { deleted: true, heading, line, databaseId }//! account.forget {} → { forgot, databaseId }                     this phone's copy gone//! account.keep { server, credential } → { kept: true, line }     in the thirty days: everything as it was//! account.leave { server, credential } → { left: true }          in the thirty days: that sign-in ends//! ```//!//! THIRTY DAYS TO CHANGE ONE'S MIND (owner, 22 Nov 2026). `account.delete`//! erases nothing: the object sets the account to be deleted thirty days on//! and answers the date, which the done line says ("Your account will be//! deleted on 22 December. Until then, sign in to keep it."). Every phone is//! signed out at once and answered 410 with the date in its message, so the//! elsewhere line says it too. Signing in again in the thirty days,//! `personal.signIn` answers `deleting: { eraseAt, date, heading, line, keep,//! leave }`: the app connects nothing and asks Keep my account (then connects//! as any sign-in does, and the account is as it was) or Leave it to be//! deleted (the credential is forgotten and the phone stays on its first//! screen). Past the date, the 410 says only that the account was deleted.//!//! `account.delete` asks the object (the code typed back, `confirm://! "delete"`) and, once the object has taken it, forgets everything this//! phone holds of the database (`account.forget`) and stands on a fresh local//! database, as a new install does. The app then forgets what only it keeps//! (the credential, the data key in the key store) and opens on its first//! screen. A refusal is said in the kit's words: a wrong or old code, no//! connection.//!//! DELETED ELSEWHERE. A phone whose account was deleted from another phone or//! the website is answered 410 `account_deleted` on its next pass; the//! `personal` event at `signed_out` then carries `deleted: true` and the//! words to show (`personal_object`), and the app calls `account.forget`.use cotton_core::rules::shell_lines::resolve;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::personal_object::ObjectDoor;pub const CODE: &str = "/v1/account/delete/code";pub const DELETE: &str = "/v1/account/delete";/// The methods a signed-in phone calls through its object door, and the one/// that only forgets.pub const KEEP: &str = "/v1/account/keep";pub const LEAVE: &str = "/v1/account/leave";/// The methods a signed-in phone calls through its object door, the one/// that only forgets, and the two a sign-in in the thirty days calls.pub const METHODS: [&str; 6] = ["account.delete", "account.deleteCode", "account.deletePage", "account.forget", "account.keep", "account.leave"];pub fn say(line: &str, fills: &[(&str, &str)]) -> String {    resolve("signin", &format!("delete.{line}"), &[], fills).unwrap_or_default()}pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    call_with(handle, method, request, &cotton_client::transport::SocketExchange)}pub fn call_with(handle: &CottonHandle, method: &str, request: &Value, exchange: &dyn cotton_client::transport::Exchange) -> Result<Value, MethodError> {    match method {        "account.deletePage" => Ok(page(&app_of(request))),        "account.forget" => forget(handle),        "account.keep" | "account.leave" => decide(method, request, exchange),        _ => {            let door = handle.client().object_door().ok_or_else(|| MethodError::new("not_connected", say("offline", &[])))?;            match method {                "account.deleteCode" => ask_code(&door),                "account.delete" => {                    // Each shared album this person owns is handed, signed, to its longest member before the account                    // goes (best effort: an album not reached now is claimed later by its members' people).                    let _ = crate::phone::albums_shared::hand_over_all(&handle.client());                    let mut answer = confirm(&door, request)?;                    let forgot = forget(handle)?;                    answer["databaseId"] = forgot["databaseId"].clone();                    Ok(answer)                }                other => Err(MethodError::new("unknown_method", format!("{other} is not an account method"))),            }        }    }}/// The app's own name, which the words say ("not only in Days on this phone").fn app_of(request: &Value) -> String {    request.get("app").and_then(Value::as_str).map(str::trim).filter(|app| !app.is_empty()).unwrap_or("Cotton").to_string()}/// Everything the page says before the code is asked.pub fn page(app: &str) -> Value {    json!({        "row": say("row", &[]),        "heading": say("heading", &[]),        "whatGoes": say("what_goes", &[]),        // One account across every Cotton app, said in the app the person is in (coordinator, 24 Nov 2026).        "whatStays": say("what_stays", &[("app", app)]),        "when": say("when", &[]),        "otherApps": say("other_apps", &[("app", app)]),        "send": say("send", &[]),        "codeLabel": say("code_label", &[]),        "confirm": say("confirm", &[]),        "cancel": say("cancel", &[]),        "working": say("working", &[]),    })}/// A code to the account's own number; the line names the number it went to.pub fn ask_code(door: &ObjectDoor) -> Result<Value, MethodError> {    let me = door.send("GET", "/v1/me", None).map_err(said)?;    let asked = door.send("POST", CODE, Some(&json!({}))).map_err(said)?;    let challenge = asked["challenge_id"].as_str().filter(|c| !c.is_empty()).ok_or_else(|| MethodError::new("refused", "the object sent no code"))?;    let number = me["person"]["phone"].as_str().unwrap_or_default();    Ok(json!({ "challengeId": challenge, "sent": say("sent", &[("number", number)]) }))}/// The code typed back: the object begins the deletion.pub fn confirm(door: &ObjectDoor, request: &Value) -> Result<Value, MethodError> {    let field = |name: &str| request.get(name).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty());    let challenge = field("challengeId").ok_or_else(|| MethodError::new("bad_request", "`challengeId` is missing"))?;    let code = field("code").ok_or_else(|| MethodError::new("invalid_code", say("wrong", &[])))?;    let answer = door.send("POST", DELETE, Some(&json!({ "challenge_id": challenge, "code": code, "confirm": "delete" }))).map_err(said)?;    let date = answer["erase_at"].as_str().map(day_and_month).unwrap_or_default();    Ok(json!({ "deleted": true, "eraseAt": answer["erase_at"], "heading": say("done_heading", &[]), "line": say("done_line", &[("app", &app_of(request)), ("date", &date)]) }))}const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];/// "22 December" from the object's ISO time (`2026-12-22T…`), as the web page says it; the text itself when it is no date.pub fn day_and_month(iso: &str) -> String {    let mut parts = iso.get(..10).unwrap_or_default().split('-');    let (_, month, day) = (parts.next(), parts.next().and_then(|m| m.parse::<usize>().ok()), parts.next().and_then(|d| d.parse::<u32>().ok()));    match (month, day) {        (Some(month @ 1..=12), Some(day @ 1..=31)) => format!("{day} {}", MONTHS[month - 1]),        _ => iso.to_string(),    }}/// The ISO date a refusal's words carry in the thirty days (`set to be deleted on 2026-12-22.`), or none.fn date_in(message: &str) -> Option<String> {    let at = message.find("deleted on ")? + "deleted on ".len();    let date = message.get(at..at + 10)?;    date.bytes().enumerate().all(|(i, b)| if i == 4 || i == 7 { b == b'-' } else { b.is_ascii_digit() }).then(|| date.to_string())}/// What a sign-in in the thirty days shows: the date, and the two ways.pub fn pending(erase_at: &str) -> Value {    let date = day_and_month(erase_at);    json!({        "eraseAt": erase_at,        "date": date,        "heading": say("pending_heading", &[]),        "line": say("pending_line", &[("date", &date)]),        "keep": say("keep", &[]),        "leave": say("leave", &[]),    })}/// `account.keep` / `account.leave` with the sign-in's own credential, before anything is connected.fn decide(method: &str, request: &Value, exchange: &dyn cotton_client::transport::Exchange) -> Result<Value, MethodError> {    let field = |name: &str| request.get(name).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty());    let server = field("server").ok_or_else(|| MethodError::new("bad_request", "`server` is missing"))?;    let credential = field("credential").ok_or_else(|| MethodError::new("bad_request", "`credential` is missing"))?;    let address = cotton_client::transport::object::ObjectAddress::open(server).map_err(|reason| MethodError::new("bad_request", reason))?;    let headers = cotton_client::transport::object::bearer(credential);    if method == "account.keep" {        address.send(exchange, "POST", KEEP, headers, Some(&json!({}))).map_err(|refusal| said(refusal.into()))?;        return Ok(json!({ "kept": true, "line": say("kept", &[]) }));    }    address.send(exchange, "POST", LEAVE, headers, Some(&json!({}))).map_err(|refusal| said(refusal.into()))?;    Ok(json!({ "left": true }))}/// A refusal in the kit's words where the person can act on it.fn said(error: MethodError) -> MethodError {    match error.code.as_str() {        "invalid_code" | "too_many_codes" => MethodError::new(&error.code, say("wrong", &[])),        "offline" => MethodError::new("offline", say("offline", &[])),        _ => error,    }}/// The words a phone shows when the account was set to be deleted from another phone or the website (the/// refusal's words carry the date), or was erased while it was away.pub fn elsewhere(message: &str) -> Value {    match date_in(message) {        Some(iso) => {            let date = day_and_month(&iso);            json!({ "heading": say("elsewhere_heading", &[]), "line": say("elsewhere_line", &[("date", &date)]), "eraseAt": iso })        }        None => json!({ "heading": say("erased_heading", &[]), "line": say("erased_line", &[]) }),    }}/// `account.forget`: nothing of the database this phone held stays on it —/// the copy, its media and keeps, and any copy of it set aside — and the/// phone stands on a fresh local database of its own.pub fn forget(handle: &CottonHandle) -> Result<Value, MethodError> {    crate::phone::adopt::stop(handle);    let client = handle.client();    // From the detach until the fresh local database stands, a read on    // another thread waits (`shell::swap`): never "has not started or joined    // a database yet", nor the deleted copy opened again as its folder goes.    let _swap = client.swapping();    let layout = client.layout().clone();    let held = crate::phone::copy_aside::held(&layout).and_then(|held| held.workspace_id).filter(|id| !id.is_empty());    client.detach();    crate::phone::personal_object::let_go(&client);    client.finish_moves();    client.keep_signed_in(None);    client.note_signed_out(None);    client.note_connect_refused(None);    client.note_trouble(None);    client.note_topped_up(None);    client.set_adopting(None);    let mut forgot = false;    // The person deleted their account: one of the three acts that end a copy outright (QUEUE BAD OP 5, item 5).    let act = cotton_client::copy_keep::PersonsAct::of_the_person();    if let Some(database) = &held {        forgot = crate::phone::copy_aside::forget(&layout, database, &act)?;    }    // not a copy: the connection file.    match std::fs::remove_file(layout.connection_json()) {        Ok(()) => forgot = true,        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}        Err(error) => return Err(MethodError::new("io", format!("this phone's connection could not be removed ({error})"))),    }    if let Some(database) = &held {        client.forget_notes(database);    }    let started = crate::phone::commands::start_local(handle, &json!({}))?;    client.let_go_if_stale();    // Standing up the fresh database can touch the old one's folder once more (a pass winding down): gone again.    if let Some(database) = &held {        crate::phone::copy_aside::forget(&layout, database, &act)?;    }    Ok(json!({ "forgot": forgot, "databaseId": held, "standing": started["workspaceId"] }))}#[cfg(test)]#[path = "account_delete_tests.rs"]mod tests;