Cotton code
1093 lines · 61.2 KB · RustRaw
//! `recovery.*` — the way back into a person's vault on a new device with no//! other device of theirs at hand (rulings R7a and R7c)://! a recovery code the person keeps, and a platform key the phone's own//! synced key store keeps (Google Block Store on Android, iCloud Keychain on//! iPhone). The cryptography is `cotton_core::vault::recovery_code`; the//! object's half is `apps/business/src/recovery.ts`, which holds a salt, the//! hash of an auth key and the vault key wrapped under a key that never//! leaves a device, and answers the wrap only for the right auth key, inside//! its try limit.//!//! ```text//! recovery.status {copy?, why?}               → {code, google, apple: {made, current, line} | null,//!                                                holdsVault, offer, alone, away, copyBack, lines: {…}}//!                                                copy: what THIS phone's own store did with its platform key//!                                                (back: it comes back after a reinstall or on a new phone; here://!                                                kept on this phone only; none: not kept); why: no_lock//! recovery.make {privateKey?}                 → {code}   a new code (retires the old), shown once to its caller//! recovery.show {privateKey?}                 → {code}   the code again, on a device that holds the vault//! recovery.check {code}                       → {ok, problem?, line?}   a typo caught before a try is spent//! recovery.open {code, privateKey, name?}     → {opened}  a new device opens the vault with the code//! recovery.makePlatform {store, privateKey?}  → {key}    a new platform key (store google | apple), for the shell to//!                                                keep in that store (Block Store, iCloud Keychain)//! recovery.openPlatform {store, key, privateKey, name?} → {opened}//! ```//!//! The vault key is lent for `make`, `show` and `makePlatform` as for an//! approval: by `privateKey` (the device's own key, after the phone's lock),//! else by the five-minute unlock this device already holds.//!//! Opening: the code is read back (a typo refused by name, nothing sent), the//! salt and stretch are asked, the auth key is sent, the wrap that comes back//! is opened here; this device then publishes its own key if it has not,//! wraps the vault key for itself (the object lets it, for ten minutes, as it//! just proved the secret), takes the data key and opens. From then on it is a//! device of the vault like any other: it approves others.//!//! Nothing here logs or answers a key, a wrap or the code, except the code//! itself to the one caller that made or asked for it, and a new platform//! key to the shell that keeps it.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use serde_json::{json, Value};use cotton_client::transport::object::bearer;use cotton_client::vault::devices;use cotton_core::records::page::{stamp_parts, DateWords};use cotton_core::rules::shell_lines::resolve;use cotton_core::seal::share;use cotton_core::vault::recovery_code::{self as code, Kdf, Kind};use cotton_core::vault::{self as vault_core, Vmk};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::owner;use crate::phone::personal_object::ObjectDoor;use crate::phone::vault;use crate::shell::client::ClientController;pub const METHODS: [&str; 13] = [    "recovery.askHelp",    "recovery.check",    "recovery.helpApprove",    "recovery.helpAsks",    "recovery.helpDecline",    "recovery.helped",    "recovery.make",    "recovery.makePlatform",    "recovery.open",    "recovery.openPlatform",    "recovery.show",    "recovery.status",    "recovery.trust",];/// The id the code is sealed under (with the vault key), as a secret's row id binds its seal.pub const CODE_ROW: &str = "recovery-code";const PATH: &str = "/v1/recovery";/// The query every call of this build carries (TRUSTED RECOVERY BUILD 2, H1): it speaks the six-digit compare, flow 2./// The Worker serves an earlier build's calls (no query) as before, and never lets this build skip the digits.pub(super) const FLOW: &str = "?flow=2";pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    call_on(&handle.client(), method, request)}pub(crate) fn call_on(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    // Any recovery act may change what the object holds: the next status asks it again, never the launch's last answer.    if !matches!(method, "recovery.status" | "recovery.check") {        held::forget(client);    }    match method {        "recovery.check" => Ok(check(request)),        "recovery.status" => status(client, request),        "recovery.make" => make(client, request),        "recovery.show" => show(client, request),        "recovery.open" => open(client, request, Kind::Code),        "recovery.makePlatform" => make_platform(client, request),        "recovery.openPlatform" => open(client, request, store_arg(request)?),        "recovery.trust" => trust(client, request),        "recovery.askHelp" => ask_help(client, request),        "recovery.helped" => helped(client, request),        "recovery.helpAsks" => help_asks(client),        "recovery.helpApprove" => help_answer(client, request, true),        "recovery.helpDecline" => help_answer(client, request, false),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a recovery method"))),    }}/// One of the kit's recovery lines (`kits/shell/lines/unlock.json` `recovery.*`).pub fn say(line: &str, fills: &[(&str, &str)]) -> String {    resolve("unlock", &format!("recovery.{line}"), &[], fills).unwrap_or_default()}pub(super) fn door(client: &ClientController) -> Result<std::sync::Arc<ObjectDoor>, MethodError> {    client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "Sign in first: the way back in is kept with your account."))}/// What the object holds of this person's ways back in, for `recovery.status`, asked on a thread of its own and/// waited for at most [`held::FIRST_WAIT`] (OFFLINE START, 26 Nov 2026). The status is read at every launch beside/// the first screen: it asked the object on the caller's thread, with no network waited out the lookup, and on/// Android the four threads every screen's call shares were held by it (`shell.lines` answered 7 s late at a cold/// start). Online each status reads the object's answer as before; one that does not come in time answers the last/// one this launch heard (or offline), and while that ask is still out the next status does not wait behind it./// Any recovery act forgets the last answer. Kept per data folder and database, so two cores never share one.mod held {    use std::collections::HashMap;    use std::sync::{Arc, Condvar, Mutex, OnceLock};    use std::time::{Duration, Instant};    use serde_json::Value;    use super::{get, ClientController, MethodError, ObjectDoor};    /// How long a status waits for the object's answer to its own ask.    pub const FIRST_WAIT: Duration = Duration::from_secs(1);    #[derive(Default)]    struct Held {        /// The object's last answer.        answer: Option<Value>,        /// The last ask's refusal, while no answer came after it.        refused: Option<MethodError>,        /// Answers and refusals landed so far: a status waits for one past the count it began at.        landed: u64,        asking: bool,        /// A status already waited [`FIRST_WAIT`] for the ask still out: the next one does not wait behind it.        waited: bool,    }    fn all() -> &'static (Mutex<HashMap<String, Held>>, Condvar) {        static ALL: OnceLock<(Mutex<HashMap<String, Held>>, Condvar)> = OnceLock::new();        ALL.get_or_init(|| (Mutex::new(HashMap::new()), Condvar::new()))    }    fn key(client: &ClientController) -> String {        format!("{}|{}", client.layout().root().display(), client.current_database().unwrap_or_default())    }    fn offline() -> MethodError {        MethodError::new("offline", "cottondb.com did not answer yet: the ways back in are said once it does.")    }    fn unheld() -> MethodError {        MethodError::new("could_not_read", "the recovery status is held elsewhere")    }    /// Any recovery act: the last answer no longer stands for what the object holds.    pub fn forget(client: &ClientController) {        if let Ok(mut held) = all().0.lock() {            if let Some(entry) = held.get_mut(&key(client)) {                entry.answer = None;            }        }    }    pub fn of(client: &ClientController, door: &Arc<ObjectDoor>) -> Result<Value, MethodError> {        let key = key(client);        let (lock, landed) = all();        let mut held = lock.lock().map_err(|_| unheld())?;        let entry = held.entry(key.clone()).or_default();        // An ask still out that a status already gave up waiting for: answer now, from what is held.        if entry.asking && entry.waited {            return entry.answer.clone().ok_or_else(|| entry.refused.clone().unwrap_or_else(offline));        }        let began = entry.landed;        if !entry.asking {            entry.asking = true;            let beside = Arc::clone(door);            let asked = key.clone();            let spawned = std::thread::Builder::new().name("cotton-recovery-status".into()).spawn(move || {                let answer = get(&beside);                let (lock, landed) = all();                if let Ok(mut held) = lock.lock() {                    let entry = held.entry(asked).or_default();                    entry.asking = false;                    entry.waited = false;                    entry.landed += 1;                    match answer {                        Ok(value) => {                            entry.answer = Some(value);                            entry.refused = None;                        }                        Err(refusal) => entry.refused = Some(refusal),                    }                }                landed.notify_all();            });            if spawned.is_err() {                entry.asking = false;                drop(held);                return get(door.as_ref());            }        }        let started = Instant::now();        loop {            let entry = held.entry(key.clone()).or_default();            if entry.landed > began {                return match (&entry.refused, &entry.answer) {                    (None, Some(value)) => Ok(value.clone()),                    // The object did not answer this ask: its last answer stands, else the refusal.                    (Some(refusal), answer) => answer.clone().ok_or_else(|| refusal.clone()),                    (None, None) => Err(offline()),                };            }            let left = FIRST_WAIT.saturating_sub(started.elapsed());            if left.is_zero() {                entry.waited = true;                return entry.answer.clone().ok_or_else(offline);            }            held = landed.wait_timeout(held, left).map_err(|_| unheld())?.0;        }    }}fn get(door: &ObjectDoor) -> Result<Value, MethodError> {    door.address        .send(door.exchange.as_ref(), "GET", &format!("{PATH}{FLOW}"), bearer(&door.credential), None)        .map_err(|refusal| MethodError::new(&refusal.code, refusal.message))}pub(super) fn post(door: &ObjectDoor, path: &str, body: &Value) -> Result<(u16, Value), MethodError> {    let (status, bytes) = door        .address        .send_bytes(door.exchange.as_ref(), "POST", &with_flow(&format!("{PATH}{path}")), bearer(&door.credential), Some(body))        .map_err(|refusal| MethodError::new(&refusal.code, refusal.message))?;    let answer: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);    Ok((status, answer))}/// Every call of this build says its flow (TRUSTED RECOVERY BUILD 3, LOW: /set, /open and /retire too), so the owner's/// count of devices on the earlier flow is true.pub(super) fn with_flow(path: &str) -> String {    if path.contains('?') {        path.to_string()    } else {        format!("{path}{FLOW}")    }}pub(super) fn refused_by(status: u16, answer: &Value) -> MethodError {    let code = answer.get("code").and_then(Value::as_str).unwrap_or("recovery_refused");    let message = answer.get("message").and_then(Value::as_str).unwrap_or("The way back in was refused.");    MethodError::new(code, format!("{message} ({status})"))}pub(super) fn current_version(client: &ClientController) -> Result<Option<u32>, MethodError> {    client.with_file(|replica| vault::state_version(replica)).map_err(|why| MethodError::new("unreadable", why))}/// The vault key for the calls that hand the whole vault or the account's way back in to whoever holds the phone/// (recovery codes made or shown, a platform copy, a trusted person, every password exported): only by a fresh/// `privateKey` (the phone's lock asked now), never by an unlock still held (AUDIT E, a borrowed phone: the five/// minutes the vault stays open were enough to export it or make the borrower the trusted person). Without one it/// answers `vault_locked`, which both shells meet by asking the phone's lock and calling again.pub(super) fn with_fresh_vmk<T>(client: &ClientController, request: &Value, work: impl FnOnce(&Vmk, u32) -> Result<T, MethodError>) -> Result<T, MethodError> {    if request.get("privateKey").is_none() {        return Err(vault::locked());    }    with_vmk(client, request, work)}/// The vault key lent for one call: by `privateKey`, else by the unlock held.pub(super) fn with_vmk<T>(client: &ClientController, request: &Value, work: impl FnOnce(&Vmk, u32) -> Result<T, MethodError>) -> Result<T, MethodError> {    if request.get("privateKey").is_some() {        let secret = vault::private_key_arg(request)?;        let (vmk, version) = vault::opened_vmk(client, &secret)?;        return work(&vmk, version);    }    let now = client.now();    let door = client.vault().map_err(|why| MethodError::new("unreadable", why))?;    let mut work = Some(work);    door.with_vmk(now, |vmk, version| (work.take().expect("called once"))(vmk, version)).ok_or_else(vault::locked)?}// ── recovery.check ─────────────────────────────────────────────────────────fn problem_line(problem: code::Problem) -> String {    say(        match problem {            code::Problem::Length => "length",            code::Problem::Character => "character",            code::Problem::Check => "typo",        },        &[],    )}fn check(request: &Value) -> Value {    let typed = request.get("code").and_then(Value::as_str).unwrap_or_default();    match code::normalize(typed) {        Ok(_) => json!({ "ok": true }),        Err(problem) => json!({ "ok": false, "problem": problem.code(), "line": problem_line(problem) }),    }}// ── recovery.status ────────────────────────────────────────────────────────fn status(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let lines = json!({        "offer": say("offer", &[]), "savedAs": say("saved_as", &[]), "copy": say("copy", &[]), "notNow": say("not_now", &[]), "done": say("done", &[]),        "copied": say("copied", &[]), "alone": say("alone", &[]), "show": say("show", &[]),        "makeNew": say("make_new", &[]), "madeNew": say("made_new", &[]), "stale": say("stale", &[]),        "haveCode": say("have_code", &[]), "enter": say("enter", &[]), "hint": say("hint", &[]), "open": say("open", &[]),        "opened": say("opened", &[]), "googleKept": say("google_kept", &[]), "appleKept": say("apple_kept", &[]),        "askHelp": say("ask_help", &[]), "helperPick": say("helper_pick", &[]),        // GETTING-IN.md: the code saved in one tap, one reminder a week later, a new code asked first.        "offerHeading": say("offer_heading", &[]), "savePasswords": say("save_passwords", &[]), "saveFiles": say("save_files", &[]),        "saved": say("saved", &[]), "reminder": say("reminder", &[]), "makeNewConfirm": say("make_new_confirm", &[]),        "fileName": say("file_name", &[]), "fileText": say("file_text", &[]), "none": say("none", &[]),    });    let own_back = own_copy_back(request);    // Whether this device holds a wrap, and whether any other device does.    let (holds, others) = client        .self_device_id()        .map(|device| {            client.with_file(|replica| {                let keys = devices::keys(replica.driver, replica.workspace_id)?;                Ok((                    keys.iter().any(|key| key.device_id == device && key.wrapped),                    keys.iter().any(|key| key.device_id != device && key.wrapped),                ))            })        })        .transpose()        .map_err(|why| MethodError::new("unreadable", why))?        .unwrap_or((false, false));    let Some(door) = client.object_door() else {        return Ok(json!({ "code": null, "google": null, "apple": null, "trusted": null, "holdsVault": holds, "offer": false, "alone": false, "away": null, "signedIn": false, "lines": lines }));    };    let held = held::of(client, &door)?;    let current = current_version(client)?;    // The day a copy was made, in the reader's zone and words ("15 November", the year outside theirs).    let (zone, now, dates) = (client.time_zone().unwrap_or("Etc/UTC").to_string(), client.clock().now(), DateWords::shipped());    let day_of = |made: &str| match stamp_parts(made, &zone, now, dates) {        Some(parts) => parts.day_long,        None => {            tracing::warn!("recovery.status: a copy's made date is not a date ({made})");            made.to_string()        }    };    let summary = |kind: &str| -> Value {        match held.get(kind) {            Some(entry) if entry.is_object() => {                let version = entry.get("vmk_version").and_then(Value::as_u64).unwrap_or(0) as u32;                let made = entry.get("created_at").and_then(Value::as_str).unwrap_or_default();                json!({                    "made": made,                    "current": current.is_none_or(|current| version >= current),                    "line": say("held", &[("date", &day_of(made))]),                })            }            _ => Value::Null,        }    };    let code = summary("code");    let trusted = held.get("trusted").filter(|entry| entry.is_object()).map(|entry| {        let helper = entry.get("helper").and_then(Value::as_str).unwrap_or_default();        let name = entry.get("helper_name").and_then(Value::as_str).filter(|name| !name.is_empty()).unwrap_or(helper);        // A helper who can help no more (TRUSTED RECOVERY BUILD 1, step 2) is said, and offers no ask.        if entry.get("gone").and_then(Value::as_bool) == Some(true) {            return json!({ "helper": helper, "name": name, "gone": true, "current": true, "line": say("helper_gone", &[("name", name)]), "ask": null });        }        // A wrap made under an earlier vault key than the vault's own (step 3) would open a key the vault has moved        // past: said, no ask, and no way back in. Nothing rotates today; this holds for the day something does.        let version = entry.get("vmk_version").and_then(Value::as_u64).unwrap_or(0) as u32;        if current.is_some_and(|current| version < current) {            return json!({ "helper": helper, "name": name, "current": false, "line": say("helper_stale", &[("name", name)]), "ask": null });        }        json!({ "helper": helper, "name": name, "current": true, "line": say("helper_held", &[("name", name)]), "ask": say("ask_helper", &[("name", name)]) })    });    // The circle (step 4): who helps, who has not accepted yet, and a recovery under way, said with Stop.    // A device signed in only by SMS in the last two days shows no helper's name or number without its screen lock (the    // shell hands in this device's own key behind Face ID or the passcode): TRUSTED RECOVERY BUILD 2, review LOW.    let hide = held.get("device").and_then(|d| d.get("fresh")).and_then(Value::as_bool) == Some(true) && vault::private_key_arg(request).is_err();    let circle = held.get("circle").filter(|entry| entry.is_object()).map(|entry| {        let mut said = circle_status(client, entry, current, hide);        // The shell asks for Face ID or the passcode and calls again with this device's key to show who helps.        if hide {            said["screenLock"] = json!({ "line": say("circle_unlock_to_see", &[]) });        }        said    });    // A way back in through a helper counts only while they can help, under the vault's own key.    let helps = trusted.as_ref().is_some_and(|entry| entry.get("gone").is_none() && entry["current"] == json!(true))        || circle.as_ref().is_some_and(|entry| entry["live"] == json!(true) && entry["current"] == json!(true));    let google = summary("google");    let apple = summary("apple");    // A platform copy is a way back only where it comes back: when the phone says what its own store did, that    // decides (a copy kept on this phone alone dies with the app); else the object's row stands, as before.    let platform_back = own_back.unwrap_or(!google.is_null() || !apple.is_null());    // Said once at the code's offer: this phone's copy will not come back and nothing else would.    let away = (holds && !others && code.is_null() && !helps && own_back == Some(false)).then(|| {        say(if request.get("why").and_then(Value::as_str) == Some("no_lock") { "away_no_lock" } else { "away" }, &[])    });    Ok(json!({        "code": code,        "google": google,        "apple": apple,        "trusted": trusted,        "circle": circle,        "holdsVault": holds,        // Offered once by the shell (it keeps whether it asked): a device holding the vault, and no code yet.        "offer": holds && code.is_null(),        // Declining the code leaves nothing else: no other device and no platform copy. The shell says `alone` once then.        "alone": holds && !others && !platform_back && !helps,        "away": away,        // This phone's own copy comes back (true), does not (false), or was not said or is not heard (null).        "copyBack": own_back,        "signedIn": true,        "lines": lines,    }))}/// What this phone said its own store did with its platform key (`copy`): `Some(true)` when the copy comes back/// after a reinstall or on a new phone, `Some(false)` when it does not (kept here only, or not kept), `None` when the/// phone said nothing, or where the switch is off (on for Cotton Dev only until the coordinator/// turns it on for the real apps).fn own_copy_back(request: &Value) -> Option<bool> {    if !copy_honesty_on() {        return None;    }    match request.get("copy").and_then(Value::as_str)? {        "back" => Some(true),        "here" | "none" => Some(false),        _ => None,    }}/// The switch for [`own_copy_back`]: on in every flavor but the real one.pub(crate) fn copy_honesty_on() -> bool {    !matches!(cotton_core::flavor::current(), Some(cotton_core::flavor::Flavor::Real))}// ── recovery.make / recovery.show / recovery.makePlatform ──────────────────fn set(door: &ObjectDoor, kind: Kind, secret: &[u8], vmk: &Vmk, version: u32, extra: serde_json::Map<String, Value>) -> Result<(), MethodError> {    let salt = code::salt();    let kdf = kind.kdf();    let keys = code::derive(secret, &salt, kdf).ok_or_else(|| MethodError::new("recovery_unmade", "The code could not be stretched. Nothing was changed."))?;    let wrapped = code::wrap(&keys.wrap, kind, version, vmk.expose()).ok_or_else(|| MethodError::new("recovery_unmade", "The vault key could not be wrapped. Nothing was changed."))?;    let mut body = json!({        "kind": kind.as_str(),        "salt": URL_SAFE_NO_PAD.encode(salt),        "kdf": kdf.text(),        "auth_hash": code::auth_hash(&keys.auth),        "wrapped": wrapped,        "vmk_version": version,    });    for (key, value) in extra {        body[key] = value;    }    let (status, answer) = post(door, "/set", &body)?;    if status != 200 {        return Err(refused_by(status, &answer));    }    Ok(())}fn make(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let door = door(client)?;    with_fresh_vmk(client, request, |vmk, version| {        let made = code::mint();        let plain = code::normalize(&made).map_err(|problem| MethodError::new(problem.code(), problem_line(problem)))?;        let sealed = vault_core::seal(vmk, CODE_ROW, version, made.as_bytes())            .ok_or_else(|| MethodError::new("recovery_unmade", "The code could not be made. Nothing was changed."))?;        let mut extra = serde_json::Map::new();        extra.insert("code_enc".into(), Value::from(sealed));        set(&door, Kind::Code, plain.as_bytes(), vmk, version, extra)?;        Ok(json!({ "code": made }))    })}fn show(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let door = door(client)?;    let held = get(&door)?;    let entry = held.get("code").filter(|entry| entry.is_object()).ok_or_else(|| MethodError::new("recovery_none", say("none", &[])))?;    let sealed = entry.get("code_enc").and_then(Value::as_str).ok_or_else(|| MethodError::new("recovery_stale", say("stale", &[])))?.to_string();    let at = entry.get("vmk_version").and_then(Value::as_u64).unwrap_or(0) as u32;    with_fresh_vmk(client, request, |vmk, version| {        if at != version {            return Err(MethodError::new("recovery_stale", say("stale", &[])));        }        let opened = vault_core::open(vmk, CODE_ROW, at, &sealed).ok_or_else(|| MethodError::new("recovery_stale", say("stale", &[])))?;        Ok(json!({ "code": String::from_utf8_lossy(&opened) }))    })}/// The platform store a call names: `google` (Block Store) or `apple` (iCloud Keychain).fn store_arg(request: &Value) -> Result<Kind, MethodError> {    request        .get("store")        .and_then(Value::as_str)        .and_then(Kind::parse)        .filter(|kind| kind.is_platform())        .ok_or_else(|| MethodError::new("bad_store", "store is google or apple"))}fn make_platform(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let store = store_arg(request)?;    let door = door(client)?;    with_fresh_vmk(client, request, |vmk, version| {        let key = code::platform_key();        set(&door, store, key.as_ref(), vmk, version, serde_json::Map::new())?;        Ok(json!({ "key": URL_SAFE_NO_PAD.encode(key.as_ref()) }))    })}// ── recovery.open / recovery.openPlatform ──────────────────────────────────fn open(client: &ClientController, request: &Value, kind: Kind) -> Result<Value, MethodError> {    if let Some(sentence) = client.write_refusal() {        return Err(MethodError::new(vault::REFUSED_DEVICE, sentence));    }    // The secret first: a typo is said before anything is sent.    let secret: zeroize::Zeroizing<Vec<u8>> = match kind {        Kind::Code => {            let typed = owner::text(request, "code")?;            zeroize::Zeroizing::new(code::normalize(&typed).map_err(|problem| MethodError::new(problem.code(), problem_line(problem)))?.into_bytes())        }        Kind::Google | Kind::Apple => {            let key = owner::text(request, "key")?;            zeroize::Zeroizing::new(URL_SAFE_NO_PAD.decode(key.trim()).ok().filter(|bytes| bytes.len() == 32).ok_or_else(|| MethodError::new("bad_key", "key is 32 bytes, base64url"))?)        }        Kind::Trusted => return Err(MethodError::new("bad_kind", "a trusted person's way in opens through recovery.helped")),        Kind::Circle => return Err(MethodError::new("bad_kind", "the circle's way in opens through recovery.circleWait")),    };    let private = vault::private_key_arg(request)?;    let door = door(client)?;    open_with(client, request, &door, kind, &secret, &private, &[])}/// The way back in of `kind` opened with `secret`: asked of the object (its try limit), the wrap opened here, and/// this device taken into the vault.pub(super) fn open_with(client: &ClientController, request: &Value, door: &ObjectDoor, kind: Kind, secret: &[u8], private: &[u8; 32], fills: &[(&str, &str)]) -> Result<Value, MethodError> {    let held = get(door)?;    let entry = held.get(kind.as_str()).filter(|entry| entry.is_object()).ok_or_else(|| MethodError::new("recovery_none", say("none", &[])))?;    let salt = entry.get("salt").and_then(Value::as_str).and_then(|salt| URL_SAFE_NO_PAD.decode(salt).ok()).ok_or_else(|| MethodError::new("unreadable", "the way back in has no salt"))?;    let kdf = entry.get("kdf").and_then(Value::as_str).and_then(Kdf::parse).ok_or_else(|| MethodError::new("unreadable", "the way back in names a stretch this build does not know"))?;    let keys = code::derive(secret, &salt, kdf).ok_or_else(|| MethodError::new("unreadable", "the secret could not be stretched"))?;    let (status, answer) = post(door, "/open", &json!({ "kind": kind.as_str(), "auth": URL_SAFE_NO_PAD.encode(keys.auth.as_ref()) }))?;    match (status, answer.get("code").and_then(Value::as_str)) {        (200, _) => {}        (_, Some("recovery_wrong")) => {            let left = answer.get("tries_left").and_then(Value::as_u64).unwrap_or(0).to_string();            return Err(MethodError::new("recovery_wrong", say("wrong", &[("n", &left)])).with_details(json!({ "triesLeft": answer.get("tries_left") })));        }        (_, Some("recovery_wait")) => {            let seconds = answer.get("retry_after").and_then(Value::as_u64).unwrap_or(60);            let minutes = seconds.div_ceil(60).to_string();            return Err(MethodError::new("recovery_wait", say("wait", &[("n", &minutes)])).with_details(json!({ "retryAfter": seconds })));        }        (_, Some("recovery_none")) => return Err(MethodError::new("recovery_none", say("none", &[]))),        _ => return Err(refused_by(status, &answer)),    }    let version = answer.get("vmk_version").and_then(Value::as_u64).unwrap_or(0) as u32;    let wrapped = answer.get("wrapped").and_then(Value::as_str).unwrap_or_default();    let vmk = code::unwrap(&keys.wrap, kind, version, wrapped)        .map(|bytes| Vmk::from_bytes(*bytes))        .ok_or_else(|| MethodError::new("recovery_does_not_open", "The way back in did not open the vault key. Nothing was changed."))?;    take_in(client, request, private, vmk, version)?;    let line = match kind {        Kind::Code => "opened",        Kind::Google => "google_opened",        Kind::Apple => "apple_opened",        Kind::Trusted => "helped",        Kind::Circle => "circle_opened",    };    Ok(json!({ "opened": true, "line": say(line, fills) }))}// ── the trusted person (R7d) ───────────────────────────────────────────────/// `recovery.trust {number, name?, privateKey?}`: one of this person's people becomes the one who can help them back in. A/// new secret is split: the person's half is sealed to their sharing key (`help:<this person's number>`) and parked/// in their object; the other half stays in this person's object beside the wrap. A new trust retires the old one.fn trust(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let number = owner::text(request, "number")?;    let door = door(client)?;    let asked = door        .address        .send(door.exchange.as_ref(), "GET", &format!("/v1/send/key?number={}", urlencode(&number)), bearer(&door.credential), None)        .map_err(|refusal| MethodError::new(&refusal.code, refusal.message))?;    let theirs_pub = asked.get("key").and_then(Value::as_str).and_then(share::key_from_text).ok_or_else(|| MethodError::new("unreadable", "their sharing key did not read"))?;    let me = asked.get("me").and_then(Value::as_str).unwrap_or_default().to_string();    let mine = super::send_seal::post_key(client)?;    with_fresh_vmk(client, request, |vmk, version| {        let secret = code::platform_key();        let (theirs, held) = code::split(&secret);        let sealed = share::seal_to_person(&mine, &theirs_pub, &code::help_context(&me), theirs.as_ref()).map_err(|e| MethodError::new(e.code(), e.to_string()))?;        let mut extra = serde_json::Map::new();        extra.insert("helper".into(), Value::from(number.clone()));        extra.insert("share".into(), Value::from(URL_SAFE_NO_PAD.encode(held.as_ref())));        extra.insert("box".into(), Value::from(sealed));        let shown = owner::optional_text(request, "name").unwrap_or_else(|| number.clone());        extra.insert("helper_name".into(), Value::from(shown.clone()));        set(&door, Kind::Trusted, secret.as_ref(), vmk, version, extra)?;        Ok(json!({ "trusted": true, "line": say("help_chosen", &[("name", &shown)]) }))    })}fn urlencode(text: &str) -> String {    text.bytes().map(|b| if b.is_ascii_alphanumeric() || b == b'-' || b == b'.' || b == b'_' { (b as char).to_string() } else { format!("%{b:02X}") }).collect()}/// What a new device keeps while its ask for help waits (TRUSTED RECOVERY BUILD 1): which database, its key, the ask/// it minted, the account it asks as, and the nonce it committed to, revealed only once the helper's nonce has come./// Kept in a file beside the data, so a restart does not lose the compare.const ASKING_FILE: &str = "recovery-help-ask.json";/// What a helper's phone keeps per ask it opened: its own nonce, and the device key and commit it saw when it set it./// It approves only against these, never against what the server says later.const HELPING_FILE: &str = "recovery-help-in.json";/// What a helper's phone counts per person it helps (TRUSTED RECOVERY BUILD 2, review LOW): compares opened and wrong/// codes in the last day, so a server cannot guess its way through by starting compare after compare.const GUARD_FILE: &str = "recovery-help-guard.json";/// Compares a helper's phone opens for one person in a day, and wrong codes it takes, before it stops helping that/// day. Each compare is one chance in a million: at most three a day.pub(super) const COMPARES_PER_DAY: usize = 3;pub(super) const WRONG_PER_DAY: usize = 3;const DAY_MS: i64 = 24 * 60 * 60 * 1000;#[derive(serde::Serialize, serde::Deserialize, Default, Clone)]struct Asking {    database: String,    device_key: String,    nonce: String,    #[serde(default)]    request: String,    #[serde(default)]    account: String,}#[derive(serde::Serialize, serde::Deserialize, Default, Clone, PartialEq)]struct Helping {    nonce_b: String,    commit: String,    device_key: String,    /// The person's number as this phone's own pin of them holds it: who the compare is for.    #[serde(default)]    account: String,}/// A helper's phone's counts for one person: when it opened compares and when it took wrong codes.#[derive(serde::Serialize, serde::Deserialize, Default, Clone)]pub(super) struct Guard {    #[serde(default)]    pub(super) opened: Vec<i64>,    #[serde(default)]    pub(super) wrong: Vec<i64>,}impl Guard {    fn recent(list: &[i64], now: i64) -> usize {        list.iter().filter(|at| now - **at < DAY_MS).count()    }    pub(super) fn may_open(&self, now: i64) -> bool {        Self::recent(&self.opened, now) < COMPARES_PER_DAY && Self::recent(&self.wrong, now) < WRONG_PER_DAY    }    pub(super) fn may_answer(&self, now: i64) -> bool {        Self::recent(&self.wrong, now) < WRONG_PER_DAY    }}/// The guard for one person this phone helps (`who` is their number or account), changed and kept.pub(super) fn guarded(client: &ClientController, who: &str, change: impl FnOnce(&mut Guard, i64)) -> Result<Guard, MethodError> {    let mut all: std::collections::BTreeMap<String, Guard> = kept(client, GUARD_FILE);    let now = client.now().timestamp_millis();    let slot = format!("{}/{who}", database_of(client));    let guard = all.entry(slot).or_default();    change(guard, now);    guard.opened.retain(|at| now - at < DAY_MS);    guard.wrong.retain(|at| now - at < DAY_MS);    let out = guard.clone();    keep(client, GUARD_FILE, &all)?;    Ok(out)}pub(super) fn guard_of(client: &ClientController, who: &str) -> Guard {    let all: std::collections::BTreeMap<String, Guard> = kept(client, GUARD_FILE);    all.get(&format!("{}/{who}", database_of(client))).cloned().unwrap_or_default()}/// Who a box held for a person was really sealed by (TRUSTED RECOVERY BUILD 2, review M1): the box opened with this/// phone's sharing key under its context, its authenticated sender matched against this phone's own pins (S1). Answers/// that person's number, their name as this phone's own people list says it, and what the box held; None when the box/// does not open or no pin holds its sender's key. Never the name or number a server sends.pub(super) fn sealed_by(client: &ClientController, notes: &std::collections::BTreeMap<String, Value>, sealed: &str, context: &str) -> Result<Option<(String, String, Vec<u8>)>, MethodError> {    let (mine, _) = super::send_seal::sharing(client)?;    let Ok(opened) = share::open_from_person(&mine, sealed, context) else { return Ok(None) };    let Some(number) = super::secrets_app::pinned_number(notes, &opened.sender) else { return Ok(None) };    let name = super::secrets_app::own_name_of(client, &number);    Ok(Some((number, name, opened.payload.to_vec())))}/// The device unlock (the vault key the shell reads behind Face ID or the passcode, or an unlock held) before a helper's/// phone lets anything go (TRUSTED RECOVERY BUILD 2, review LOW): a screen that is merely on is not enough.pub(super) fn device_unlocked(client: &ClientController, request: &Value) -> Result<(), MethodError> {    with_vmk(client, request, |_, _| Ok(())).map_err(|_| MethodError::new("device_unlock_needed", say("help_unlock_needed", &[])))}/// This person's number as the new device signed in with it: the account its compare is for.fn own_number(client: &ClientController) -> Result<String, MethodError> {    super::cotton_chat::my_number(client).filter(|n| !n.is_empty()).ok_or_else(|| MethodError::new("offline", "This device does not know its number yet. Try again when it is online."))}pub(super) fn kept<T: serde::de::DeserializeOwned + Default>(client: &ClientController, file: &str) -> T {    std::fs::read(client.layout().root().join(file)).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default()}pub(super) fn keep<T: serde::Serialize>(client: &ClientController, file: &str, value: &T) -> Result<(), MethodError> {    let bytes = serde_json::to_vec(value).map_err(|e| MethodError::new("unreadable", e.to_string()))?;    // not a copy: trusted recovery's own small state file beside the copies.    cotton_client::whole_file::replace(&client.layout().root().join(file), &bytes).map_err(|e| MethodError::new("unwritable", e.to_string()))}/// The circle as every device of the person shows it (TRUSTED RECOVERY BUILD 1, step 4), and a circle set but not yet/// live (`pending`, BUILD 2 review M2: the way in before it stands until it is). With `hide`, no name or number of a/// helper is shown, only how many.fn circle_status(client: &ClientController, entry: &Value, current: Option<u32>, hide: bool) -> Value {    let strip = |list: Vec<Value>| -> Vec<Value> {        if !hide {            return list;        }        list.into_iter().map(|m| json!({ "index": m.get("index"), "state": m.get("state") })).collect()    };    let members = strip(entry.get("members").and_then(Value::as_array).cloned().unwrap_or_default());    let and = |names: &[String]| match names {        [] => String::new(),        [one] => one.clone(),        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),    };    let named = |list: &[Value], state: &str| -> Vec<String> { list.iter().filter(|m| m["state"] == json!(state)).filter_map(|m| m["name"].as_str().filter(|n| !n.is_empty()).or_else(|| m["number"].as_str()).map(str::to_string)).collect() };    let count = |list: &[Value], state: &str| list.iter().filter(|m| m["state"] == json!(state)).count();    let live = entry.get("live").and_then(Value::as_bool).unwrap_or(false);    let version = entry.get("vmk_version").and_then(Value::as_u64).unwrap_or(0) as u32;    let fresh = current.is_none_or(|current| version >= current);    let mut line = String::new();    if hide {        if !members.is_empty() {            line = say("circle_count", &[("done", &count(&members, "accepted").to_string()), ("n", &members.len().to_string())]);        }    } else {        let (helping, asked, gone) = (named(&members, "accepted"), named(&members, "asked"), named(&members, "gone"));        if !helping.is_empty() {            line = say("circle_helps", &[("names", &and(&helping))]);        }        if !asked.is_empty() {            line = format!("{line} {}", say("circle_waiting_accept", &[("names", &and(&asked))])).trim().to_string();        }        if !gone.is_empty() {            line = format!("{line} {}", say("circle_gone", &[("names", &and(&gone))])).trim().to_string();        }    }    if !fresh && !members.is_empty() {        line = say("circle_stale", &[]);    }    let pending = entry.get("pending").filter(|p| p.is_object()).map(|p| {        let list = strip(p.get("members").and_then(Value::as_array).cloned().unwrap_or_default());        let waiting = if hide { say("circle_count", &[("done", &count(&list, "accepted").to_string()), ("n", &list.len().to_string())]) } else { say("circle_waiting_accept", &[("names", &and(&named(&list, "asked")))]) };        json!({ "setup": p.get("setup"), "k": p.get("k"), "n": p.get("n"), "members": list, "line": format!("{} {waiting}", say("circle_pending", &[])) })    });    let request = entry.get("request").filter(|r| r.get("state").and_then(Value::as_str) == Some("waiting")).map(|r| {        let device = r.get("name").and_then(Value::as_str).unwrap_or_default();        let ends = r.get("ends_at").and_then(Value::as_i64).unwrap_or_default();        let when = super::recovery_circle::when_of(client, ends);        json!({ "id": r.get("id"), "endsAt": ends, "line": say("circle_request", &[("device", device), ("when", &when)]), "stop": say("circle_stop", &[]) })    });    json!({ "live": live && fresh, "current": fresh, "k": entry.get("k"), "n": entry.get("n"), "members": members, "line": line, "pending": pending, "request": request, "paused": entry.get("paused_until").is_some() })}pub(super) fn bytes32(text: Option<&str>) -> Option<[u8; 32]> {    URL_SAFE_NO_PAD.decode(text?).ok()?.try_into().ok()}pub(super) fn database_of(client: &ClientController) -> String {    client.current_database().unwrap_or_default()}/// `recovery.askHelp {privateKey, name?}`: a new device of this person asks their trusted person to help it in: its/// own key published, the ask (an id it mints) sent with its vault key's public half and a commit to whose recovery it/// is, that key and a nonce it keeps. The key's fingerprint goes too, for a helper whose phone runs an earlier build.fn ask_help(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let private = vault::private_key_arg(request)?;    let key = vault_core::wrap::public_of(&private);    let public = URL_SAFE_NO_PAD.encode(key);    let name = owner::optional_text(request, "name");    vault::publish_on_need(client, &public, name.as_deref())?;    let account = own_number(client)?;    let id = URL_SAFE_NO_PAD.encode(&code::salt());    let nonce = code::platform_key();    let commit = code::help_commit(&code::HelpFor { account: &account, setup: code::TRUSTED_SETUP, index: 0, request: &id }, &key, &nonce);    keep(client, ASKING_FILE, &Asking { database: database_of(client), device_key: public.clone(), nonce: URL_SAFE_NO_PAD.encode(nonce.as_ref()), request: id.clone(), account })?;    let fingerprint = vault_core::wrap::fingerprint(&public).unwrap_or_default();    let door = door(client)?;    let (status, answer) = post(&door, &format!("/help/ask{FLOW}"), &json!({ "id": id, "device_key": public, "commit": URL_SAFE_NO_PAD.encode(commit), "code": fingerprint, "name": name }))?;    if status != 200 {        return Err(refused_by(status, &answer));    }    let helper = answer.get("name").and_then(Value::as_str).unwrap_or_default();    Ok(json!({ "asked": true, "line": say("asked_helper", &[("name", helper)]) }))}/// `recovery.helped {privateKey, name?}`: where this device's ask stands. Once the helper's phone has set its nonce,/// this device reveals its own and answers the six digits to read to the helper (`state: compare`, `code`, `line`);/// once the helper approved, their half (wrapped to this device's key) and the object's half are joined, and the vault/// opens as for a code. A helper whose phone runs an earlier build answers with no compare, as it always did./// Answers `{opened: false, state}` while it waits.fn helped(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let private = vault::private_key_arg(request)?;    let key = vault_core::wrap::public_of(&private);    let door = door(client)?;    let asked = door        .address        .send(door.exchange.as_ref(), "GET", &format!("/v1/recovery/help/ask{FLOW}"), bearer(&door.credential), None)        .map_err(|refusal| MethodError::new(&refusal.code, refusal.message))?;    let state = asked.get("state").and_then(Value::as_str).unwrap_or("none").to_string();    let name = asked.get("name").and_then(Value::as_str).unwrap_or_default().to_string();    if state == "opened" || state == "compare" {        let mine: Asking = kept(client, ASKING_FILE);        let (Some(nonce), Some(nonce_b)) = (bytes32(Some(&mine.nonce)), bytes32(asked.get("nonce_b").and_then(Value::as_str))) else {            return Ok(json!({ "opened": false, "state": "again", "line": say("help_again", &[("name", &name)]) }));        };        if mine.database != database_of(client) || mine.device_key != URL_SAFE_NO_PAD.encode(key) || mine.request.is_empty() || mine.account.is_empty() {            return Ok(json!({ "opened": false, "state": "again", "line": say("help_again", &[("name", &name)]) }));        }        if state == "opened" {            let (status, answer) = post(&door, &format!("/help/reveal{FLOW}"), &json!({ "nonce": mine.nonce }))?;            if status != 200 {                return Err(refused_by(status, &answer));            }        }        let at = code::HelpFor { account: &mine.account, setup: code::TRUSTED_SETUP, index: 0, request: &mine.request };        let shown = vault_core::approval::shown_code(&code::help_sas(&at, &key, &nonce, &nonce_b));        return Ok(json!({ "opened": false, "state": "compare", "code": shown, "line": say("help_read_code", &[("name", &name), ("code", &shown)]) }));    }    if state != "approved" {        return Ok(json!({ "opened": false, "state": state }));    }    let sealed = asked.get("sealed").and_then(Value::as_str).unwrap_or_default();    let theirs: [u8; 32] = vault_core::wrap::unwrap(&private, sealed).and_then(|bytes| bytes.try_into().ok()).ok_or_else(|| MethodError::new("recovery_does_not_open", "The half your helper sent does not open on this device."))?;    let held: [u8; 32] = asked.get("share").and_then(Value::as_str).and_then(|text| URL_SAFE_NO_PAD.decode(text).ok()).and_then(|bytes| bytes.try_into().ok()).ok_or_else(|| MethodError::new("unreadable", "the object's half did not read"))?;    let secret = code::join(&theirs, &held);    let opened = open_with(client, request, &door, Kind::Trusted, secret.as_ref(), &private, &[("name", &name)])?;    // The ask is over: the nonce it kept goes (not a copy: a small note of this ask).    let _ = std::fs::remove_file(client.layout().root().join(ASKING_FILE));    Ok(opened)}/// One ask as the helper's phone weighs it: `old_flow` (the asking device runs an earlier build: it cannot be checked/// by the digits, so never approvable here), `unknown` (the half kept does not open as sealed by anyone this phone/// checked in Secrets), `waiting` (its nonce set, the device not yet revealed), `compare` (the device revealed a nonce/// that hashes to the commit this phone saw: type the code), `changed` (the device key, the commit or the nonce differs/// from what this phone kept, or the reveal does not hash: never approvable), `elsewhere` (another device of the helper/// opened it), `resting` (this phone took its day's compares or wrong codes for that person).fn phase_of(ask: &Value, record: Option<&Helping>, id: &str) -> &'static str {    if ask.get("flow").and_then(Value::as_u64) == Some(1) || ask.get("commit").is_none() {        return "old_flow";    }    let Some(record) = record else { return "elsewhere" };    let text = |field: &str| ask.get(field).and_then(Value::as_str).unwrap_or_default().to_string();    if text("device_key") != record.device_key || text("commit") != record.commit || text("nonce_b") != record.nonce_b {        return "changed";    }    let Some(reveal) = bytes32(ask.get("reveal").and_then(Value::as_str)) else { return "waiting" };    let at = code::HelpFor { account: &record.account, setup: code::TRUSTED_SETUP, index: 0, request: id };    match (bytes32(Some(&record.device_key)), bytes32(Some(&record.commit))) {        (Some(key), Some(commit)) if code::help_commit(&at, &key, &reveal) == commit => "compare",        _ => "changed",    }}/// What a helper's phone offers on an ask or piece from someone it has not checked (S1): Secrets' check of the number it/// is said to be from, the six words compared in person or on a call. Checking is safe whoever the number is: it pins/// only a key the person confirms, and the ask is then named and judged by that pin.pub(super) fn check_act(number: &str) -> Value {    if number.is_empty() {        return Value::Null;    }    json!({ "method": "secrets.check", "number": number, "label": say("help_check", &[]) })}fn help_line(phase: &str, name: &str) -> String {    match phase {        "compare" => say("help_type", &[("name", name)]),        "changed" => say("help_changed", &[("name", name)]),        "elsewhere" => say("help_elsewhere", &[("name", name)]),        "old_flow" => say("help_old_flow", &[("name", name)]),        "unknown" => say("help_not_checked", &[]),        "resting" => say("help_resting", &[("name", name)]),        _ => say("help_waiting", &[("name", name)]),    }}/// `recovery.helpAsks {}`: on a trusted person's phone, the people of theirs asking for help now. Each ask is named by/// who sealed the half kept for it, as this phone's own pins and people list say (never the server's label); one from/// nobody this phone checked is `unknown`. A new ask is opened at once with this phone's own nonce, the device key and/// commit it carries kept here first, within the day's compares for that person. No code: the helper types the code/// the person reads from their new device.fn help_asks(client: &ClientController) -> Result<Value, MethodError> {    let door = door(client)?;    let listed = door        .address        .send(door.exchange.as_ref(), "GET", &format!("/v1/recovery/help{FLOW}"), bearer(&door.credential), None)        .map_err(|refusal| MethodError::new(&refusal.code, refusal.message))?;    let database = database_of(client);    let notes = super::secrets_app::notes(client)?;    let mut records: std::collections::BTreeMap<String, Helping> = kept(client, HELPING_FILE);    let listed_asks = listed.get("asks").and_then(Value::as_array).cloned().unwrap_or_default();    let mut asks = Vec::new();    let now = client.now().timestamp_millis();    for ask in listed_asks {        let id = ask.get("id").and_then(Value::as_str).unwrap_or_default().to_string();        let peer = ask.get("peer").and_then(Value::as_str).unwrap_or_default().to_string();        let slot = format!("{database}/{id}");        let sealed = ask.get("box").and_then(Value::as_str).unwrap_or_default();        // Who it is for: the half kept for them, sealed by someone this phone checked, under that person's context.        let who = sealed_by(client, &notes, sealed, &code::help_context(&peer))?.filter(|(number, _, _)| *number == peer);        let Some((account, name, _)) = who else {            asks.push(json!({ "id": id, "name": "", "phase": "unknown", "line": help_line("unknown", ""), "check": check_act(&peer), "decline": say("help_decline", &[]) }));            continue;        };        let new_flow = ask.get("commit").is_some() && ask.get("flow").is_none();        if new_flow && !records.contains_key(&slot) && ask.get("nonce_b").is_none() && guard_of(client, &account).may_open(now) {            let nonce_b = URL_SAFE_NO_PAD.encode(code::platform_key().as_ref());            let record = Helping {                nonce_b: nonce_b.clone(),                commit: ask.get("commit").and_then(Value::as_str).unwrap_or_default().to_string(),                device_key: ask.get("device_key").and_then(Value::as_str).unwrap_or_default().to_string(),                account: account.clone(),            };            records.insert(slot.clone(), record);            keep(client, HELPING_FILE, &records)?;            guarded(client, &account, |g, now| g.opened.push(now))?;            let (status, answer) = post(&door, &format!("/help/open{FLOW}"), &json!({ "id": id, "nonce": nonce_b }))?;            let theirs = answer.get("nonce").and_then(Value::as_str);            if status != 200 || theirs.is_some_and(|nonce| nonce != nonce_b) {                // Another device of this helper set its nonce first: this one can never vouch for that compare.                records.remove(&slot);                keep(client, HELPING_FILE, &records)?;            }        }        let mut seen = ask.clone();        if let (Some(record), Some(object)) = (records.get(&slot), seen.as_object_mut()) {            if !object.contains_key("nonce_b") {                object.insert("nonce_b".into(), Value::from(record.nonce_b.clone()));            }        }        let mut phase = phase_of(&seen, records.get(&slot).filter(|r| r.account == account), &id);        if (phase == "elsewhere" || phase == "compare" || phase == "waiting") && !records.contains_key(&slot) && !guard_of(client, &account).may_open(now) {            phase = "resting";        }        if phase == "compare" && !guard_of(client, &account).may_answer(now) {            phase = "resting";        }        asks.push(json!({            "id": id,            "name": name,            "phase": phase,            "line": help_line(phase, &name),            "approve": say("help_approve", &[]),            "decline": say("help_decline", &[]),            "approved": say("help_approved", &[("name", &name)]),        }));    }    // Notes of asks no longer listed go.    let live: std::collections::BTreeSet<String> = asks.iter().filter_map(|ask| ask["id"].as_str().map(|id| format!("{database}/{id}"))).collect();    let before = records.len();    records.retain(|slot, _| !slot.starts_with(&format!("{database}/")) || live.contains(slot));    if records.len() != before {        keep(client, HELPING_FILE, &records)?;    }    Ok(json!({ "asks": asks }))}/// `recovery.helpApprove {id, code, privateKey?}` / `recovery.helpDecline {id}`: the trusted person answers. Approve/// needs the device unlock and the six digits the person reads from their new device, typed; this phone works them out/// from whose recovery it is (as its own pin says), the device key and commit it kept when it opened the ask, its own/// nonce and the device's reveal, and only when they match opens the half kept for that person with its sharing key and/// wraps it to that key alone. Wrong codes count for the day per person: at the third, this phone stops helping that/// person until the day is over, and the ask is declined. Decline tells the asker's object no.fn help_answer(client: &ClientController, request: &Value, approve: bool) -> Result<Value, MethodError> {    let id = owner::text(request, "id")?;    let door = door(client)?;    let slot = format!("{}/{id}", database_of(client));    let mut records: std::collections::BTreeMap<String, Helping> = kept(client, HELPING_FILE);    if !approve {        let (status, answer) = post(&door, &format!("/help/answer{FLOW}"), &json!({ "id": id, "decline": true }))?;        if records.remove(&slot).is_some() {            keep(client, HELPING_FILE, &records)?;        }        return if status == 200 { Ok(json!({ "declined": true })) } else { Err(refused_by(status, &answer)) };    }    let Some(typed) = owner::optional_text(request, "code") else {        return Err(MethodError::new("help_code_needed", say("help_code_needed", &[])));    };    device_unlocked(client, request)?;    let listed = door        .address        .send(door.exchange.as_ref(), "GET", &format!("/v1/recovery/help{FLOW}"), bearer(&door.credential), None)        .map_err(|refusal| MethodError::new(&refusal.code, refusal.message))?;    let ask = listed.get("asks").and_then(Value::as_array).and_then(|asks| asks.iter().find(|ask| ask.get("id").and_then(Value::as_str) == Some(id.as_str())).cloned()).ok_or_else(|| MethodError::new("help_not_waiting", "That ask is no longer waiting."))?;    let peer = ask.get("peer").and_then(Value::as_str).unwrap_or_default().to_string();    let sealed = ask.get("box").and_then(Value::as_str).ok_or_else(|| MethodError::new("help_none", "No half is kept here for that person."))?;    let notes = super::secrets_app::notes(client)?;    let Some((account, name, half)) = sealed_by(client, &notes, sealed, &code::help_context(&peer))?.filter(|(number, _, _)| *number == peer) else {        return Err(MethodError::new("help_not_checked", say("help_not_checked", &[])));    };    let now = client.now().timestamp_millis();    if !guard_of(client, &account).may_answer(now) {        return Err(MethodError::new("help_resting", say("help_resting", &[("name", &name)])));    }    let record = records.get(&slot).cloned().filter(|r| r.account == account);    match phase_of(&ask, record.as_ref(), &id) {        "compare" => {}        "old_flow" => return Err(MethodError::new("help_old_flow", say("help_old_flow", &[("name", &name)]))),        "waiting" => return Err(MethodError::new("help_not_compared", say("help_waiting", &[("name", &name)]))),        "elsewhere" => return Err(MethodError::new("help_elsewhere", say("help_elsewhere", &[("name", &name)]))),        _ => return Err(MethodError::new("help_changed", say("help_changed", &[("name", &name)]))),    }    let record = record.expect("a compare has its note");    let (Some(key), Some(nonce_b), Some(reveal)) = (bytes32(Some(&record.device_key)), bytes32(Some(&record.nonce_b)), bytes32(ask.get("reveal").and_then(Value::as_str))) else {        return Err(MethodError::new("help_changed", say("help_changed", &[("name", &name)])));    };    let at = code::HelpFor { account: &account, setup: code::TRUSTED_SETUP, index: 0, request: &id };    if !code::help_code_matches(&code::help_sas(&at, &key, &reveal, &nonce_b), &typed) {        let guard = guarded(client, &account, |g, now| g.wrong.push(now))?;        if !guard.may_answer(now) {            records.remove(&slot);            keep(client, HELPING_FILE, &records)?;            let _ = post(&door, &format!("/help/answer{FLOW}"), &json!({ "id": id, "decline": true }));            return Err(MethodError::new("help_wrong_ended", say("help_wrong_ended", &[("name", &name)])));        }        return Err(MethodError::new("help_wrong_code", say("help_wrong_code", &[("name", &name)])));    }    let wrapped = vault_core::wrap::wrap(&key, &half).ok_or_else(|| MethodError::new("unreadable", "the half could not be wrapped for that device"))?;    let (status, answer) = post(&door, &format!("/help/answer{FLOW}"), &json!({ "id": id, "sealed": wrapped }))?;    if status != 200 {        return Err(refused_by(status, &answer));    }    records.remove(&slot);    keep(client, HELPING_FILE, &records)?;    Ok(json!({ "approved": true }))}/// This device becomes a device of the vault with the key a way back in opened: its own key published (named),/// the vault key wrapped for it on its own row (pushed: the object lets it, as the secret was just proved), the/// person key and the data key taken, and the vault open for the usual five minutes.fn take_in(client: &ClientController, request: &Value, private: &[u8; 32], vmk: Vmk, version: u32) -> Result<(), MethodError> {    let public = URL_SAFE_NO_PAD.encode(vault_core::wrap::public_of(private));    let name = owner::optional_text(request, "name");    vault::publish_on_need(client, &public, name.as_deref())?;    let device = vault::this_device(client).map_err(|why| MethodError::new("unreadable", why))?;    let wrapped_already = client        .with_file(|replica| Ok(devices::keys(replica.driver, replica.workspace_id)?.iter().any(|key| key.device_id == device && key.wrapped)))        .map_err(|why| MethodError::new("unreadable", why))?;    if !wrapped_already {        vault::write(client, "recovery.open", &mut |ctx| devices::approve(ctx, &device, &vmk, version))?;    }    client.nudge_sync();    if let Err(refusal) = super::person_key::ensure(client, &vmk, version) {        tracing::warn!("person key: not kept — {}", refusal.message);    }    if let Err(refusal) = super::seal::ensure(client, &vmk, version) {        tracing::warn!("data key: not taken — {}: {}", refusal.code, refusal.message);    }    let now = client.now();    client.vault().map_err(|why| MethodError::new("unreadable", why))?.unlock(vmk, version, now);    Ok(())}#[cfg(test)]#[path = "recovery_tests.rs"]pub(crate) mod tests;