//! `recovery.circle*`: getting back in with the help of people a person trusts (TRUSTED RECOVERY BUILD 1, step 4; //! assets/design/shared/TRUSTED-RECOVERY.md). The object's half is `apps/business/src/recovery_circle.ts`; the //! arithmetic is `cotton_core::vault::recovery_code` (`circle_pieces`, `circle_join`, `help_commit`, `help_sas`). //! //! ```text //! THE PERSON, on a device that holds the vault: //! recovery.circleSet {numbers: [1 or 3], names?, privateKey?} → {setup, line} each helper checked first (Secrets' S1: //! refused not_checked / key_changed in its words) //! recovery.circleStop {} → {stopped, line} any device of the person //! A NEW DEVICE: //! recovery.circleStart {privateKey, name?} → {started, endsAt, line} //! recovery.circleWait {privateKey, name?} → {opened: false, state, line, helpers: [{index, name, code?, //! helped}]} | {opened: true, line} on every read: it starts each //! helper's compare, reveals once their nonce comes, and opens //! once the object releases its half after the wait //! A HELPER: //! recovery.circleHeld {} → {held: [{account, setup, name, accepted, line, accept, decline}]} //! recovery.circleAccept {account, setup} / circleDecline → {accepted} / {declined} accepting opens the piece once, here, //! to prove it opens; nothing is kept //! recovery.circleAsks {} → {asks: [{request, account, name, phase, line, endsAt, …}]} //! recovery.circleApprove {request, account, code} → {approved} the typed six digits; the piece wrapped to the key //! the digits vouch for, against what this phone kept when it opened //! recovery.circleStopFor {request, account} → {stopped} //! ``` //! //! Nothing here logs or answers a key, a piece, a nonce kept secret or the circle's secret. 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_core::records::page::{stamp_parts, DateWords}; use cotton_core::seal::share; use cotton_core::vault::recovery_code::{self as code, Kind}; use cotton_core::vault::{self as vault_core}; use super::recovery::{bytes32, database_of, device_unlocked, door, guard_of, guarded, keep, kept, open_with, post, refused_by, say, sealed_by, with_vmk, FLOW}; 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; 10] = [ "recovery.circleAccept", "recovery.circleApprove", "recovery.circleAsks", "recovery.circleDecline", "recovery.circleHeld", "recovery.circleSet", "recovery.circleStart", "recovery.circleStop", "recovery.circleStopFor", "recovery.circleWait", ]; /// What a new device keeps per helper while it waits: its nonce for that helper's compare, and the request it is for. const WAITING_FILE: &str = "recovery-circle-wait.json"; /// What a helper's phone keeps per ask it opened: its nonce, and the device key and commit it saw first. const HELPING_FILE: &str = "recovery-circle-help.json"; /// The wait, as the helper's phone holds it on its own clock (TRUSTED RECOVERY BUILD 2, review LOW): no piece leaves /// this phone sooner than this after it first heard of the request, nor before the end the request first carried, so /// the wait holds against a server that lies about the time. pub(crate) const WAIT_MS: i64 = 48 * 60 * 60 * 1000; pub(crate) fn call(client: &ClientController, method: &str, request: &Value) -> Result { match method { "recovery.circleSet" => set(client, request), "recovery.circleStop" => stop(client, request), "recovery.circleStart" => start(client, request), "recovery.circleWait" => wait(client, request), "recovery.circleHeld" => held(client), "recovery.circleAccept" => answer_holding(client, request, true), "recovery.circleDecline" => answer_holding(client, request, false), "recovery.circleAsks" => asks(client), "recovery.circleApprove" => approve(client, request), "recovery.circleStopFor" => stop_for(client, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a circle method"))), } } fn get_at(door: &ObjectDoor, path: &str) -> Result { door.address.send(door.exchange.as_ref(), "GET", &super::recovery::with_flow(path), bearer(&door.credential), None).map_err(|refusal| MethodError::new(&refusal.code, refusal.message)) } fn posted(door: &ObjectDoor, path: &str, body: &Value) -> Result { let (status, answer) = post(door, path, body)?; if status != 200 { return Err(refused_by(status, &answer)); } Ok(answer) } fn b64(bytes: &[u8]) -> String { URL_SAFE_NO_PAD.encode(bytes) } pub(super) fn when_of(client: &ClientController, ms: i64) -> String { when(client, ms) } /// "Saturday 18:40" or "29 Nov 18:40", in the reader's zone and words. fn when(client: &ClientController, ms: i64) -> String { let Some(at) = chrono::DateTime::::from_timestamp_millis(ms) else { return String::new() }; let zone = client.time_zone().unwrap_or("Etc/UTC").to_string(); match stamp_parts(&at.to_rfc3339(), &zone, client.clock().now(), DateWords::shipped()) { Some(parts) => match parts.clock { Some(clock) => format!("{} {clock}", parts.near.unwrap_or(parts.dated)), None => parts.near.unwrap_or(parts.dated), }, None => at.to_rfc3339(), } } // ── The person ── /// `recovery.circleSet {numbers, names?, privateKey?}`: one or three of this person's people, each checked (S1), become /// the circle. R is minted here and split R = H ⊕ Q; the object gets H and the vault key wrapped under R's key; Q goes /// as pieces, each sealed to that helper's pinned key and bound to its place. Nothing of R is kept. fn set(client: &ClientController, request: &Value) -> Result { let numbers: Vec = request.get("numbers").and_then(Value::as_array).map(|list| list.iter().filter_map(|n| n.as_str().map(str::to_string)).collect()).unwrap_or_default(); let k = match numbers.len() { 1 => 1, 3 => 2, _ => return Err(MethodError::new("bad_members", say("circle_shape", &[]))), }; let names: Vec> = (0..numbers.len()).map(|i| request.get("names").and_then(|names| names.get(i)).and_then(Value::as_str).map(str::to_string)).collect(); let notes = super::secrets_app::notes(client)?; let keys: Vec<[u8; 32]> = numbers.iter().map(|number| super::secrets_app::checked_key(client, ¬es, number)).collect::>()?; let mine = super::send_seal::post_key(client)?; let door = door(client)?; with_vmk(client, request, |vmk, version| { let secret = code::platform_key(); let held = code::platform_key(); let q = code::join(&secret, &held); let pieces = code::circle_pieces(&q, k, numbers.len()).ok_or_else(|| MethodError::new("bad_members", say("circle_shape", &[])))?; let salt = code::salt(); let derived = code::derive(secret.as_ref(), &salt, Kind::Circle.kdf()).ok_or_else(|| MethodError::new("recovery_unmade", "The circle could not be made. Nothing was changed."))?; let wrapped = code::wrap(&derived.wrap, Kind::Circle, version, vmk.expose()).ok_or_else(|| MethodError::new("recovery_unmade", "The vault key could not be wrapped. Nothing was changed."))?; // The setup id, minted here, binds each piece to its place in this circle. let setup = b64(&code::salt()); let mut members = Vec::new(); for (index, number) in numbers.iter().enumerate() { let sealed = share::seal_to_person(&mine, &keys[index], &code::circle_context(&setup, index), &pieces[index]).map_err(|e| MethodError::new(e.code(), e.to_string()))?; members.push(json!({ "number": number, "name": names[index], "box": sealed })); } let answer = posted(&door, "/circle/set", &json!({ "setup": setup, "salt": b64(&salt), "kdf": Kind::Circle.kdf().text(), "auth_hash": code::auth_hash(&derived.auth), "wrapped": wrapped, "vmk_version": version, "k": k, "held": b64(held.as_ref()), "members": members, }))?; let shown: Vec = numbers.iter().enumerate().map(|(i, n)| names[i].clone().unwrap_or_else(|| n.clone())).collect(); Ok(json!({ "setup": answer.get("setup"), "line": say("circle_chosen", &[("names", &shown.join(", "))]) })) }) } /// `recovery.circleStop {privateKey?}`: any device of the person stops a recovery under way. A device signed in only by /// SMS in the last two days (the object says `fresh`) stops only behind its screen lock: the shell hands in this /// device's own key from the Keychain behind Face ID or the passcode (TRUSTED RECOVERY BUILD 2, review LOW). fn stop(client: &ClientController, request: &Value) -> Result { let door = door(client)?; let standing = get_at(&door, &format!("/v1/recovery{FLOW}"))?; if standing.get("device").and_then(|d| d.get("fresh")).and_then(Value::as_bool) == Some(true) && vault::private_key_arg(request).is_err() { return Err(MethodError::new("screen_lock_needed", say("circle_screen_lock_needed", &[]))); } let answer = posted(&door, "/circle/stop", &json!({}))?; let stopped = answer.get("stopped").and_then(Value::as_bool).unwrap_or(false); Ok(json!({ "stopped": stopped, "line": say(if stopped { "circle_stopped" } else { "circle_nothing_to_stop" }, &[]) })) } // ── A new device ── #[derive(serde::Serialize, serde::Deserialize, Default, Clone)] struct Waiting { database: String, request: String, device_key: String, /// Per helper index: this device's nonce for its compare (secret until revealed). nonces: std::collections::BTreeMap, } /// `recovery.circleStart {privateKey, name?}`: this device asks the circle; the wait begins and everyone is told. fn start(client: &ClientController, request: &Value) -> Result { let private = vault::private_key_arg(request)?; let key = b64(&vault_core::wrap::public_of(&private)); let name = owner::optional_text(request, "name"); vault::publish_on_need(client, &key, name.as_deref())?; let answer = posted(door(client)?.as_ref(), "/circle/start", &json!({ "device_key": key, "name": name }))?; let request_id = answer.get("request").and_then(Value::as_str).unwrap_or_default().to_string(); let ends = answer.get("ends_at").and_then(Value::as_i64).unwrap_or_default(); keep(client, WAITING_FILE, &Waiting { database: database_of(client), request: request_id, device_key: key, nonces: Default::default() })?; // Whether the text with the Stop link went to the person's number (none where texts are not set up): said plainly. let texted = answer.get("texted").and_then(Value::as_bool).unwrap_or(false); let mut line = say("circle_started", &[("when", &when(client, ends))]); if !texted { line = format!("{line} {}", say("circle_no_text", &[])); } Ok(json!({ "started": true, "endsAt": ends, "texted": texted, "line": line })) } /// `recovery.circleWait {privateKey, name?}`: where this device's recovery stands, moving each compare on. fn wait(client: &ClientController, request: &Value) -> Result { let private = vault::private_key_arg(request)?; let key = vault_core::wrap::public_of(&private); let door = door(client)?; let answer = get_at(&door, "/v1/recovery/circle/request")?; let state = answer.get("state").and_then(Value::as_str).unwrap_or("none").to_string(); let mut mine: Waiting = kept(client, WAITING_FILE); let request_id = answer.get("request").and_then(Value::as_str).unwrap_or_default().to_string(); if state == "released" { return open_released(client, request, &door, &answer, &private); } if state != "waiting" { return Ok(json!({ "opened": false, "state": state, "line": say(if state == "stopped" { "circle_stopped" } else { "circle_none" }, &[]) })); } if mine.database != database_of(client) || mine.request != request_id || mine.device_key != b64(&key) { mine = Waiting { database: database_of(client), request: request_id.clone(), device_key: b64(&key), nonces: Default::default() }; } let account = 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."))?; let setup = answer.get("setup").and_then(Value::as_str).unwrap_or_default().to_string(); let mut helpers = Vec::new(); let members = answer.get("members").and_then(Value::as_array).cloned().unwrap_or_default(); for member in &members { let index = member.get("index").and_then(Value::as_u64).unwrap_or(0); let name = member.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); let helped = member.get("approved").and_then(Value::as_bool).unwrap_or(false); if helped || member.get("gone").is_some() { helpers.push(json!({ "index": index, "name": name, "helped": helped })); continue; } let slot = index.to_string(); let at = code::HelpFor { account: &account, setup: &setup, index: index as u32, request: &request_id }; let nonce = mine.nonces.get(&slot).and_then(|n| bytes32(Some(n))); let commit_there = member.get("commit").and_then(Value::as_str).map(str::to_string); // A compare this device can carry on: it holds the nonce for the commit the object holds. let ours = nonce.filter(|n| commit_there.as_deref() == Some(b64(&code::help_commit(&at, &key, n)).as_str())); let Some(nonce) = ours else { let fresh = code::platform_key(); let commit = code::help_commit(&at, &key, &fresh); mine.nonces.insert(slot.clone(), b64(fresh.as_ref())); keep(client, WAITING_FILE, &mine)?; posted(&door, "/circle/commit", &json!({ "index": index, "commit": b64(&commit) }))?; helpers.push(json!({ "index": index, "name": name, "helped": false, "line": say("circle_call", &[("name", &name)]) })); continue; }; let Some(nonce_b) = bytes32(member.get("nonce_b").and_then(Value::as_str)) else { helpers.push(json!({ "index": index, "name": name, "helped": false, "line": say("circle_call", &[("name", &name)]) })); continue; }; if member.get("reveal").is_none() { posted(&door, "/circle/reveal", &json!({ "index": index, "nonce": b64(&nonce) }))?; } let shown = vault_core::approval::shown_code(&code::help_sas(&at, &key, &nonce, &nonce_b)); helpers.push(json!({ "index": index, "name": name, "helped": false, "code": shown, "line": say("help_read_code", &[("name", &name), ("code", &shown)]) })); } let ends = answer.get("ends_at").and_then(Value::as_i64).unwrap_or_default(); let k = answer.get("k").and_then(Value::as_u64).unwrap_or(1); let done = helpers.iter().filter(|h| h["helped"] == json!(true)).count(); Ok(json!({ "opened": false, "state": "waiting", "endsAt": ends, "line": say("circle_waiting", &[("when", &when(client, ends)), ("done", &done.to_string()), ("k", &k.to_string())]), "helpers": helpers, })) } /// The object released H and k pieces: each piece opened with this device's key, Q joined, R = H ⊕ Q, and the vault /// opened as for any way back in (the auth key proves R, the wrap opens here). fn open_released(client: &ClientController, request: &Value, door: &ObjectDoor, answer: &Value, private: &[u8; 32]) -> Result { let held = bytes32(answer.get("held").and_then(Value::as_str)).ok_or_else(|| MethodError::new("unreadable", "the object's half did not read"))?; let k = answer.get("k").and_then(Value::as_u64).unwrap_or(1) as usize; let n = if k == 1 { 1 } else { 3 }; let pieces: Vec> = answer .get("pieces") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(|piece| vault_core::wrap::unwrap(private, piece.get("sealed")?.as_str()?)) .map(|bytes| bytes.to_vec()) .collect(); let slices: Vec<&[u8]> = pieces.iter().map(Vec::as_slice).collect(); let q = code::circle_join(k, n, &slices).ok_or_else(|| MethodError::new("recovery_does_not_open", say("circle_does_not_open", &[])))?; let secret = code::join(&q, &held); let opened = open_with(client, request, door, Kind::Circle, secret.as_ref(), private, &[])?; // Over: what this device kept for the wait goes (not a copy: a small note of this wait). let _ = std::fs::remove_file(client.layout().root().join(WAITING_FILE)); Ok(json!({ "opened": opened.get("opened").cloned().unwrap_or(json!(true)), "line": say("circle_opened", &[]), "again": say("circle_again", &[]) })) } // ── A helper ── /// Who a held piece is from, as this phone's own pins say (TRUSTED RECOVERY BUILD 2, review M1): their number, their /// name in this phone's people list, and the piece; None when it opens as sealed by nobody this phone checked. fn from_whom(client: &ClientController, notes: &std::collections::BTreeMap, entry: &Value) -> Result)>, MethodError> { let sealed = entry.get("box").and_then(Value::as_str).unwrap_or_default(); let setup = entry.get("setup").and_then(Value::as_str).unwrap_or_default(); let index = entry.get("index").and_then(Value::as_u64).unwrap_or(0) as usize; sealed_by(client, notes, sealed, &code::circle_context(setup, index)) } /// `recovery.circleHeld {}`: the people who asked this one to help them back in, accepted or not yet, each named as /// this phone's own pins and people list say; a piece from nobody this phone checked shows as such and cannot be accepted. fn held(client: &ClientController) -> Result { let answer = get_at(door(client)?.as_ref(), "/v1/recovery/circle/held")?; let notes = super::secrets_app::notes(client)?; let mut held = Vec::new(); for h in answer.get("held").and_then(Value::as_array).cloned().unwrap_or_default() { let accepted = h.get("accepted").and_then(Value::as_bool).unwrap_or(false); let Some((_, name, _)) = from_whom(client, ¬es, &h)? else { let number = h.get("number").and_then(Value::as_str).unwrap_or_default(); held.push(json!({ "account": h.get("account"), "setup": h.get("setup"), "name": "", "accepted": accepted, "checked": false, "line": say("help_not_checked", &[]), "check": super::recovery::check_act(number), "decline": say("help_decline", &[]) })); continue; }; held.push(json!({ "account": h.get("account"), "setup": h.get("setup"), "name": name, "accepted": accepted, "checked": true, "line": say(if accepted { "circle_helping" } else { "circle_asked_to_help" }, &[("name", &name)]), "accept": say("circle_accept", &[]), "decline": say("help_decline", &[]), })); } Ok(json!({ "held": held })) } /// `recovery.circleAccept {account, setup}` / `recovery.circleDecline`: accepting opens the piece once here, to prove /// it was sealed to this phone's key and its place by someone this phone checked, and keeps nothing; a piece that does /// not open so is refused. fn answer_holding(client: &ClientController, request: &Value, accept: bool) -> Result { let account = owner::text(request, "account")?; let setup = owner::text(request, "setup")?; let door = door(client)?; if accept { let answer = get_at(&door, "/v1/recovery/circle/held")?; let entry = answer.get("held").and_then(Value::as_array).and_then(|list| list.iter().find(|h| h.get("account").and_then(Value::as_str) == Some(account.as_str()) && h.get("setup").and_then(Value::as_str) == Some(setup.as_str())).cloned()).ok_or_else(|| MethodError::new("circle_not_held", "Nothing is kept here for that person."))?; let notes = super::secrets_app::notes(client)?; if from_whom(client, ¬es, &entry)?.is_none() { return Err(MethodError::new("circle_does_not_open", say("circle_piece_does_not_open", &[]))); } } posted(&door, if accept { "/circle/accept" } else { "/circle/decline" }, &json!({ "account": account, "setup": setup }))?; Ok(if accept { json!({ "accepted": true }) } else { json!({ "declined": true }) }) } #[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. #[serde(default)] account: String, /// When this phone first heard of the request, on its own clock, and the end the request carried then. #[serde(default)] seen_at: i64, #[serde(default)] ends_seen: i64, /// The code matched: the piece leaves once this phone's own clock passes `release_at`. #[serde(default)] ready: bool, } impl Helping { fn release_at(&self) -> i64 { self.ends_seen.max(self.seen_at + WAIT_MS) } } fn slot_of(client: &ClientController, ask: &Value) -> String { format!("{}/{}/{}", database_of(client), ask.get("account").and_then(Value::as_str).unwrap_or_default(), ask.get("request").and_then(Value::as_str).unwrap_or_default()) } /// When each request was first heard of here, on this phone's clock (kept apart from the compares, which a new commit /// replaces): slot → (seen_at, ends_at as first carried). const SEEN_FILE: &str = "recovery-circle-seen.json"; /// As `recovery.rs` `phase_of`: `waiting`, `compare`, `changed`, `elsewhere` or `sending` (the code matched; the piece /// leaves when this phone's clock says the wait is over), judged against what this phone kept. fn phase_of(ask: &Value, record: Option<&Helping>, account: &str) -> &'static str { if ask.get("commit").is_none() { return "waiting"; } let Some(record) = record.filter(|r| r.account == account) 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 = help_for(ask, account); match (bytes32(Some(&record.device_key)), bytes32(Some(&record.commit))) { (Some(key), Some(commit)) if code::help_commit(&at, &key, &reveal) == commit => { if record.ready { "sending" } else { "compare" } } _ => "changed", } } fn help_for<'a>(ask: &'a Value, account: &'a str) -> code::HelpFor<'a> { code::HelpFor { account, setup: ask.get("setup").and_then(Value::as_str).unwrap_or_default(), index: ask.get("index").and_then(Value::as_u64).unwrap_or(0) as u32, request: ask.get("request").and_then(Value::as_str).unwrap_or_default(), } } /// The piece wrapped to the device's key and sent: only once the code matched and this phone's own clock says the wait /// is over. fn send_piece(client: &ClientController, door: &ObjectDoor, ask: &Value, record: &Helping, piece: &[u8]) -> Result<(), MethodError> { let key = bytes32(Some(&record.device_key)).ok_or_else(|| MethodError::new("unreadable", "the device's key did not read"))?; let wrapped = vault_core::wrap::wrap(&key, piece).ok_or_else(|| MethodError::new("unreadable", "the piece could not be wrapped for that device"))?; let _ = client; posted(door, "/circle/approve", &json!({ "request": ask.get("request"), "account": ask.get("account"), "sealed": wrapped }))?; Ok(()) } /// `recovery.circleAsks {}`: the people this one helps who are getting back in now, each named as this phone's own pins /// say. A compare the new device started is opened at once with this phone's own nonce, the device key and commit kept /// here first, within the day's compares for that person. A piece whose code matched leaves here once this phone's own /// clock says the wait is over. fn asks(client: &ClientController) -> Result { let door = door(client)?; let answer = get_at(&door, "/v1/recovery/circle/asks")?; let notes = super::secrets_app::notes(client)?; let mut records: std::collections::BTreeMap = kept(client, HELPING_FILE); let mut seen_file: std::collections::BTreeMap = kept(client, SEEN_FILE); let now = client.now().timestamp_millis(); let mut out = Vec::new(); for ask in answer.get("asks").and_then(Value::as_array).cloned().unwrap_or_default() { let slot = slot_of(client, &ask); let ends = ask.get("ends_at").and_then(Value::as_i64).unwrap_or_default(); if !seen_file.contains_key(&slot) { seen_file.insert(slot.clone(), (now, ends)); keep(client, SEEN_FILE, &seen_file)?; } let (seen_at, ends_seen) = seen_file[&slot]; let Some((account, name, piece)) = from_whom(client, ¬es, &ask)? else { let number = ask.get("number").and_then(Value::as_str).unwrap_or_default(); out.push(json!({ "request": ask.get("request"), "account": ask.get("account"), "name": "", "phase": "unknown", "line": say("help_not_checked", &[]), "check": super::recovery::check_act(number), "stop": say("circle_stop", &[]) })); continue; }; let commit = ask.get("commit").and_then(Value::as_str).map(str::to_string); // A new commit (the device started again) replaces what was kept for an earlier one, unless the code matched. if let (Some(commit), Some(record)) = (&commit, records.get(&slot)) { if &record.commit != commit && ask.get("nonce_b").is_none() && !record.ready { records.remove(&slot); } } if let Some(commit) = &commit { if !records.contains_key(&slot) && ask.get("nonce_b").is_none() && guard_of(client, &account).may_open(now) { let nonce_b = b64(code::platform_key().as_ref()); records.insert(slot.clone(), Helping { nonce_b: nonce_b.clone(), commit: commit.clone(), device_key: ask.get("device_key").and_then(Value::as_str).unwrap_or_default().to_string(), account: account.clone(), seen_at, ends_seen, ready: false }); keep(client, HELPING_FILE, &records)?; guarded(client, &account, |g, now| g.opened.push(now))?; let (status, opened) = post(&door, "/circle/open", &json!({ "request": ask.get("request"), "account": ask.get("account"), "nonce": nonce_b }))?; if status != 200 || opened.get("nonce").and_then(Value::as_str).is_some_and(|n| n != nonce_b) { 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), &account); if phase == "sending" { let record = records.get(&slot).cloned().expect("a piece sending has its note"); if now >= record.release_at() { send_piece(client, &door, &ask, &record, &piece)?; records.remove(&slot); keep(client, HELPING_FILE, &records)?; out.push(json!({ "request": ask.get("request"), "account": ask.get("account"), "name": name, "phase": "sent", "line": say("circle_helped", &[("name", &name)]) })); continue; } } if (phase == "elsewhere" || phase == "waiting") && !records.contains_key(&slot) && commit.is_some() && !guard_of(client, &account).may_open(now) { phase = "resting"; } let release = records.get(&slot).map(Helping::release_at).unwrap_or(ends_seen.max(seen_at + WAIT_MS)); let line = match phase { "compare" => say("help_type", &[("name", &name)]), "changed" => say("help_changed", &[("name", &name)]), "elsewhere" => say("help_elsewhere", &[("name", &name)]), "resting" => say("help_resting", &[("name", &name)]), "sending" => say("circle_sends_at", &[("name", &name), ("when", &when(client, release))]), _ => say("circle_help_waiting", &[("name", &name), ("when", &when(client, ends))]), }; out.push(json!({ "request": ask.get("request"), "account": ask.get("account"), "name": name, "phase": phase, "line": line, "endsAt": ends, "sendsAt": release, "approve": say("help_approve", &[]), "stop": say("circle_stop", &[]), "approved": say("circle_helped", &[("name", &name)]), })); } // Notes of requests no longer listed go. let live: std::collections::BTreeSet = out.iter().map(|a| format!("{}/{}/{}", database_of(client), a["account"].as_str().unwrap_or_default(), a["request"].as_str().unwrap_or_default())).collect(); let prefix = format!("{}/", database_of(client)); let before = (records.len(), seen_file.len()); records.retain(|slot, _| !slot.starts_with(&prefix) || live.contains(slot)); seen_file.retain(|slot, _| !slot.starts_with(&prefix) || live.contains(slot)); if before != (records.len(), seen_file.len()) { keep(client, HELPING_FILE, &records)?; keep(client, SEEN_FILE, &seen_file)?; } // When this phone next has a piece to send: the shell wakes then (a local notification or a background task) and // calls circleAsks again, as the piece leaves only from here, on this phone's own clock. let next = out.iter().filter(|a| a["phase"] == json!("sending")).filter_map(|a| a["sendsAt"].as_i64()).min(); Ok(json!({ "asks": out, "nextAt": next, "nextLine": next.map(|at| say("circle_open_at", &[("when", &when(client, at))])) })) } /// `recovery.circleApprove {request, account, code, privateKey?}`: as `recovery.helpApprove`: the device unlock, then /// the typed digits against what this phone works out from what it kept and whose recovery its own pin says it is. A /// match sends the piece, wrapped to the device's key alone, once this phone's own clock says the wait is over (now, /// or later from `recovery.circleAsks`). Wrong codes count for the day per person: at the third, this helper's part in /// that request ends (the request goes on with the others). fn approve(client: &ClientController, request: &Value) -> Result { let request_id = owner::text(request, "request")?; let account_id = owner::text(request, "account")?; 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 door = door(client)?; let answer = get_at(&door, "/v1/recovery/circle/asks")?; let ask = answer.get("asks").and_then(Value::as_array).and_then(|list| list.iter().find(|a| a.get("request").and_then(Value::as_str) == Some(request_id.as_str()) && a.get("account").and_then(Value::as_str) == Some(account_id.as_str())).cloned()).ok_or_else(|| MethodError::new("help_not_waiting", "That ask is no longer waiting."))?; let notes = super::secrets_app::notes(client)?; let Some((account, name, piece)) = from_whom(client, ¬es, &ask)? 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 slot = slot_of(client, &ask); let mut records: std::collections::BTreeMap = kept(client, HELPING_FILE); let record = records.get(&slot).cloned(); match phase_of(&ask, record.as_ref(), &account) { "compare" => {} "sending" => return Ok(json!({ "approved": true, "sendsAt": record.as_ref().map(Helping::release_at), "line": say("circle_sends_at", &[("name", &name), ("when", &when(client, record.as_ref().map(Helping::release_at).unwrap_or_default()))]) })), "waiting" => return Err(MethodError::new("help_not_compared", say("circle_help_waiting", &[("name", &name), ("when", "")]))), "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)]))); }; if !code::help_code_matches(&code::help_sas(&help_for(&ask, &account), &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, "/circle/stop-for", &json!({ "request": request_id, "account": account_id })); return Err(MethodError::new("help_wrong_ended", say("circle_wrong_ended", &[("name", &name)]))); } return Err(MethodError::new("help_wrong_code", say("help_wrong_code", &[("name", &name)]))); } let ready = Helping { ready: true, ..record }; if now >= ready.release_at() { send_piece(client, &door, &ask, &ready, &piece)?; records.remove(&slot); keep(client, HELPING_FILE, &records)?; return Ok(json!({ "approved": true, "line": say("circle_helped", &[("name", &name)]) })); } let release = ready.release_at(); records.insert(slot, ready); keep(client, HELPING_FILE, &records)?; Ok(json!({ "approved": true, "sendsAt": release, "line": say("circle_sends_at", &[("name", &name), ("when", &when(client, release))]) })) } /// `recovery.circleStopFor {request, account}`: a helper stops their own part in someone's recovery (the request goes /// on with the others; only the person's own devices stop it whole). fn stop_for(client: &ClientController, request: &Value) -> Result { posted(door(client)?.as_ref(), "/circle/stop-for", &json!({ "request": owner::text(request, "request")?, "account": owner::text(request, "account")? }))?; Ok(json!({ "stopped": true, "line": say("circle_stopped_for", &[]) })) } #[cfg(test)] #[path = "recovery_circle_tests.rs"] mod tests;