//! `recovery.*` over real attached copies and a scripted object, which hands //! the second device back exactly what the first one set. Synthetic keys only. use std::sync::Arc; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use cotton_client::transport::scripted::Reply; use cotton_core::vault::wrap; use super::call_on; use crate::phone::unlock::tests::{device_secret, door, exec, fixture_vmk, wrapped}; use crate::shell::client::phone_tests::attached_on_a_clock; use crate::shell::client::ClientController; pub(crate) fn other_secret() -> [u8; 32] { [77; 32] } fn body(seen: &cotton_client::transport::scripted::Seen) -> Value { serde_json::from_slice(&seen.body).expect("a JSON body") } /// A new device's copy: the vault's state and data key row as a pull lays them, its own key published, no wrap. pub(crate) fn newcomer(client: &ClientController) { let now = "2026-11-11T08:00:00.000Z"; let ws = client.with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap(); exec(client, "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at) VALUES (?, 1, ?, ?, ?)", &[&ws, now, now, now]); let device = client.self_device_id().expect("a device id"); let public = URL_SAFE_NO_PAD.encode(wrap::public_of(&other_secret())); exec( client, "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at) VALUES ('vk-new', ?, ?, ?, NULL, 0, ?, ?)", &[&ws, &device, &public, now, now], ); let (_dk, row) = cotton_client::seal::mint_data_key(&fixture_vmk(), 1, now).unwrap(); let file = rusqlite::Connection::open(client.layout().replica(&client.current_database().unwrap())).unwrap(); cotton_client::seal::write_notes(&file, &[cotton_client::seal::Note::Key { id: "dk".into(), data: row }]).unwrap(); } /// RULE (R7c): a code is made on a device that holds the vault and sent only as a salt, a stretch, /// an auth hash, a wrap and the code sealed under the vault key; it is shown again from that device; and typed on a /// new device (any case, spaced) it opens the vault there: the device wraps the vault key for itself and takes the /// data key. A typo is refused before anything is sent. #[test] fn a_code_is_made_shown_again_and_opens_a_new_device() { let (_a_dir, holder, _a_clock) = attached_on_a_clock(); wrapped(&holder); // The first open of the vault in a process declares this device's key identity (vault_carry::declare, KEPT FOUR): // done here, on a door of its own, so the scripted door after sees only the calls the test is about. let (first, _) = door([Reply::ok(r#"{"ok":true}"#)]); holder.set_object_door(Some(Arc::new(first))); let _ = crate::phone::vault::opened_vmk(&holder, &device_secret()); let (object, exchange) = door([Reply::ok(r#"{"kind":"code","created_at":"2026-11-15T10:00:00.000Z"}"#)]); holder.set_object_door(Some(Arc::new(object))); let private = URL_SAFE_NO_PAD.encode(device_secret()); let made = call_on(&holder, "recovery.make", &json!({ "privateKey": private })).expect("made"); let code = made["code"].as_str().expect("a code").to_string(); assert_eq!(code.len(), 29, "six groups of four and five dashes: {code}"); let set = exchange.only(); assert_eq!((set.method.as_str(), set.path.as_str()), ("POST", "/v1/recovery/set?flow=2")); let sent = body(&set); let text = sent.to_string(); assert!(!text.contains(&code) && !text.contains(&code.replace('-', "")), "the code never goes in the clear"); assert!(!text.contains(&URL_SAFE_NO_PAD.encode(fixture_vmk().expose())), "nor the vault key"); assert_eq!(sent["kind"], json!("code")); assert_eq!(sent["kdf"], json!("scrypt:15:8:1")); assert_eq!(sent["vmk_version"], json!(1)); assert!(sent["auth_hash"].as_str().unwrap().len() == 64); assert!(sent["wrapped"].as_str().unwrap().starts_with("r1:")); assert!(sent["code_enc"].as_str().unwrap().starts_with("v2:") || sent["code_enc"].is_string()); // Shown again on the device that holds the vault, from what the object keeps. let held = json!({ "code": { "salt": sent["salt"], "kdf": sent["kdf"], "vmk_version": 1, "created_at": "2026-11-15T10:00:00.000Z", "code_enc": sent["code_enc"] }, "google": null, "apple": null }); let (object, _) = door([Reply::ok(&held.to_string())]); holder.set_object_door(Some(Arc::new(object))); assert_eq!(call_on(&holder, "recovery.show", &json!({ "privateKey": private })).expect("shown")["code"], json!(code)); // A new device, no other device at hand. let (_b_dir, fresh, _b_clock) = attached_on_a_clock(); newcomer(&fresh); let opened_answer = json!({ "wrapped": sent["wrapped"], "vmk_version": 1 }); let (object, exchange) = door([Reply::ok(&held.to_string()), Reply::ok(&opened_answer.to_string())]); fresh.set_object_door(Some(Arc::new(object))); let mut typo = code.clone().into_bytes(); typo[2] = if typo[2] == b'7' { b'8' } else { b'7' }; let refused = call_on(&fresh, "recovery.open", &json!({ "code": String::from_utf8(typo).unwrap(), "privateKey": URL_SAFE_NO_PAD.encode(other_secret()) })).unwrap_err(); assert_eq!(refused.code, "recovery_code_check", "{}", refused.message); assert_eq!(exchange.calls(), 0, "a typo spends no try"); let spoken = code.to_lowercase().replace('-', " "); let opened = call_on(&fresh, "recovery.open", &json!({ "code": spoken, "privateKey": URL_SAFE_NO_PAD.encode(other_secret()), "name": "Pixel walk" })).expect("opened"); assert_eq!(opened["opened"], json!(true)); let open = exchange.nth(1); assert_eq!(open.path, "/v1/recovery/open?flow=2"); let auth = URL_SAFE_NO_PAD.decode(body(&open)["auth"].as_str().unwrap()).unwrap(); let hash: String = Sha256::digest(&auth).iter().map(|b| format!("{b:02x}")).collect(); assert_eq!(hash, sent["auth_hash"].as_str().unwrap(), "the object can check the auth key against the hash it keeps"); // Its own row now holds a wrap of the vault key under its own key, and it holds the data key. let own: String = fresh .with_file(|replica| Ok(replica.driver.get("SELECT wrapped_vmk FROM cotton_vault_keys WHERE id = 'vk-new'", &[]).unwrap().and_then(|row| row.text("wrapped_vmk").map(str::to_string)).unwrap_or_default())) .unwrap(); assert_eq!(wrap::unwrap(&other_secret(), &own).as_deref(), Some(&fixture_vmk().expose()[..])); use cotton_client::seal::DataKeyStore as _; assert!(fresh.data_keys().data_key(&fresh.current_database().unwrap()).unwrap().is_some(), "the data key taken"); assert!(fresh.vault().unwrap().until(fresh.now()).is_some(), "and the vault open"); } /// RULE: a wrong code and a wait are said in the kit's plain words, with the tries left and the minutes. #[test] fn a_wrong_code_and_a_wait_are_said_plainly() { let (_dir, fresh, _clock) = attached_on_a_clock(); newcomer(&fresh); let held = json!({ "code": { "salt": URL_SAFE_NO_PAD.encode([5u8; 16]), "kdf": "scrypt:15:8:1", "vmk_version": 1, "created_at": "2026-11-15T10:00:00.000Z" }, "google": null, "apple": null }).to_string(); let (object, _) = door([ Reply::ok(&held), Reply::json(403, r#"{"code":"recovery_wrong","message":"That code does not open this account.","tries_left":3}"#), Reply::ok(&held), Reply::json(429, r#"{"code":"recovery_wait","message":"Too many tries.","retry_after":2950}"#), ]); fresh.set_object_door(Some(Arc::new(object))); let code = cotton_core::vault::recovery_code::mint_with(&[1; 14]); let args = json!({ "code": code, "privateKey": URL_SAFE_NO_PAD.encode(other_secret()) }); let wrong = call_on(&fresh, "recovery.open", &args).unwrap_err(); assert_eq!((wrong.code.as_str(), wrong.message.as_str()), ("recovery_wrong", "That code does not open this account. 3 more tries before a wait.")); let wait = call_on(&fresh, "recovery.open", &args).unwrap_err(); assert_eq!((wait.code.as_str(), wait.message.as_str()), ("recovery_wait", "Too many tries. Try again in 50 minutes.")); } /// RULE (R7, the honest line): a device holding the vault alone, with no code and no platform copy, is `alone`; the /// offer stands while no code is set; a platform copy or a code ends both. #[test] fn the_status_says_offer_and_alone_from_what_is_held() { let (_dir, holder, _clock) = attached_on_a_clock(); wrapped(&holder); let none = json!({ "code": null, "google": null, "apple": null }).to_string(); let google = json!({ "code": null, "google": { "salt": "AAAAAAAAAAAAAAAAAAAAAA", "kdf": "none", "vmk_version": 1, "created_at": "2026-11-15T10:00:00.000Z" }, "apple": null }).to_string(); let (object, _) = door([Reply::ok(&none), Reply::ok(&google)]); holder.set_object_door(Some(Arc::new(object))); let alone = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!((alone["holdsVault"].clone(), alone["offer"].clone(), alone["alone"].clone()), (json!(true), json!(true), json!(true))); assert_eq!(alone["lines"]["haveCode"], json!("I have a code")); let kept = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!((kept["offer"].clone(), kept["alone"].clone()), (json!(true), json!(false)), "a Google copy is a way back in"); assert_eq!(kept["google"]["current"], json!(true)); } /// Seen on emulator-5554 (22 Nov 2026, Comms on an invented account): the You page said "Recovery code made /// 2026-11-22". A copy's day is said in the reader's words, the year only outside theirs. #[test] fn the_day_a_copy_was_made_is_said_in_words() { let (_dir, holder, _clock) = attached_on_a_clock(); wrapped(&holder); let made = |at: &str| json!({ "code": { "salt": "AAAAAAAAAAAAAAAAAAAAAA", "kdf": "scrypt:15:8:1", "vmk_version": 1, "created_at": at }, "google": null, "apple": null }).to_string(); let (object, _) = door([Reply::ok(&made("2026-08-15T10:00:00.000Z")), Reply::ok(&made("2025-11-18T10:00:00.000Z"))]); holder.set_object_door(Some(Arc::new(object))); let this_year = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!(this_year["code"]["line"], json!("Recovery code made 15 August.")); let last_year = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!(last_year["code"]["line"], json!("Recovery code made 18 November 2025.")); } /// RULE (the honest line at first sign-in): a platform copy is a way back only where it comes back. /// A phone whose own store kept it here alone (no screen lock: Block Store backs nothing up) or kept nothing is /// `alone` though the object holds a row for that store, and `away` says once why and offers the code; a phone whose /// copy comes back says nothing; a phone that says nothing of its store is read from the object's rows, as before. #[test] fn a_copy_that_will_not_come_back_is_said_once_with_the_code() { let (_dir, holder, _clock) = attached_on_a_clock(); wrapped(&holder); let google = json!({ "code": null, "google": { "salt": "AAAAAAAAAAAAAAAAAAAAAA", "kdf": "none", "vmk_version": 1, "created_at": "2026-11-15T10:00:00.000Z" }, "apple": null }).to_string(); let (object, _) = door([Reply::ok(&google), Reply::ok(&google), Reply::ok(&google), Reply::ok(&google)]); holder.set_object_door(Some(Arc::new(object))); let no_lock = call_on(&holder, "recovery.status", &json!({ "copy": "here", "why": "no_lock" })).unwrap(); assert_eq!((no_lock["offer"].clone(), no_lock["alone"].clone()), (json!(true), json!(true)), "a copy kept here alone is no way back"); assert!(no_lock["away"].as_str().unwrap().starts_with("This phone has no screen lock"), "{}", no_lock["away"]); assert_eq!(no_lock["copyBack"], json!(false)); let refused = call_on(&holder, "recovery.status", &json!({ "copy": "none" })).unwrap(); assert!(refused["away"].as_str().unwrap().starts_with("This phone couldn't keep a copy"), "{}", refused["away"]); let back = call_on(&holder, "recovery.status", &json!({ "copy": "back" })).unwrap(); assert_eq!((back["alone"].clone(), back["away"].clone()), (json!(false), Value::Null)); let unsaid = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!((unsaid["alone"].clone(), unsaid["away"].clone()), (json!(false), Value::Null), "the object's row stands"); } /// RULE (GETTING-IN.md, 22 Nov 2026, the owner agreeing; it replaces the ruling of 16 Nov that removed Save): the code /// is offered to save in one tap, into the phone's password manager or Files, with one reminder a week after Not now, /// and Make a new code is asked first; Copy stays. #[test] fn the_code_offers_saving_with_passwords_or_files_and_one_reminder() { let (_dir, holder, _clock) = attached_on_a_clock(); wrapped(&holder); let status = call_on(&holder, "recovery.status", &json!({})).unwrap(); let lines = &status["lines"]; assert!(lines["copy"].is_string() && lines["makeNew"].is_string(), "{lines}"); assert_eq!(lines["offerHeading"], "Save your recovery code"); assert_eq!(lines["savePasswords"], "Save with my passwords"); assert_eq!(lines["saveFiles"], "Save to Files"); assert_eq!(lines["offer"], "Keep this code somewhere safe. You'll need it only if you ever lose every device."); assert_eq!(lines["reminder"], "You haven't saved your recovery code yet. You'll need it only if you ever lose every device. We won't remind you again."); assert_eq!(lines["makeNewConfirm"], "Make a new recovery code? Your old code will stop working."); assert!(lines["fileText"].as_str().unwrap().contains("{code}"), "the shell fills the code in: {lines}"); for word in ["records", "vault", "let in"] { assert!(!lines.to_string().contains(word), "the recovery words never say {word:?}: {lines}"); } } /// RULE: recovery.check catches a typo on the device, in words. #[test] fn a_typed_code_is_checked_on_the_device() { let (_dir, client, _clock) = attached_on_a_clock(); let code = cotton_core::vault::recovery_code::mint_with(&[9; 14]); assert_eq!(call_on(&client, "recovery.check", &json!({ "code": code })).unwrap(), json!({ "ok": true })); let short = call_on(&client, "recovery.check", &json!({ "code": &code[..10] })).unwrap(); assert_eq!(short["line"], json!("A recovery code is 24 characters, in six groups of four.")); } /// RULE (R7a): a platform key is made on a device holding the vault, handed to the shell to keep in the platform's /// store, set with no stretch, and opens a new device the same way. #[test] fn a_platform_key_is_made_and_opens_a_new_device() { let (_a_dir, holder, _a_clock) = attached_on_a_clock(); wrapped(&holder); let (object, exchange) = door([Reply::ok(r#"{"kind":"google","created_at":"2026-11-15T10:00:00.000Z"}"#)]); holder.set_object_door(Some(Arc::new(object))); let made = call_on(&holder, "recovery.makePlatform", &json!({ "store": "google", "privateKey": URL_SAFE_NO_PAD.encode(device_secret()) })).expect("made"); let key = made["key"].as_str().unwrap().to_string(); let sent = body(&exchange.only()); assert_eq!((sent["kind"].clone(), sent["kdf"].clone()), (json!("google"), json!("none"))); assert!(!sent.to_string().contains(&key), "the key itself stays on the device and in its store"); let (_b_dir, fresh, _b_clock) = attached_on_a_clock(); newcomer(&fresh); let held = json!({ "code": null, "apple": null, "google": { "salt": sent["salt"], "kdf": "none", "vmk_version": 1, "created_at": "2026-11-15T10:00:00.000Z" } }); let (object, _) = door([Reply::ok(&held.to_string()), Reply::ok(&json!({ "wrapped": sent["wrapped"], "vmk_version": 1 }).to_string())]); fresh.set_object_door(Some(Arc::new(object))); let opened = call_on(&fresh, "recovery.openPlatform", &json!({ "store": "google", "key": key, "privateKey": URL_SAFE_NO_PAD.encode(other_secret()) })).expect("opened"); assert_eq!(opened["line"], json!("Opened with the copy your Google account keeps.")); } /// A copy holding its own data key (as a phone that reads its sealed tables does): its sharing key is derived from it. pub(crate) fn holding_a_data_key(client: &ClientController) -> cotton_core::seal::DataKey { let (dk, _row) = cotton_client::seal::mint_data_key(&fixture_vmk(), 1, "2026-11-11T08:00:00.000Z").unwrap(); client.data_keys().hold(&client.current_database().unwrap(), &dk); dk } /// The helper's own Secrets notes as its object answers them: one pin per person it checked (S1), each the number and /// the sharing key it checked, sealed to the helper's own key as Secrets keeps them. pub(crate) fn pins_reply(helper: &ClientController, pins: &[(&str, [u8; 32])]) -> String { use cotton_core::seal::share::{key_text, seal_to_person}; // Secrets posts the phone's sharing key once a launch: done here, on a door of its own, so the scripted doors after // see only the calls the test is about. let (object, _) = door([Reply::ok(r#"{"ok":true}"#)]); helper.set_object_door(Some(Arc::new(object))); let (secret, public) = crate::phone::secrets_app::me(helper).expect("the helper's own key"); let notes: Vec = pins .iter() .map(|(number, key)| { let slot = crate::phone::secrets_app::pin_key(number); let pin = json!({ "number": number, "key": key_text(key), "checked_at": 1 }); let boxed = seal_to_person(&secret, &public, &crate::phone::secrets_app::note_context(&slot), &serde_json::to_vec(&pin).unwrap()).unwrap(); json!({ "key": slot, "box": boxed }) }) .collect(); json!({ "notes": notes }).to_string() } /// A helper's copy: its own data key (its sharing key comes from it) and a vault it holds, so the device unlock opens. fn helper_copy() -> (tempfile::TempDir, Arc, [u8; 32], Arc) { use cotton_core::seal::share::sharing_secret; let (dir, helper, clock) = attached_on_a_clock(); wrapped(&helper); let h_dk = holding_a_data_key(&helper); let h_secret = sharing_secret(&h_dk, &helper.current_database().unwrap()).unwrap(); (dir, helper, *h_secret, clock) } const UNLOCK: fn() -> String = || URL_SAFE_NO_PAD.encode(device_secret()); /// RULE (R7d): the owner's phone splits a secret, seals the helper's half to the helper's sharing /// key and sends the object only its own half; the helper's phone opens that half and wraps it to the new device's /// vault key alone; the new device joins the halves and opens the vault. Real keys on three copies; the objects are /// scripted with exactly what each side posted. #[test] fn a_trusted_person_helps_a_new_device_in_and_reads_nothing() { use cotton_core::seal::share::key_text; const OWNER: &str = "+919000000009"; const HELPER: &str = "+919000000077"; // The helper's copy and sharing key. let (_h_dir, helper, h_secret, _h_clock) = helper_copy(); let h_public = key_text(&wrap::public_of(&h_secret)); // The owner trusts them. let (_o_dir, owner, _o_clock) = attached_on_a_clock(); wrapped(&owner); holding_a_data_key(&owner); let owner_key = wrap::public_of(&crate::phone::send_seal::sharing(&owner).unwrap().0); let (object, exchange) = door([ Reply::ok(&json!({ "key": h_public, "me": OWNER }).to_string()), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"kind":"trusted","created_at":"2026-11-16T01:00:00.000Z"}"#), ]); owner.set_object_door(Some(Arc::new(object))); let trusted = call_on(&owner, "recovery.trust", &json!({ "number": HELPER, "privateKey": URL_SAFE_NO_PAD.encode(device_secret()) })).expect("trusted"); assert_eq!(trusted["trusted"], json!(true)); let set = body(&exchange.nth(2)); assert_eq!(exchange.nth(2).path, "/v1/recovery/set?flow=2"); assert_eq!((set["kind"].clone(), set["helper"].clone(), set["kdf"].clone()), (json!("trusted"), json!(HELPER), json!("none"))); let share = set["share"].as_str().unwrap().to_string(); let sealed_half = set["box"].as_str().unwrap().to_string(); assert!(sealed_half.starts_with("p1:")); let pins = pins_reply(&helper, &[(OWNER, owner_key)]); // A new device of the owner asks for help. let (_n_dir, fresh, _n_clock) = attached_on_a_clock(); newcomer(&fresh); crate::phone::cotton_chat::remember_number(&fresh, OWNER); let (object, exchange) = door([Reply::ok(r#"{"id":"x","name":"Helper Walk"}"#)]); fresh.set_object_door(Some(Arc::new(object))); let n_private = URL_SAFE_NO_PAD.encode(other_secret()); let asked = call_on(&fresh, "recovery.askHelp", &json!({ "privateKey": n_private, "name": "Pixel walk" })).expect("asked"); assert_eq!(asked["line"], json!("Asked Helper Walk. Once they approve on their phone, this one opens.")); assert_eq!(exchange.only().path, "/v1/recovery/help/ask?flow=2"); let ask = body(&exchange.only()); let device_key = URL_SAFE_NO_PAD.encode(wrap::public_of(&other_secret())); assert_eq!(ask["device_key"], json!(device_key)); let commit = ask["commit"].as_str().unwrap().to_string(); let id = ask["id"].as_str().expect("the device mints the ask's id").to_string(); // The helper's phone opens the ask with its nonce; the new device reveals and shows the code; the helper types it. let listed = json!({ "asks": [{ "id": id, "peer": OWNER, "device_key": device_key, "commit": commit, "box": sealed_half }] }).to_string(); let (object, exchange) = door([Reply::ok(&listed), Reply::ok(&pins), Reply::ok(r#"{"ok":true}"#)]); helper.set_object_door(Some(Arc::new(object))); let asks = call_on(&helper, "recovery.helpAsks", &json!({})).expect("asks"); assert_eq!(asks["asks"][0]["line"], json!(format!("{OWNER} asks for your help to get back in. Talk to them in person, or on a call where you know their voice. Their new device will show a code for you to type here."))); assert_eq!(exchange.nth(2).path, "/v1/recovery/help/open?flow=2"); let nonce_b = body(&exchange.nth(2))["nonce"].as_str().unwrap().to_string(); let (object, exchange) = door([Reply::ok(&json!({ "state": "opened", "name": "Helper Walk", "nonce_b": nonce_b }).to_string()), Reply::ok(r#"{"ok":true}"#)]); fresh.set_object_door(Some(Arc::new(object))); let shown = call_on(&fresh, "recovery.helped", &json!({ "privateKey": n_private })).expect("compare"); let nonce_a = body(&exchange.nth(1))["nonce"].as_str().unwrap().to_string(); let typed = shown["code"].as_str().unwrap().to_string(); assert_eq!(shown["line"], json!(format!("When Helper Walk calls, read them this code: {typed}"))); let listed = json!({ "asks": [{ "id": id, "peer": OWNER, "device_key": device_key, "commit": commit, "nonce_b": nonce_b, "reveal": nonce_a, "box": sealed_half }] }).to_string(); let (object, exchange) = door([Reply::ok(&listed), Reply::ok(&pins), Reply::ok(&listed), Reply::ok(&pins), Reply::ok(r#"{"ok":true}"#)]); helper.set_object_door(Some(Arc::new(object))); let asks = call_on(&helper, "recovery.helpAsks", &json!({})).expect("asks"); assert_eq!(asks["asks"][0]["phase"], json!("compare")); // The device unlock first: a screen that is on is not enough. assert_eq!(call_on(&helper, "recovery.helpApprove", &json!({ "id": id, "code": typed })).unwrap_err().code, "device_unlock_needed"); call_on(&helper, "recovery.helpApprove", &json!({ "id": id, "code": typed, "privateKey": UNLOCK() })).expect("approved"); let answer = body(&exchange.nth(4)); let for_device = answer["sealed"].as_str().unwrap().to_string(); // What the helper sent opens only under the new device's key, and is only their half: with it alone the wrap // the owner set does not open. let half = wrap::unwrap(&other_secret(), &for_device).expect("opens for the device"); assert!(wrap::unwrap(&device_secret(), &for_device).is_none(), "not for any other key"); let salt = URL_SAFE_NO_PAD.decode(set["salt"].as_str().unwrap()).unwrap(); use cotton_core::vault::recovery_code as rc; let alone = rc::derive(&half, &salt, rc::Kdf::None).unwrap(); assert!(rc::unwrap(&alone.wrap, rc::Kind::Trusted, 1, set["wrapped"].as_str().unwrap()).is_none(), "the helper's half alone opens nothing"); let held_alone = rc::derive(&URL_SAFE_NO_PAD.decode(&share).unwrap(), &salt, rc::Kdf::None).unwrap(); assert!(rc::unwrap(&held_alone.wrap, rc::Kind::Trusted, 1, set["wrapped"].as_str().unwrap()).is_none(), "nor the object's"); // The new device, once approved, joins both halves and opens. let approved = json!({ "state": "approved", "name": "Helper Walk", "sealed": for_device, "share": share }).to_string(); let held = json!({ "code": null, "google": null, "apple": null, "trusted": { "salt": set["salt"], "kdf": "none", "vmk_version": 1, "created_at": "2026-11-16T01:00:00.000Z", "helper": HELPER, "helper_name": "Helper Walk" } }).to_string(); let (object, exchange) = door([Reply::ok(r#"{"state":"asked","name":"Helper Walk"}"#), Reply::ok(&approved), Reply::ok(&held), Reply::ok(&json!({ "wrapped": set["wrapped"], "vmk_version": 1 }).to_string())]); fresh.set_object_door(Some(Arc::new(object))); assert_eq!(call_on(&fresh, "recovery.helped", &json!({ "privateKey": n_private })).unwrap(), json!({ "opened": false, "state": "asked" })); let opened = call_on(&fresh, "recovery.helped", &json!({ "privateKey": n_private, "name": "Pixel walk" })).expect("opened"); assert_eq!(opened["line"], json!("Opened with Helper Walk's help.")); let auth = URL_SAFE_NO_PAD.decode(body(&exchange.nth(3))["auth"].as_str().unwrap()).unwrap(); let hash: String = Sha256::digest(&auth).iter().map(|b| format!("{b:02x}")).collect(); assert_eq!(hash, set["auth_hash"].as_str().unwrap()); use cotton_client::seal::DataKeyStore as _; assert!(fresh.data_keys().data_key(&fresh.current_database().unwrap()).unwrap().is_some(), "the data key taken"); } /// The trusted-person scene the review's tests share: a helper's copy, a half kept for OWNER sealed by OWNER's key, the /// helper's pin of OWNER (and of anyone else given), and a new device of OWNER that asked and revealed. struct Scene { helper: Arc, sealed_half: String, pins: String, device_key: String, commit: String, id: String, nonce_b: String, nonce_a: String, code: String, _keep: Vec>, } const OWNER: &str = "+919000000009"; const OTHER: &str = "+919000000044"; const O_SECRET: [u8; 32] = [55u8; 32]; const P_SECRET: [u8; 32] = [56u8; 32]; const HALF: [u8; 32] = [66u8; 32]; fn listed_one(id: &str, peer: &str, device_key: &str, commit: &str, sealed: &str, extra: Value) -> String { let mut one = json!({ "id": id, "peer": peer, "device_key": device_key, "commit": commit, "box": sealed }); one.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); json!({ "asks": [one] }).to_string() } fn scene() -> Scene { use cotton_core::seal::share::seal_to_person; use cotton_core::vault::recovery_code as rc; let (h_dir, helper, h_secret, h_clock) = helper_copy(); let sealed_half = seal_to_person(&O_SECRET, &wrap::public_of(&h_secret), &rc::help_context(OWNER), &HALF).unwrap(); let pins = pins_reply(&helper, &[(OWNER, wrap::public_of(&O_SECRET)), (OTHER, wrap::public_of(&P_SECRET))]); let (n_dir, fresh, n_clock) = attached_on_a_clock(); newcomer(&fresh); crate::phone::cotton_chat::remember_number(&fresh, OWNER); let n_private = URL_SAFE_NO_PAD.encode(other_secret()); let device_key = URL_SAFE_NO_PAD.encode(wrap::public_of(&other_secret())); let (object, exchange) = door([Reply::ok(r#"{"id":"x","name":"Helper Walk"}"#)]); fresh.set_object_door(Some(Arc::new(object))); call_on(&fresh, "recovery.askHelp", &json!({ "privateKey": n_private, "name": "Pixel walk" })).expect("asked"); let ask = body(&exchange.only()); let commit = ask["commit"].as_str().unwrap().to_string(); let id = ask["id"].as_str().unwrap().to_string(); let (object, exchange) = door([Reply::ok(&listed_one(&id, OWNER, &device_key, &commit, &sealed_half, json!({}))), Reply::ok(&pins), Reply::ok(r#"{"ok":true}"#)]); helper.set_object_door(Some(Arc::new(object))); call_on(&helper, "recovery.helpAsks", &json!({})).expect("asks"); let nonce_b = body(&exchange.nth(2))["nonce"].as_str().unwrap().to_string(); let (object, exchange) = door([Reply::ok(&json!({ "state": "opened", "name": "Helper Walk", "nonce_b": nonce_b }).to_string()), Reply::ok(r#"{"ok":true}"#)]); fresh.set_object_door(Some(Arc::new(object))); let shown = call_on(&fresh, "recovery.helped", &json!({ "privateKey": n_private })).expect("compare"); let nonce_a = body(&exchange.nth(1))["nonce"].as_str().unwrap().to_string(); let code = shown["code"].as_str().unwrap().replace(' ', ""); Scene { helper, sealed_half, pins, device_key, commit, id, nonce_b, nonce_a, code, _keep: vec![Box::new(h_dir), Box::new(h_clock), Box::new(n_dir), Box::new(fresh), Box::new(n_clock)] } } impl Scene { /// helpApprove against what the server lists now: the answer, and how many answers were posted. fn approve(&self, typed: Option<&str>, list: &str) -> (Result, usize) { let (object, exchange) = door([Reply::ok(list), Reply::ok(&self.pins), Reply::ok(r#"{"ok":true}"#)]); self.helper.set_object_door(Some(Arc::new(object))); let mut request = json!({ "id": self.id, "privateKey": UNLOCK() }); if let Some(typed) = typed { request["code"] = json!(typed); } let answer = call_on(&self.helper, "recovery.helpApprove", &request); (answer, exchange.seen().iter().filter(|seen| seen.path == "/v1/recovery/help/answer?flow=2" && body(seen).get("sealed").is_some()).count()) } fn revealed(&self) -> String { listed_one(&self.id, OWNER, &self.device_key, &self.commit, &self.sealed_half, json!({ "nonce_b": self.nonce_b, "reveal": self.nonce_a })) } } /// RULE (TRUSTED RECOVERY BUILD 1, weakness 1): the helper's phone wraps its half only to the key the six digits vouch /// for, digits it works out itself from whose recovery it is, the device's key and both nonces, and only when the /// helper TYPES the digits the person reads from their new device. A key the server swaps in, before or after the /// helper's nonce, a commit it changes, or no code at all: nothing is wrapped and nothing is posted. #[test] fn a_helper_wraps_only_to_the_key_the_typed_code_vouches_for() { use cotton_core::vault::recovery_code as rc; let s = scene(); let decode = |t: &str| -> [u8; 32] { URL_SAFE_NO_PAD.decode(t).unwrap().try_into().unwrap() }; let at = rc::HelpFor { account: OWNER, setup: rc::TRUSTED_SETUP, index: 0, request: &s.id }; assert_eq!(rc::help_commit(&at, &decode(&s.device_key), &decode(&s.nonce_a)), decode(&s.commit), "the reveal is what it committed to"); assert_eq!(rc::help_sas(&at, &decode(&s.device_key), &decode(&s.nonce_a), &decode(&s.nonce_b)), s.code); // No code: refused, nothing posted. let (answer, posted) = s.approve(None, &s.revealed()); assert_eq!((answer.unwrap_err().code, posted), ("help_code_needed".to_string(), 0)); // A wrong code: refused, nothing posted. let wrong = if s.code == "000000" { "111111" } else { "000000" }; let (answer, posted) = s.approve(Some(wrong), &s.revealed()); assert_eq!((answer.unwrap_err().code, posted), ("help_wrong_code".to_string(), 0)); // The server swaps in a key of its own, with a commit and a reveal that fit it: refused, nothing wrapped. let server_secret = [99u8; 32]; let server_key = URL_SAFE_NO_PAD.encode(wrap::public_of(&server_secret)); let server_nonce = [7u8; 32]; let server_commit = URL_SAFE_NO_PAD.encode(rc::help_commit(&at, &decode(&server_key), &server_nonce)); let swapped = listed_one(&s.id, OWNER, &server_key, &server_commit, &s.sealed_half, json!({ "nonce_b": s.nonce_b, "reveal": URL_SAFE_NO_PAD.encode(server_nonce) })); let (answer, posted) = s.approve(Some(&s.code), &swapped); assert_eq!(posted, 0, "nothing wrapped to a swapped key: {answer:?}"); assert_eq!(answer.unwrap_err().code, "help_changed"); // A reveal that does not hash to the commit the helper saw: refused. let forged = listed_one(&s.id, OWNER, &s.device_key, &s.commit, &s.sealed_half, json!({ "nonce_b": s.nonce_b, "reveal": URL_SAFE_NO_PAD.encode([8u8; 32]) })); let (answer, posted) = s.approve(Some(&s.code), &forged); assert_eq!((answer.unwrap_err().code, posted), ("help_changed".to_string(), 0)); // The right code, the device's own key: the helper's half, wrapped to that key alone. let (answer, posted) = s.approve(Some(&format!("{} {}", &s.code[..3], &s.code[3..])), &s.revealed()); assert_eq!(answer.expect("approved")["approved"], json!(true)); assert_eq!(posted, 1); } /// RULE (TRUSTED RECOVERY BUILD 2, review M1): an ask is named by who sealed the half kept for it, as the helper's own /// pins and people list say, never by the server's label; and the digits bind whose recovery it is. A server that /// shows one person's ask under another's number finds a half that does not open there; one that shows an ask with /// a name of its choosing is overruled by the phone's own name; a half from nobody the helper checked is never approved. #[test] fn a_mislabelled_ask_is_named_by_the_helpers_own_pin_and_never_approved() { use cotton_core::seal::share::seal_to_person; let s = scene(); // OWNER's ask shown as OTHER's (OTHER is someone the helper checked too): the half does not open as OTHER's. let as_other = listed_one(&s.id, OTHER, &s.device_key, &s.commit, &s.sealed_half, json!({ "nonce_b": s.nonce_b, "reveal": s.nonce_a, "name": "Other Person" })); let (object, _) = door([Reply::ok(&as_other), Reply::ok(&s.pins)]); s.helper.set_object_door(Some(Arc::new(object))); let asks = call_on(&s.helper, "recovery.helpAsks", &json!({})).unwrap(); assert_eq!((asks["asks"][0]["phase"].clone(), asks["asks"][0]["name"].clone()), (json!("unknown"), json!("")), "{asks}"); // Offered: Secrets' check of the number it is said to be from (safe whoever it is: it pins only a key confirmed in person). assert_eq!((asks["asks"][0]["check"]["method"].clone(), asks["asks"][0]["check"]["number"].clone()), (json!("secrets.check"), json!(OTHER))); let (answer, posted) = s.approve(Some(&s.code), &as_other); assert_eq!((answer.unwrap_err().code, posted), ("help_not_checked".to_string(), 0)); // A name the server chose is never shown: the phone names OWNER as its own list does. let labelled = listed_one(&s.id, OWNER, &s.device_key, &s.commit, &s.sealed_half, json!({ "nonce_b": s.nonce_b, "reveal": s.nonce_a, "name": "Other Person" })); let (object, _) = door([Reply::ok(&labelled), Reply::ok(&s.pins)]); s.helper.set_object_door(Some(Arc::new(object))); let asks = call_on(&s.helper, "recovery.helpAsks", &json!({})).unwrap(); assert_eq!(asks["asks"][0]["name"], json!(OWNER), "{asks}"); // A half sealed by someone the helper never checked, under OWNER's number: never approved. let (mine, _) = crate::phone::send_seal::sharing(&s.helper).unwrap(); let stranger = seal_to_person(&[57u8; 32], &wrap::public_of(&mine), &cotton_core::vault::recovery_code::help_context(OWNER), &HALF).unwrap(); let from_stranger = listed_one(&s.id, OWNER, &s.device_key, &s.commit, &stranger, json!({ "nonce_b": s.nonce_b, "reveal": s.nonce_a })); let (answer, posted) = s.approve(Some(&s.code), &from_stranger); assert_eq!((answer.unwrap_err().code, posted), ("help_not_checked".to_string(), 0)); } /// RULE (TRUSTED RECOVERY BUILD 2, the review's missing tests): a server that makes the ask itself, with its own key /// from the start (its own commit, its own reveal, all consistent), gets nothing: the digits the person reads from /// their real new device are for another key, nonce and request, so the helper's typing them does not match. #[test] fn a_server_that_uses_its_own_key_from_the_start_gets_nothing() { use cotton_core::vault::recovery_code as rc; let s = scene(); let decode = |t: &str| -> [u8; 32] { URL_SAFE_NO_PAD.decode(t).unwrap().try_into().unwrap() }; let server_key = URL_SAFE_NO_PAD.encode(wrap::public_of(&[98u8; 32])); let server_nonce = [6u8; 32]; let fake_id = "ask-made-by-the-server-0001"; let at = rc::HelpFor { account: OWNER, setup: rc::TRUSTED_SETUP, index: 0, request: fake_id }; let server_commit = URL_SAFE_NO_PAD.encode(rc::help_commit(&at, &decode(&server_key), &server_nonce)); // The helper's phone opens the server's ask as any other. let fresh_list = listed_one(fake_id, OWNER, &server_key, &server_commit, &s.sealed_half, json!({})); let (object, exchange) = door([Reply::ok(&fresh_list), Reply::ok(&s.pins), Reply::ok(r#"{"ok":true}"#)]); s.helper.set_object_door(Some(Arc::new(object))); call_on(&s.helper, "recovery.helpAsks", &json!({})).unwrap(); let nonce_b = body(&exchange.nth(2))["nonce"].as_str().unwrap().to_string(); let revealed = listed_one(fake_id, OWNER, &server_key, &server_commit, &s.sealed_half, json!({ "nonce_b": nonce_b, "reveal": URL_SAFE_NO_PAD.encode(server_nonce) })); let (object, exchange) = door([Reply::ok(&revealed), Reply::ok(&s.pins), Reply::ok(r#"{"ok":true}"#)]); s.helper.set_object_door(Some(Arc::new(object))); // The person reads the code their real device shows. let answer = call_on(&s.helper, "recovery.helpApprove", &json!({ "id": fake_id, "code": s.code, "privateKey": UNLOCK() })); assert_eq!(answer.unwrap_err().code, "help_wrong_code"); assert!(exchange.seen().iter().all(|seen| body_or_null(seen).get("sealed").is_none()), "nothing wrapped for the server's key"); } fn body_or_null(seen: &cotton_client::transport::scripted::Seen) -> Value { serde_json::from_slice(&seen.body).unwrap_or(Value::Null) } /// RULE (TRUSTED RECOVERY BUILD 2, review LOW): a helper's phone takes at most three compares and three wrong codes a /// day for one person, however many asks the server makes: guessing through repeated compares stops there. #[test] fn guessing_through_repeated_compares_stops_at_three_a_day() { let s = scene(); // The scene opened one compare. Two more asks open; the fourth rests. let mut opened = 1; for i in 0..3 { let id = format!("ask-again-{i}-synthetic-id"); // The new ask listed beside the one still waiting. let mut both: Value = serde_json::from_str(&s.revealed()).unwrap(); let new_one: Value = serde_json::from_str(&listed_one(&id, OWNER, &s.device_key, &s.commit, &s.sealed_half, json!({}))).unwrap(); both["asks"].as_array_mut().unwrap().push(new_one["asks"][0].clone()); let (object, exchange) = door([Reply::ok(&both.to_string()), Reply::ok(&s.pins), Reply::ok(r#"{"ok":true}"#)]); s.helper.set_object_door(Some(Arc::new(object))); let asks = call_on(&s.helper, "recovery.helpAsks", &json!({})).unwrap(); if exchange.seen().iter().any(|seen| seen.path == "/v1/recovery/help/open?flow=2") { opened += 1; } else { assert_eq!(asks["asks"][1]["phase"], json!("resting"), "{asks}"); } } assert_eq!(opened, 3, "three compares a day for one person"); // Wrong codes: the third ends the ask, and the phone rests for that person. let wrong = if s.code == "000000" { "111111" } else { "000000" }; assert_eq!(s.approve(Some(wrong), &s.revealed()).0.unwrap_err().code, "help_wrong_code"); assert_eq!(s.approve(Some(wrong), &s.revealed()).0.unwrap_err().code, "help_wrong_code"); assert_eq!(s.approve(Some(wrong), &s.revealed()).0.unwrap_err().code, "help_wrong_ended"); let (answer, posted) = s.approve(Some(&s.code), &s.revealed()); assert_eq!((answer.unwrap_err().code, posted), ("help_resting".to_string(), 0), "not even the right code, until the day is over"); } /// RULE (TRUSTED RECOVERY BUILD 2, review H1): an ask from a device that runs an earlier build carries no commit; this /// build's helper phone says so in words and never approves it, whatever the server sends (no downgrade). #[test] fn a_new_helper_never_approves_an_earlier_builds_ask() { let s = scene(); let old = json!({ "asks": [{ "id": "ask-old-0001-synthetic", "peer": OWNER, "device_key": s.device_key, "flow": 1, "box": s.sealed_half }] }).to_string(); let (object, _) = door([Reply::ok(&old), Reply::ok(&s.pins)]); s.helper.set_object_door(Some(Arc::new(object))); let asks = call_on(&s.helper, "recovery.helpAsks", &json!({})).unwrap(); assert_eq!(asks["asks"][0]["phase"], json!("old_flow")); assert!(asks["asks"][0]["line"].as_str().unwrap().contains("older Cotton"), "{asks}"); let (object, exchange) = door([Reply::ok(&old), Reply::ok(&s.pins), Reply::ok(r#"{"ok":true}"#)]); s.helper.set_object_door(Some(Arc::new(object))); let answer = call_on(&s.helper, "recovery.helpApprove", &json!({ "id": "ask-old-0001-synthetic", "code": s.code, "privateKey": UNLOCK() })); assert_eq!(answer.unwrap_err().code, "help_old_flow"); assert!(exchange.seen().iter().all(|seen| body_or_null(seen).get("sealed").is_none())); // Even with a server that claims a compare on an ask with no commit. let claimed = json!({ "asks": [{ "id": "ask-old-0001-synthetic", "peer": OWNER, "device_key": s.device_key, "nonce_b": s.nonce_b, "reveal": s.nonce_a, "box": s.sealed_half }] }).to_string(); let (object, _) = door([Reply::ok(&claimed), Reply::ok(&s.pins), Reply::ok(r#"{"ok":true}"#)]); s.helper.set_object_door(Some(Arc::new(object))); let answer = call_on(&s.helper, "recovery.helpApprove", &json!({ "id": "ask-old-0001-synthetic", "code": s.code, "privateKey": UNLOCK() })); assert_eq!(answer.unwrap_err().code, "help_old_flow"); } /// RULE (TRUSTED RECOVERY BUILD 1, step 2): a helper who can help no more (they removed or blocked this person, or /// deleted their account) is said on the status in words, with no ask offered, and counts as no way back in. #[test] fn a_helper_who_has_gone_is_said_and_offers_no_ask() { let (_dir, holder, _clock) = attached_on_a_clock(); wrapped(&holder); let trusted = |gone: bool| { let mut entry = json!({ "salt": "AAAAAAAAAAAAAAAAAAAAAA", "kdf": "none", "vmk_version": 1, "created_at": "2026-11-15T10:00:00.000Z", "helper": "+919000000077", "helper_name": "Asha" }); if gone { entry["gone"] = json!(true); } json!({ "code": null, "google": null, "apple": null, "trusted": entry }).to_string() }; let (object, _) = door([Reply::ok(&trusted(false)), Reply::ok(&trusted(true))]); holder.set_object_door(Some(Arc::new(object))); let held = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!((held["trusted"]["line"].clone(), held["trusted"]["ask"].clone(), held["alone"].clone()), (json!("Asha can help you get back in."), json!("Ask Asha to help"), json!(false))); let gone = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!(gone["trusted"]["gone"], json!(true)); assert_eq!(gone["trusted"]["line"], json!("Asha can no longer help you get back in. Choose someone else.")); assert!(gone["trusted"]["ask"].is_null(), "no ask to someone who cannot answer: {gone}"); assert_eq!(gone["alone"], json!(true), "a helper who has gone is no way back in"); } /// RULE (TRUSTED RECOVERY BUILD 1, step 3): nothing rotates the vault key today (the rotation left with the Rust server, /// f1d43c1105), but a helper's wrap made under an earlier version than the vault's own is said as the code's is /// (`current: false`), offers no ask, and counts as no way back in: it would open a key the vault has moved past. #[test] fn a_helper_chosen_under_an_earlier_key_is_said_and_counts_for_nothing() { let (_dir, holder, _clock) = attached_on_a_clock(); wrapped(&holder); let ws = holder.with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap(); exec(&holder, "UPDATE cotton_vault_state SET vmk_version = 2 WHERE workspace_id = ?", &[&ws]); let held = json!({ "code": null, "google": null, "apple": null, "trusted": { "salt": "AAAAAAAAAAAAAAAAAAAAAA", "kdf": "none", "vmk_version": 1, "created_at": "2026-11-15T10:00:00.000Z", "helper": "+919000000077", "helper_name": "Asha" } }).to_string(); let (object, _) = door([Reply::ok(&held)]); holder.set_object_door(Some(Arc::new(object))); let status = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!(status["trusted"]["current"], json!(false), "{status}"); assert_eq!(status["trusted"]["line"], json!("Asha was chosen before your key changed. Choose them again.")); assert!(status["trusted"]["ask"].is_null()); assert_eq!(status["alone"], json!(true)); } /// RULE (TRUSTED RECOVERY BUILD 1, step 4): every device of the person shows the circle, who accepted, and a recovery /// under way in words with Stop; a live circle is a way back in. #[test] fn the_status_says_the_circle_and_a_recovery_under_way_with_stop() { let (_dir, holder, _clock) = attached_on_a_clock(); wrapped(&holder); let circle = |request: bool| { let mut entry = json!({ "salt": "AAAAAAAAAAAAAAAAAAAAAA", "kdf": "none", "vmk_version": 1, "created_at": "2026-11-15T10:00:00.000Z", "setup": "s1", "k": 2, "n": 3, "live": true, "members": [{ "index": 0, "name": "Asha", "state": "accepted" }, { "index": 1, "name": "Vikram", "state": "accepted" }, { "index": 2, "name": "Neha", "state": "asked" }] }); if request { entry["request"] = json!({ "id": "r1", "started_at": 1_764_000_000_000i64, "ends_at": 1_764_172_800_000i64, "name": "Pixel", "state": "waiting" }); } json!({ "code": null, "google": null, "apple": null, "trusted": null, "circle": entry }).to_string() }; let (object, _) = door([Reply::ok(&circle(false)), Reply::ok(&circle(true))]); holder.set_object_door(Some(Arc::new(object))); let quiet = call_on(&holder, "recovery.status", &json!({})).unwrap(); assert_eq!(quiet["circle"]["line"], json!("Asha and Vikram can help you get back in. Waiting for Neha to accept."), "{quiet}"); assert!(quiet["circle"]["request"].is_null()); assert_eq!(quiet["alone"], json!(false), "a live circle is a way back in"); let under_way = call_on(&holder, "recovery.status", &json!({})).unwrap(); let request = &under_way["circle"]["request"]; assert!(request["line"].as_str().unwrap().starts_with("Someone is getting into your Cotton on a new phone (Pixel). It opens "), "{request}"); assert_eq!(request["stop"], json!("Stop it")); }