572 lines · 33.2 KB · RustRaw
//! `recovery.circle*` end to end with real keys on five copies: a person, three helpers and a new device, over a small//! in-memory stand-in for the objects (the relays only: what each side posted, handed to the other as//! apps/business/src/recovery_circle.ts does). Synthetic keys and numbers only.use std::collections::BTreeMap;use std::io::Read;use std::sync::{Arc, Mutex};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use serde_json::{json, Value};use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::wire::Origin;use cotton_client::transport::{http1::Http1Request, Answer, Exchange};use cotton_core::seal::share::{key_text, seal_to_person, sharing_secret};use cotton_core::vault::recovery_code as rc;use cotton_core::vault::wrap;use super::call;use crate::phone::personal_object::ObjectDoor;use crate::phone::recovery::tests::{holding_a_data_key, newcomer, other_secret};use crate::phone::unlock::tests::{device_secret, wrapped};use crate::shell::client::phone_tests::attached_on_a_clock;use crate::shell::client::ClientController;const OWNER: &str = "+919000000100";const HELPERS: [&str; 3] = ["+919000000101", "+919000000102", "+919000000103"];const FRESH: &str = "fresh";/// The objects, as far as the circle goes: what the person set, what each helper holds, the request and its compares.#[derive(Default)]struct Net { keys: BTreeMap<String, String>, /// Each phone's own Secrets notes (its pins), by who asks. notes: BTreeMap<String, Vec<Value>>, set: Option<Value>, accepted: BTreeMap<usize, bool>, request: Option<String>, device_key: Option<String>, compares: BTreeMap<usize, Value>, released: bool, stopped: bool, /// When set, the object hands helpers this key in place of the device's own (a server that lies). swap_key: Option<String>, /// A server that lies all the way: its own key, a commit to it and the reveal of that commit, all handed to helpers. swap_all: Option<(String, String, String)>, seen: Vec<(String, String, String)>, /// The end a lying server tells helpers, in place of the real one. ends_told: Option<i64>, /// Helpers who stopped their own part. stopped_for: Vec<usize>, /// What GET /v1/recovery says of the calling device (`fresh`: signed in only by SMS in the last two days). fresh_device: bool,}/// The end of the wait the stand-in tells: two days after the copies' clock starts (2026-09-08T10:00Z).const ENDS: i64 = 1_788_861_600_000 + 48 * 60 * 60 * 1000;impl Net { fn helper_index(who: &str) -> Option<usize> { HELPERS.iter().position(|h| *h == who) } fn route(&mut self, who: &str, method: &str, path: &str, body: &Value) -> (u16, Value) { self.seen.push((who.to_string(), method.to_string(), path.to_string())); let set = self.set.clone().unwrap_or(Value::Null); let k = set["k"].as_u64().unwrap_or(1) as usize; match (method, path.split('?').next().unwrap_or(path)) { ("GET", "/v1/send/key") => { let number = path.split("number=").nth(1).unwrap_or_default().replace("%2B", "+"); (200, json!({ "key": self.keys.get(&number).cloned().unwrap_or_default(), "me": who })) } ("POST", "/v1/send/key") => (200, json!({ "ok": true })), ("GET", "/v1/secret/note") => (200, json!({ "notes": self.notes.get(who).cloned().unwrap_or_default() })), ("POST", "/v1/recovery/circle/set") => { self.set = Some(body.clone()); (200, json!({ "setup": body["setup"], "live": false })) } ("GET", "/v1/recovery/circle/held") => { let Some(i) = Net::helper_index(who) else { return (200, json!({ "held": [] })) }; (200, json!({ "held": [{ "account": "p-owner", "number": OWNER, "setup": set["setup"], "index": i, "accepted": self.accepted.get(&i) == Some(&true), "box": set["members"][i]["box"] }] })) } ("POST", "/v1/recovery/circle/accept") => { self.accepted.insert(Net::helper_index(who).unwrap(), true); (200, json!({ "ok": true })) } ("POST", "/v1/recovery/circle/start") => { self.request = Some("req-1".into()); self.device_key = body["device_key"].as_str().map(str::to_string); (200, json!({ "request": "req-1", "ends_at": ENDS })) } ("GET", "/v1/recovery/circle/request") => { if self.stopped { return (200, json!({ "state": "stopped" })); } let members: Vec<Value> = (0..HELPERS.len()).filter(|i| self.accepted.get(i) == Some(&true)).map(|i| { let mut m = json!({ "index": i, "name": format!("Helper {i}"), "approved": self.compares.get(&i).is_some_and(|c| c.get("sealed").is_some()) }); if let Some(c) = self.compares.get(&i) { for field in ["commit", "nonce_b", "reveal"] { if let Some(v) = c.get(field) { m[field] = v.clone(); } } } m }).collect(); if self.released { let pieces: Vec<Value> = self.compares.iter().filter_map(|(i, c)| Some(json!({ "index": i, "sealed": c.get("sealed")? }))).take(k).collect(); return (200, json!({ "state": "released", "request": "req-1", "setup": set["setup"], "k": k, "members": members, "held": set["held"], "pieces": pieces, "ends_at": 0 })); } (200, json!({ "state": "waiting", "request": "req-1", "setup": set["setup"], "k": k, "members": members, "ends_at": ENDS })) } ("POST", "/v1/recovery/circle/commit") => { let i = body["index"].as_u64().unwrap() as usize; self.compares.insert(i, json!({ "commit": body["commit"] })); (200, json!({ "ok": true })) } ("POST", "/v1/recovery/circle/reveal") => { let i = body["index"].as_u64().unwrap() as usize; self.compares.get_mut(&i).unwrap()["reveal"] = body["nonce"].clone(); (200, json!({ "ok": true })) } ("GET", "/v1/recovery/circle/asks") => { let Some(i) = Net::helper_index(who) else { return (200, json!({ "asks": [] })) }; let Some(c) = self.compares.get(&i).filter(|c| c.get("sealed").is_none()) else { return (200, json!({ "asks": [] })) }; let mut ask = json!({ "request": "req-1", "account": "p-owner", "number": OWNER, "setup": set["setup"], "index": i, "device_key": self.swap_key.clone().or(self.device_key.clone()), "ends_at": self.ends_told.unwrap_or(ENDS), "box": set["members"][i]["box"] }); for field in ["commit", "nonce_b", "reveal"] { if let Some(v) = c.get(field) { ask[field] = v.clone(); } } if let Some((key, commit, reveal)) = &self.swap_all { ask["device_key"] = json!(key); ask["commit"] = json!(commit); if c.get("reveal").is_some() { ask["reveal"] = json!(reveal); } } (200, json!({ "asks": [ask] })) } ("POST", "/v1/recovery/circle/open") => { let i = Net::helper_index(who).unwrap(); self.compares.get_mut(&i).unwrap()["nonce_b"] = body["nonce"].clone(); (200, json!({ "nonce": body["nonce"] })) } ("POST", "/v1/recovery/circle/approve") => { let i = Net::helper_index(who).unwrap(); self.compares.get_mut(&i).unwrap()["sealed"] = body["sealed"].clone(); (200, json!({ "ok": true })) } ("POST", "/v1/recovery/circle/stop-for") => { self.stopped_for.push(Net::helper_index(who).unwrap()); (200, json!({ "ok": true })) } ("POST", "/v1/recovery/circle/stop") => { self.stopped = true; (200, json!({ "stopped": true })) } ("GET", "/v1/recovery") => (200, json!({ "code": null, "google": null, "apple": null, "trusted": null, "device": { "fresh": self.fresh_device }, "circle": { "salt": set["salt"], "kdf": "none", "vmk_version": set["vmk_version"], "created_at": "2026-11-27T10:00:00.000Z", "live": true, "k": k, "members": set["members"].as_array().cloned().unwrap_or_default().iter().enumerate().map(|(i, m)| json!({ "index": i, "number": m["number"], "name": format!("Helper {i}"), "state": "accepted" })).collect::<Vec<_>>() } })), ("POST", "/v1/recovery/open") => { let auth = URL_SAFE_NO_PAD.decode(body["auth"].as_str().unwrap()).unwrap(); let hash: String = <sha2::Sha256 as sha2::Digest>::digest(&auth).iter().map(|b| format!("{b:02x}")).collect(); if Some(hash.as_str()) != set["auth_hash"].as_str() { return (403, json!({ "code": "recovery_wrong", "message": "That does not open this account.", "tries_left": 4 })); } (200, json!({ "wrapped": set["wrapped"], "vmk_version": set["vmk_version"] })) } _ => (200, json!({ "ok": true })), } }}#[derive(Debug)]struct Door { net: Arc<Mutex<Net>>, me: String,}impl std::fmt::Debug for Net { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Net") }}struct Answered { status: u16, body: std::io::Cursor<Vec<u8>>,}impl Read for Answered { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { self.body.read(buf) }}impl Answer for Answered { fn status(&self) -> u16 { self.status } fn header(&self, name: &str) -> Option<String> { name.eq_ignore_ascii_case("content-type").then(|| "application/json".into()) } fn content_length(&self) -> Option<u64> { Some(self.body.get_ref().len() as u64) } fn set_read_timeout(&mut self, _: std::time::Duration) -> std::io::Result<()> { Ok(()) }}impl Exchange for Door { fn send(&self, _: &Origin, request: &Http1Request<'_>, _: std::time::Duration) -> Result<Box<dyn Answer>, String> { let body: Value = request.body.and_then(|b| serde_json::from_slice(b).ok()).unwrap_or(Value::Null); let (status, answer) = self.net.lock().unwrap().route(&self.me, request.method, request.path, &body); Ok(Box::new(Answered { status, body: std::io::Cursor::new(answer.to_string().into_bytes()) })) } fn send_stream(&self, origin: &Origin, request: &Http1Request<'_>, body: &mut dyn Read, length: u64, ceiling: std::time::Duration) -> Result<Box<dyn Answer>, String> { let mut bytes = Vec::new(); body.take(length).read_to_end(&mut bytes).map_err(|e| e.to_string())?; self.send(origin, &Http1Request { body: Some(&bytes), headers: request.headers.clone(), ..*request }, ceiling) }}fn on_net(client: &ClientController, net: &Arc<Mutex<Net>>, me: &str) { let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: Arc::new(Door { net: net.clone(), me: me.into() }), credential: "cred-phone".into() }; client.set_object_door(Some(Arc::new(door)));}fn ask(client: &ClientController, method: &str, request: Value) -> Value { call(client, method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}struct World { net: Arc<Mutex<Net>>, owner: Arc<ClientController>, helpers: Vec<Arc<ClientController>>, fresh: Arc<ClientController>, helper_clocks: Vec<Arc<cotton_client::seams::FixedClock>>, _dirs: Vec<tempfile::TempDir>,}/// A phone's own pins (Secrets' S1), sealed to its own key as Secrets keeps them.fn pins_of(client: &ClientController, pins: &[(&str, String)]) -> Vec<Value> { let (mine, public) = crate::phone::secrets_app::me(client).unwrap(); pins.iter() .map(|(number, key)| { let slot = crate::phone::secrets_app::pin_key(number); let pin = json!({ "key": key, "number": number }); let boxed = seal_to_person(&mine, &public, &crate::phone::secrets_app::note_context(&slot), &serde_json::to_vec(&pin).unwrap()).unwrap(); json!({ "key": slot, "box": boxed }) }) .collect()}/// A person whose three helpers' keys are pinned and checked (Secrets' notes), on the stand-in.fn world() -> World { let net = Arc::new(Mutex::new(Net::default())); let mut dirs = Vec::new(); let (od, owner, _) = attached_on_a_clock(); dirs.push(od); wrapped(&owner); holding_a_data_key(&owner); on_net(&owner, &net, OWNER); let mut helpers = Vec::new(); let mut helper_clocks = Vec::new(); for number in HELPERS { let (hd, helper, clock) = attached_on_a_clock(); dirs.push(hd); helper_clocks.push(clock); wrapped(&helper); let dk = holding_a_data_key(&helper); let secret = sharing_secret(&dk, &helper.current_database().unwrap()).unwrap(); net.lock().unwrap().keys.insert(number.into(), key_text(&wrap::public_of(&secret))); on_net(&helper, &net, number); helpers.push(helper); } // The person checked each helper once (S1), and each helper checked the person: a pin each way in their own notes. let keys = net.lock().unwrap().keys.clone(); let owner_notes = pins_of(&owner, &HELPERS.iter().map(|n| (*n, keys[*n].clone())).collect::<Vec<_>>()); let owner_key = key_text(&crate::phone::secrets_app::me(&owner).unwrap().1); net.lock().unwrap().notes.insert(OWNER.into(), owner_notes); for (i, number) in HELPERS.iter().enumerate() { let notes = pins_of(&helpers[i], &[(OWNER, owner_key.clone())]); net.lock().unwrap().notes.insert((*number).into(), notes); } let (fd, fresh, _) = attached_on_a_clock(); dirs.push(fd); newcomer(&fresh); crate::phone::cotton_chat::remember_number(&fresh, OWNER); on_net(&fresh, &net, FRESH); World { net, owner, helpers, fresh, helper_clocks, _dirs: dirs }}fn lent() -> Value { json!(URL_SAFE_NO_PAD.encode(device_secret()))}fn fresh_key() -> Value { json!(URL_SAFE_NO_PAD.encode(other_secret()))}/// The code the new device shows for helper `i` now, if their compare has come that far.fn help_code(world: &World, i: usize) -> Option<String> { let waited = ask(&world.fresh, "recovery.circleWait", json!({ "privateKey": fresh_key() })); waited["helpers"].as_array()?.iter().find(|h| h["index"] == json!(i)).and_then(|h| h["code"].as_str()).map(str::to_string)}/// One helper's turn: they open the compare, the new device shows the code, the helper types it.fn help(world: &World, i: usize, typed: Option<&str>) -> Result<Value, crate::methods::MethodError> { let helper = &world.helpers[i]; let asks = ask(helper, "recovery.circleAsks", json!({})); assert_eq!(asks["asks"][0]["phase"], json!("waiting"), "{asks}"); let waited = ask(&world.fresh, "recovery.circleWait", json!({ "privateKey": fresh_key() })); let code = waited["helpers"].as_array().unwrap().iter().find(|h| h["index"] == json!(i)).and_then(|h| h["code"].as_str()).map(str::to_string).expect("the code to read"); let asks = ask(helper, "recovery.circleAsks", json!({})); assert_eq!(asks["asks"][0]["phase"], json!("compare"), "{asks}"); call(helper, "recovery.circleApprove", &json!({ "request": "req-1", "account": "p-owner", "code": typed.unwrap_or(&code), "privateKey": lent() }))}/// RULE (TRUSTED RECOVERY BUILD 1, step 4): two of three helpers, each checked by the six digits the new device shows,/// and the object's half released after the wait: the new device opens the vault; one helper's piece and the object's/// half alone open nothing; the person must have checked each helper first.#[test]fn two_of_three_helpers_and_the_wait_open_a_new_device_and_fewer_open_nothing() { let world = world(); let set = ask(&world.owner, "recovery.circleSet", json!({ "numbers": HELPERS, "names": ["Asha", "Vikram", "Neha"], "privateKey": lent() })); assert_eq!(set["line"], json!("Asked Asha, Vikram, Neha. Once they accept, they can help you get back in.")); let body = world.net.lock().unwrap().set.clone().unwrap(); assert_eq!(body["k"], json!(2)); assert_eq!(body["members"].as_array().unwrap().len(), 3); for helper in &world.helpers { let held = ask(helper, "recovery.circleHeld", json!({})); assert_eq!(held["held"][0]["accepted"], json!(false)); let entry = &held["held"][0]; ask(helper, "recovery.circleAccept", json!({ "account": entry["account"], "setup": entry["setup"] })); } ask(&world.fresh, "recovery.circleStart", json!({ "privateKey": fresh_key(), "name": "Pixel walk" })); // The first read starts a compare with each helper. let first = ask(&world.fresh, "recovery.circleWait", json!({ "privateKey": fresh_key() })); assert_eq!(first["state"], json!("waiting")); assert!(first["helpers"].as_array().unwrap().iter().all(|h| h.get("code").is_none()), "no code before a helper opens: {first}"); help(&world, 0, None).expect("helper 0 helps"); // A wrong code from the second: refused, nothing sent; then their right one. let wrong = if help_code(&world, 1).as_deref() == Some("000 000") { "111 111" } else { "000 000" }; assert_eq!(help(&world, 1, Some(wrong)).expect_err("a wrong code").code, "help_wrong_code"); assert!(world.net.lock().unwrap().compares[&1].get("sealed").is_none()); let right = help_code(&world, 1).expect("the code to read"); ask(&world.helpers[1], "recovery.circleApprove", json!({ "request": "req-1", "account": "p-owner", "code": right, "privateKey": lent() })); // The codes matched, but no piece leaves a helper's phone before its own clock says the wait is over. assert!(world.net.lock().unwrap().compares.values().all(|c| c.get("sealed").is_none()), "nothing sent inside the wait"); for (i, clock) in world.helper_clocks.iter().enumerate().take(2) { clock.set(chrono::DateTime::from_timestamp_millis(ENDS + 60_000).unwrap()); let asks = ask(&world.helpers[i], "recovery.circleAsks", json!({})); assert_eq!(asks["asks"][0]["phase"], json!("sent"), "{asks}"); } // One helper's piece and the object's half: nothing opens. let net = world.net.lock().unwrap(); let setup = net.set.clone().unwrap(); let salt = URL_SAFE_NO_PAD.decode(setup["salt"].as_str().unwrap()).unwrap(); let held = URL_SAFE_NO_PAD.decode(setup["held"].as_str().unwrap()).unwrap(); let piece0 = wrap::unwrap(&other_secret(), net.compares[&0]["sealed"].as_str().unwrap()).expect("the piece opens for the new device"); assert!(wrap::unwrap(&device_secret(), net.compares[&0]["sealed"].as_str().unwrap()).is_none(), "and for no other key"); assert!(rc::circle_join(2, 3, &[&piece0]).is_none(), "one piece gives nothing"); let held32: [u8; 32] = held.try_into().unwrap(); let alone = rc::derive(&held32, &salt, rc::Kdf::None).unwrap(); assert!(rc::unwrap(&alone.wrap, rc::Kind::Circle, 1, setup["wrapped"].as_str().unwrap()).is_none(), "the object's half alone opens nothing"); drop(net); // Before the wait is over nothing is released; after it, the new device opens. world.net.lock().unwrap().released = true; let opened = ask(&world.fresh, "recovery.circleWait", json!({ "privateKey": fresh_key(), "name": "Pixel walk" })); assert_eq!(opened["opened"], json!(true), "{opened}"); assert_eq!(opened["line"], json!("Opened with your helpers' help.")); use cotton_client::seal::DataKeyStore as _; assert!(world.fresh.data_keys().data_key(&world.fresh.current_database().unwrap()).unwrap().is_some(), "the data key taken");}/// RULE (step 4, with step 1's rule): a server that hands a helper its own key in place of the new device's gets/// nothing. A key swapped alone breaks the commit the helper's phone kept (`changed`); a server that also forges a commit/// to its key and the reveal of it meets the code: the digits the person reads from their real device are not the ones/// the helper's phone works out for the forged key. Nothing is ever wrapped, and nothing without a typed code.#[test]fn a_helper_handed_a_swapped_key_wraps_nothing() { for forged in [false, true] { let world = world(); ask(&world.owner, "recovery.circleSet", json!({ "numbers": [HELPERS[0]], "privateKey": lent() })); let held = ask(&world.helpers[0], "recovery.circleHeld", json!({})); ask(&world.helpers[0], "recovery.circleAccept", json!({ "account": held["held"][0]["account"], "setup": held["held"][0]["setup"] })); ask(&world.fresh, "recovery.circleStart", json!({ "privateKey": fresh_key() })); ask(&world.fresh, "recovery.circleWait", json!({ "privateKey": fresh_key() })); let server_key = [99u8; 32]; let server_pub = wrap::public_of(&server_key); let server_nonce = [7u8; 32]; { let mut net = world.net.lock().unwrap(); if forged { let setup = net.set.clone().unwrap()["setup"].as_str().unwrap().to_string(); let at = rc::HelpFor { account: OWNER, setup: &setup, index: 0, request: "req-1" }; let commit = URL_SAFE_NO_PAD.encode(rc::help_commit(&at, &server_pub, &server_nonce)); net.swap_all = Some((URL_SAFE_NO_PAD.encode(server_pub), commit, URL_SAFE_NO_PAD.encode(server_nonce))); } else { net.swap_key = Some(URL_SAFE_NO_PAD.encode(server_pub)); } } // The helper opens; the real device reveals and shows its code; the helper types that code. ask(&world.helpers[0], "recovery.circleAsks", json!({})); let code = help_code(&world, 0).expect("the real device shows a code"); let asks = ask(&world.helpers[0], "recovery.circleAsks", json!({})); assert_eq!(asks["asks"][0]["phase"], json!(if forged { "compare" } else { "changed" }), "{asks}"); let refused = call(&world.helpers[0], "recovery.circleApprove", &json!({ "request": "req-1", "account": "p-owner", "code": code, "privateKey": lent() })).expect_err("never approved for a swapped key"); assert_eq!(refused.code, if forged { "help_wrong_code" } else { "help_changed" }); assert!(world.net.lock().unwrap().compares[&0].get("sealed").is_none(), "nothing wrapped"); assert_eq!(call(&world.helpers[0], "recovery.circleApprove", &json!({ "request": "req-1", "account": "p-owner", "privateKey": lent() })).expect_err("no code").code, "help_code_needed"); }}/// RULE (step 4): a helper who was never checked (Secrets' S1) cannot be chosen; any device of the person stops it.#[test]fn an_unchecked_helper_is_refused_and_any_device_stops_it() { let world = world(); world.net.lock().unwrap().notes.clear(); let refused = call(&world.owner, "recovery.circleSet", &json!({ "numbers": [HELPERS[0]], "privateKey": lent() })).expect_err("not checked"); assert_eq!(refused.code, "not_checked"); assert!(world.net.lock().unwrap().set.is_none(), "nothing sent"); let stopped = ask(&world.owner, "recovery.circleStop", json!({})); assert_eq!(stopped["stopped"], json!(true)); assert_eq!(stopped["line"], json!("Getting back in on a new phone was stopped. Nothing was opened."));}/// RULE (TRUSTED RECOVERY BUILD 2, review LOW): the wait holds against a server that lies about the time. A helper's/// phone sends its piece only once its own clock is past both the end the request first carried and two days after/// it first heard of the request, whatever end the server tells later; the device unlock comes before anything.#[test]fn a_helpers_piece_waits_for_its_own_clock_whatever_the_server_says() { let world = world(); ask(&world.owner, "recovery.circleSet", json!({ "numbers": [HELPERS[0]], "privateKey": lent() })); let held = ask(&world.helpers[0], "recovery.circleHeld", json!({})); ask(&world.helpers[0], "recovery.circleAccept", json!({ "account": held["held"][0]["account"], "setup": held["held"][0]["setup"] })); // The server tells the helper the wait ended long ago. world.net.lock().unwrap().ends_told = Some(1_000); ask(&world.fresh, "recovery.circleStart", json!({ "privateKey": fresh_key() })); ask(&world.fresh, "recovery.circleWait", json!({ "privateKey": fresh_key() })); ask(&world.helpers[0], "recovery.circleAsks", json!({})); let code = help_code(&world, 0).expect("a code"); ask(&world.helpers[0], "recovery.circleAsks", json!({})); // No device unlock: refused before anything. assert_eq!(call(&world.helpers[0], "recovery.circleApprove", &json!({ "request": "req-1", "account": "p-owner", "code": code })).unwrap_err().code, "device_unlock_needed"); let approved = ask(&world.helpers[0], "recovery.circleApprove", json!({ "request": "req-1", "account": "p-owner", "code": code, "privateKey": lent() })); assert!(approved["sendsAt"].as_i64().is_some(), "{approved}"); // The shell is told when to wake this phone to send it. let listed = ask(&world.helpers[0], "recovery.circleAsks", json!({})); assert_eq!(listed["nextAt"], approved["sendsAt"], "{listed}"); assert!(world.net.lock().unwrap().compares[&0].get("sealed").is_none(), "not sent: two days have not passed on this phone"); world.helper_clocks[0].advance(chrono::Duration::hours(47)); ask(&world.helpers[0], "recovery.circleAsks", json!({})); assert!(world.net.lock().unwrap().compares[&0].get("sealed").is_none(), "not at 47 hours"); world.helper_clocks[0].advance(chrono::Duration::hours(2)); let asks = ask(&world.helpers[0], "recovery.circleAsks", json!({})); assert_eq!(asks["asks"][0]["phase"], json!("sent"), "{asks}"); assert!(world.net.lock().unwrap().compares[&0].get("sealed").is_some());}/// RULE (TRUSTED RECOVERY BUILD 2, review M3 and LOW): three wrong codes end only this helper's part (stop-for), and a/// device signed in only by SMS in the last two days stops a recovery only behind its screen lock.#[test]fn wrong_codes_end_only_the_helpers_part_and_a_fresh_device_stops_behind_its_lock() { let world = world(); ask(&world.owner, "recovery.circleSet", json!({ "numbers": HELPERS, "privateKey": lent() })); for helper in &world.helpers { let held = ask(helper, "recovery.circleHeld", json!({})); ask(helper, "recovery.circleAccept", json!({ "account": held["held"][0]["account"], "setup": held["held"][0]["setup"] })); } ask(&world.fresh, "recovery.circleStart", json!({ "privateKey": fresh_key() })); ask(&world.fresh, "recovery.circleWait", json!({ "privateKey": fresh_key() })); ask(&world.helpers[0], "recovery.circleAsks", json!({})); let code = help_code(&world, 0).expect("a code"); ask(&world.helpers[0], "recovery.circleAsks", json!({})); let wrong = if code == "000 000" { "111111" } else { "000000" }; for expected in ["help_wrong_code", "help_wrong_code", "help_wrong_ended"] { let refused = call(&world.helpers[0], "recovery.circleApprove", &json!({ "request": "req-1", "account": "p-owner", "code": wrong, "privateKey": lent() })).unwrap_err(); assert_eq!(refused.code, expected); } let net = world.net.lock().unwrap(); assert_eq!(net.stopped_for, vec![0], "only this helper's part"); assert!(!net.stopped, "the request goes on with the others"); drop(net); world.net.lock().unwrap().fresh_device = true; // The status shows no helper's name or number on a fresh device until the screen lock, and says so. let status = crate::phone::recovery::call_on(&world.fresh, "recovery.status", &json!({})).unwrap(); assert!(status["circle"]["screenLock"]["line"].as_str().is_some(), "{status}"); assert!(!status["circle"].to_string().contains(HELPERS[0]) && !status["circle"].to_string().contains("Helper 0"), "{status}"); let unlocked = crate::phone::recovery::call_on(&world.fresh, "recovery.status", &json!({ "privateKey": fresh_key() })).unwrap(); assert!(unlocked["circle"]["screenLock"].is_null(), "{unlocked}"); assert!(unlocked["circle"]["line"].as_str().unwrap_or_default().contains("Helper 0"), "{unlocked}"); assert_eq!(call(&world.fresh, "recovery.circleStop", &json!({})).unwrap_err().code, "screen_lock_needed"); assert!(!world.net.lock().unwrap().stopped); let stopped = ask(&world.fresh, "recovery.circleStop", json!({ "privateKey": fresh_key() })); assert_eq!(stopped["stopped"], json!(true));}fn screen(client: &ClientController, request: Value) -> Value { crate::phone::recovery_screens::call(client, "recovery.screen", &request).unwrap_or_else(|error| panic!("recovery.screen {request}: {} {}", error.code, error.message))}/// RULE (TRUSTED RECOVERY on main, 28 Nov 2026): each screen comes whole from the core, words and acts, so a shell/// draws it and writes nothing: choose who helps (A), being asked (B), no other device (C), waiting (D), helping (E),/// stop (F) and back in (G).#[test]fn each_screen_is_drawn_whole_from_the_core() { let world = world(); // A: before any circle, the choice: 2 of 3 first and recommended, then 1 person, and the act that asks them. let a = screen(&world.owner, json!({ "screen": "circle", "privateKey": lent() })); assert_eq!(a["heading"], json!("Getting back in")); assert_eq!(a["choices"][0], json!({ "id": "two_of_three", "k": 2, "n": 3, "label": "Any 2 of 3", "note": "recommended", "default": true })); assert_eq!(a["choices"][1]["id"], json!("one")); assert_eq!(a["act"], json!("recovery.circleSet")); assert!(a["why"].as_str().unwrap().contains("nobody can alone"), "{a}"); ask(&world.owner, "recovery.circleSet", json!({ "numbers": HELPERS, "names": ["Asha", "Vikram", "Neha"], "privateKey": lent() })); // B: each helper is asked, by name, with the act to accept or decline. let b = screen(&world.helpers[0], json!({ "screen": "help" })); assert_eq!(b["asked"].as_array().unwrap().len(), 1, "{b}"); assert!(b["asked"][0]["title"].as_str().unwrap().ends_with("asks for your help"), "{b}"); assert_eq!((b["asked"][0]["acceptAct"].clone(), b["asked"][0]["declineAct"].clone()), (json!("recovery.circleAccept"), json!("recovery.circleDecline"))); for helper in &world.helpers { let held = ask(helper, "recovery.circleHeld", json!({})); let entry = &held["held"][0]; ask(helper, "recovery.circleAccept", json!({ "account": entry["account"], "setup": entry["setup"] })); } let accepted = screen(&world.helpers[0], json!({ "screen": "help" })); assert_eq!((accepted["asked"].as_array().unwrap().len(), accepted["helping"].as_array().unwrap().len()), (0, 1), "{accepted}"); // A's line now says who helps. let a = screen(&world.owner, json!({ "screen": "circle", "privateKey": lent() })); assert!(a["now"].as_str().is_some_and(|l| l.contains("can help you get back in")), "{a}"); // C: a new phone with no other device chooses; without its key behind the lock, only the choice. let c = screen(&world.fresh, json!({ "screen": "back" })); assert_eq!(c["state"], json!("choose")); assert_eq!(c["options"].as_array().unwrap().iter().map(|o| o["act"].clone()).collect::<Vec<_>>(), vec![json!("recovery.open"), json!("recovery.circleStart")]); ask(&world.fresh, "recovery.circleStart", json!({ "privateKey": fresh_key(), "name": "Pixel walk" })); // D: waiting, each helper named, and everyone told. let d = screen(&world.fresh, json!({ "screen": "back", "privateKey": fresh_key() })); assert_eq!(d["state"], json!("waiting"), "{d}"); assert_eq!(d["helpers"].as_array().unwrap().len(), 3); assert!(d["told"].as_str().unwrap().contains("can stop it")); // E: the helper's card, with its three steps and the acts. let e = screen(&world.helpers[0], json!({ "screen": "help" })); let card = &e["asks"][0]; assert!(card["title"].as_str().unwrap().ends_with("is trying to get back in"), "{e}"); assert_eq!(card["steps"].as_array().unwrap().len(), 3); assert_eq!((card["approveAct"].clone(), card["stopAct"].clone()), (json!("recovery.circleApprove"), json!("recovery.circleStopFor"))); // F: the stand-in holds no request on the person's status: nothing to stop is drawn as nothing. assert_eq!(screen(&world.owner, json!({ "screen": "stop", "privateKey": lent() })), json!({ "show": false })); // G: two help, the wait ends, the object releases its half: opened, with Choose again opening A. help(&world, 0, None).expect("helper 0 helps"); help(&world, 1, None).expect("helper 1 helps"); for (i, clock) in world.helper_clocks.iter().enumerate().take(2) { clock.set(chrono::DateTime::from_timestamp_millis(ENDS + 60_000).unwrap()); ask(&world.helpers[i], "recovery.circleAsks", json!({})); } world.net.lock().unwrap().released = true; let g = screen(&world.fresh, json!({ "screen": "back", "privateKey": fresh_key(), "name": "Pixel walk" })); assert_eq!(g["state"], json!("opened"), "{g}"); assert_eq!((g["again"].clone(), g["actScreen"].clone()), (json!("Choose again"), json!("circle"))); assert_eq!(crate::phone::recovery_screens::call(&world.fresh, "recovery.screen", &json!({ "screen": "nope" })).expect_err("no such screen").code, "bad_screen");}