Cotton code
632 lines · 39.5 KB · RustRaw
//! Cotton Vault's screens on a phone: the list, an item shut and open, a//! reveal, add and edit, the generator, Security, Settings and the acts, and//! the list's speed over 2,000 items. Every value is invented and none is//! printed: a failing assertion names the field, never the value.use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::phone::passwords::tests::{exec, lent, phone, row, wrapped};fn call(handle: &CottonHandle, method: &str, request: Value) -> Value {    super::call(&handle.client(), method, &request, None).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn refused(handle: &CottonHandle, method: &str, request: Value) -> String {    super::call(&handle.client(), method, &request, None).err().map(|error| error.code).unwrap_or_else(|| panic!("{method} answered"))}fn add(handle: &CottonHandle, mut request: Value) -> String {    request["privateKey"] = lent();    crate::phone::keys::over(&handle.client(), "keys.add", &request).expect("keys.add")["id"].as_str().unwrap().to_string()}fn login(handle: &CottonHandle, site: &str, user: &str, password: &str) -> String {    add(handle, json!({"kind": "login", "site": site, "username": user, "fields": {"password": password}}))}fn unlock(handle: &CottonHandle) {    crate::phone::vault::over(&handle.client(), "vault.unlock", &json!({"privateKey": lent()})).expect("vault.unlock");}fn ids(section: &Value) -> Vec<String> {    section["rows"].as_array().unwrap().iter().map(|row| row["id"].as_str().unwrap().to_string()).collect()}fn section<'a>(answer: &'a Value, id: &str) -> &'a Value {    answer["sections"].as_array().unwrap().iter().find(|section| section["id"] == id).unwrap_or_else(|| panic!("no {id} section"))}fn group<'a>(answer: &'a Value, id: &str) -> &'a Value {    answer["groups"].as_array().unwrap().iter().find(|group| group["id"] == id).unwrap_or_else(|| panic!("no {id} group"))}const SECRET: &str = "otpauth://totp/Invented:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Invented";#[test]fn the_list_answers_chips_sections_and_marks_once_the_vault_is_open() {    let (_dir, handle) = phone();    wrapped(&handle);    let weak = login(&handle, "mail.invented.test", "ada", "password1");    let a = login(&handle, "shop.invented.test", "ada", "SYNTHETIC-same-Value-77!x");    let b = login(&handle, "forum.invented.test", "ada", "SYNTHETIC-same-Value-77!x");    add(&handle, json!({"kind": "note", "name": "Invented note", "fields": {"body": "SYNTHETIC body"}}));    crate::phone::keys::over(&handle.client(), "keys.favourite", &json!({"id": a, "on": true})).unwrap();    let shut = call(&handle, "vault.items", json!({}));    assert_eq!(shut["open"], false);    assert_eq!(shut["total"], 4);    assert!(shut["sections"].as_array().unwrap().iter().all(|s| s["rows"].as_array().unwrap().iter().all(|r| r["marks"].as_array().unwrap().is_empty())), "no marks while shut");    assert_eq!(ids(section(&shut, "favourites")), [a.clone()]);    let chips: Vec<&str> = shut["chips"].as_array().unwrap().iter().map(|chip| chip["id"].as_str().unwrap()).collect();    assert_eq!(chips, ["all", "favourites", "passwords", "notes"]);    assert!(!shut.to_string().contains("SYNTHETIC"), "no value in the list");    unlock(&handle);    let open = call(&handle, "vault.items", json!({"filter": "login"}));    assert_eq!(open["open"], true);    let marks = |id: &str| -> Vec<String> {        section(&open, "all")["rows"].as_array().unwrap().iter().find(|row| row["id"] == id).unwrap()["marks"].as_array().unwrap().iter().map(|m| m["id"].as_str().unwrap().to_string()).collect()    };    assert_eq!(marks(&weak), ["weak"]);    assert_eq!(marks(&a), ["reused"]);    assert_eq!(marks(&b), ["reused"]);    let found = call(&handle, "vault.items", json!({"q": "shop"}));    assert_eq!(ids(section(&found, "results")), [a.clone()]);    assert!(!open.to_string().contains("SYNTHETIC") && !open.to_string().contains("password1"), "no value with marks either");}#[test]fn an_item_shut_shows_its_plain_fields_and_open_shows_the_rest_but_never_a_secret() {    let (_dir, handle) = phone();    wrapped(&handle);    let id = add(&handle, json!({"kind": "login", "site": "bank.invented.test", "username": "ada", "fields": {"password": "SYNTHETIC-1", "notes": "SYNTHETIC-note", "totp": SECRET}}));    let shut = call(&handle, "vault.item", json!({"id": id}));    assert_eq!(shut["open"], false);    assert_eq!(shut["unlock"]["method"], "vault.unlock");    let keys: Vec<&str> = shut["blocks"][0]["fields"].as_array().unwrap().iter().map(|f| f["key"].as_str().unwrap()).collect();    assert_eq!(keys, ["username", "password"], "optional sealed fields are unknown while shut");    unlock(&handle);    crate::phone::keys::over(&handle.client(), "keys.change", &json!({"id": id, "fields": {"password": "SYNTHETIC-2"}, "privateKey": lent()})).unwrap();    let open = call(&handle, "vault.item", json!({"id": id}));    assert_eq!(open["open"], true);    let fields = open["blocks"][0]["fields"].as_array().unwrap();    let keys: Vec<&str> = fields.iter().map(|f| f["key"].as_str().unwrap()).collect();    assert_eq!(keys, ["username", "password", "notes", "totp"]);    let password = &fields[1];    assert_eq!(password["concealed"], true);    assert!(password.get("value").is_none(), "a concealed field carries no value");    assert!(password["acts"].as_array().unwrap().iter().all(|act| act["presence"] == true));    assert_eq!(fields[2]["value"], "SYNTHETIC-note", "notes read once the vault is open");    assert_eq!(fields[3]["liveCode"], true);    let blocks: Vec<&str> = open["blocks"].as_array().unwrap().iter().map(|b| b["id"].as_str().unwrap()).collect();    assert_eq!(blocks, ["fields", "fills", "history", "facts"]);    assert!(!open.to_string().contains("SYNTHETIC-1") && !open.to_string().contains("SYNTHETIC-2"));    let acts: Vec<&str> = open["acts"].as_array().unwrap().iter().map(|a| a["id"].as_str().unwrap()).collect();    assert_eq!(acts, ["edit", "favourite", "trash"]);    assert!(open["acts"][2]["confirm"].is_object());    let history = call(&handle, "vault.history", json!({"id": id}));    assert_eq!(history["rows"].as_array().unwrap().len(), 1);    assert_eq!(history["rows"][0]["value"], "SYNTHETIC-1");    assert_eq!(history["clearAfter"], 30, "an earlier password clears as every copy does");    let code = call(&handle, "vault.code", json!({"id": id}));    assert_eq!(code["code"].as_str().unwrap().len(), 6);    assert_eq!(code["shown"].as_str().unwrap().len(), 7);}#[test]fn a_field_is_revealed_to_its_caller_with_the_clipboard_seconds() {    let (_dir, handle) = phone();    wrapped(&handle);    let id = login(&handle, "mail.invented.test", "ada", "SYNTHETIC-1");    assert_eq!(refused(&handle, "vault.field", json!({"id": id, "field": "password"})), "vault_locked");    let user = call(&handle, "vault.field", json!({"id": id, "field": "username"}));    assert_eq!(user["value"], "ada");    assert_eq!(user["clearAfter"], 0);    let shown = call(&handle, "vault.field", json!({"id": id, "field": "password", "privateKey": lent()}));    assert_eq!(shown["value"], "SYNTHETIC-1");    assert_eq!(shown["clearAfter"], 30, "thirty seconds by default since Cotton Secrets");    assert_eq!(shown["mono"], true);    assert_eq!(shown["copiedToast"], "Copied. It clears from the clipboard in 30 seconds.");    call(&handle, "vault.act", json!({"act": "set", "key": "clipboardSeconds", "value": 60}));    assert_eq!(call(&handle, "vault.field", json!({"id": id, "field": "password", "privateKey": lent()}))["clearAfter"], 60);    assert_eq!(refused(&handle, "vault.act", json!({"act": "set", "key": "clipboardSeconds", "value": 7})), "bad_request");}#[test]fn add_and_edit_are_short_forms_with_the_generator_one_tap_away() {    let (_dir, handle) = phone();    wrapped(&handle);    let form = call(&handle, "vault.edit", json!({"kind": "login"}));    assert_eq!(form["title"], "New Login");    let keys: Vec<&str> = form["fields"].as_array().unwrap().iter().map(|f| f["key"].as_str().unwrap()).collect();    assert_eq!(keys, ["name", "site", "username", "password", "notes", "totp", "urls"]);    assert_eq!(form["fields"][3]["generate"], true);    assert_eq!(form["fields"][3]["input"], "secret");    assert_eq!(form["save"]["method"], "vault.save");    let saved = call(&handle, "vault.save", json!({"kind": "login", "site": "https://new.invented.test/login", "username": "ada", "fields": {"password": "SYNTHETIC-new"}, "privateKey": lent()}));    let id = saved["id"].as_str().unwrap().to_string();    assert_eq!(saved["toast"]["text"], "Saved.");    assert_eq!(row(&handle, &id)["site"], "new.invented.test");    assert_eq!(refused(&handle, "vault.edit", json!({"id": id})), "vault_locked", "an edit form holds the values: presence first");    unlock(&handle);    let edit = call(&handle, "vault.edit", json!({"id": id}));    assert_eq!(edit["title"], "Edit Login");    assert_eq!(edit["fields"][3]["value"], "SYNTHETIC-new");    call(&handle, "vault.save", json!({"id": id, "name": "Invented New", "fields": {"password": "SYNTHETIC-newer"}}));    assert_eq!(row(&handle, &id)["name"], "Invented New");    let card = call(&handle, "vault.edit", json!({"kind": "card"}));    let inputs: Vec<(&str, &str)> = card["fields"].as_array().unwrap().iter().map(|f| (f["key"].as_str().unwrap(), f["input"].as_str().unwrap())).collect();    assert_eq!(inputs, [("name", "text"), ("number", "number"), ("holder", "text"), ("expiry", "month"), ("cvv", "number"), ("notes", "multiline")]);}#[test]fn the_generator_makes_characters_words_and_pins_with_a_strength_line() {    let (_dir, handle) = phone();    let chars = call(&handle, "vault.generate", json!({}));    assert_eq!(chars["mode"], "chars");    assert_eq!(chars["value"].as_str().unwrap().chars().count(), 20);    assert_eq!(chars["strength"]["tone"], "safe");    assert_eq!(chars["strength"]["label"], "Strong");    let short = call(&handle, "vault.generate", json!({"length": 8, "symbols": false, "upper": false, "digits": false}));    assert_eq!(short["value"].as_str().unwrap().chars().count(), 8);    assert!(short["value"].as_str().unwrap().chars().all(|c| c.is_ascii_lowercase()));    let none = call(&handle, "vault.generate", json!({"lower": false, "upper": false, "digits": false, "symbols": false}));    assert!(none["value"].as_str().unwrap().chars().all(|c| c.is_ascii_lowercase()), "the last class stays on");    let words = call(&handle, "vault.generate", json!({"mode": "words", "words": 5, "separator": "."}));    assert_eq!(words["value"].as_str().unwrap().split('.').count(), 5);    assert_eq!(words["request"]["words"], 5);    let pin = call(&handle, "vault.generate", json!({"mode": "pin"}));    assert_eq!(pin["value"].as_str().unwrap().len(), 6);    assert!(pin["value"].as_str().unwrap().chars().all(|c| c.is_ascii_digit()));    assert_eq!(pin["strength"]["tone"], "danger", "a PIN is never called strong");    assert_eq!(refused(&handle, "vault.generate", json!({"mode": "emoji"})), "bad_request");    let clamped = call(&handle, "vault.generate", json!({"length": 500}));    assert_eq!(clamped["value"].as_str().unwrap().chars().count(), 64);}#[test]fn security_carries_health_waiting_windows_devices_reads_recovery_and_passkeys() {    let (_dir, handle) = phone();    wrapped(&handle);    let weak = login(&handle, "mail.invented.test", "ada", "password1");    let old = login(&handle, "old.invented.test", "ada", "SYNTHETIC-Long-Unique-Value-91!q");    exec(&handle, "UPDATE cotton_secrets SET changed_at = '2024-01-01T00:00:00Z', updated_at = '2024-01-01T00:00:00Z' WHERE id = ?", &[&old]);    let shut = call(&handle, "vault.security", json!({}));    assert_eq!(shut["health"]["open"], false);    assert_eq!(shut["health"]["old"], 1, "old is read from the plain date while shut");    let groups: Vec<&str> = shut["groups"].as_array().unwrap().iter().map(|g| g["id"].as_str().unwrap()).collect();    assert_eq!(groups, ["waiting", "windows", "breached", "weak", "reused", "old", "devices", "reads", "recovery", "passkeys"]);    assert_eq!(group(&shut, "breached")["detail"], "Not checked yet");    assert_eq!(group(&shut, "breached")["acts"][0]["method"], "vault.breach");    assert_eq!(group(&shut, "recovery")["rows"][0]["title"], "Sign in to keep a way back in with your account.");    unlock(&handle);    let open = call(&handle, "vault.security", json!({}));    assert_eq!(open["health"]["weak"], 1);    assert_eq!(open["health"]["tone"], "danger");    assert_eq!(open["health"]["summary"], "2 things to look at");    assert_eq!(ids(group(&open, "weak")), [weak]);    assert_eq!(ids(group(&open, "old")), [old]);    assert_eq!(group(&open, "reused")["empty"], "No password is used twice.");    assert_eq!(group(&open, "waiting")["empty"], "Nothing is waiting.");    assert_eq!(group(&open, "windows")["empty"], "No assistant can read your private things now.");    let devices = group(&open, "devices")["rows"].as_array().unwrap().clone();    assert!(group(&open, "devices").get("empty").is_none(), "a vault with this device says no empty line");    assert_eq!(devices.len(), 1);    assert_eq!(devices[0]["detail"], "This device");    assert!(devices[0]["acts"].as_array().unwrap().is_empty(), "this device is not removed from here");    assert_eq!(group(&open, "recovery")["rows"].as_array().unwrap().len(), 1);    assert_eq!(group(&open, "passkeys")["acts"][0]["method"], "signin.passkeyOptions");    assert!(!open.to_string().contains("password1") && !open.to_string().contains("SYNTHETIC"));}#[test]fn security_lists_a_device_waiting_and_a_sign_in_ask_from_the_host() {    let (_dir, handle) = phone();    wrapped(&handle);    let workspace = handle.client().with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap();    exec(&handle, "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, name, public_key, wrapped_vmk, vmk_version, created_at, updated_at) VALUES ('vk-2', ?, 'other-device', 'An invented tablet', 'AAAA', NULL, 1, '2026-11-11T09:00:00Z', '2026-11-11T09:00:00Z')", &[&workspace]);    let remote = |method: &str, _request: &Value| -> Result<Value, crate::methods::MethodError> {        match method {            "signin.asks" => Ok(json!({"waiting": [{"askId": "ask-1", "name": "An invented laptop", "line": "Asked a minute ago"}]})),            _ => Ok(json!({"passkeys": [{"id": "pk-1", "name": "Invented phone", "when": "Added today"}]})),        }    };    let answer = serde_json::to_value(super::security(&handle.client(), &json!({}), Some(&remote)).unwrap()).unwrap();    let waiting: Vec<String> = ids(group(&answer, "waiting"));    assert_eq!(waiting, ["device:other-device", "signin:ask-1"]);    assert_eq!(group(&answer, "waiting")["rows"][1]["open"]["method"], "signin.show");    assert_eq!(group(&answer, "waiting")["rows"][0]["acts"][0]["method"], "vault.refuseDevice");    assert_eq!(ids(group(&answer, "passkeys")), ["pk-1"]);    assert!(group(&answer, "passkeys")["rows"][0]["acts"][0]["confirm"].is_object());}#[test]fn settings_say_you_as_decisions_draws_it() {    let (_dir, handle) = phone();    let answer = call(&handle, "vault.settings", json!({"platform": "ios"}));    let groups: Vec<&str> = answer["groups"].as_array().unwrap().iter().map(|g| g["id"].as_str().unwrap()).collect();    assert_eq!(groups, ["open_with", "lock", "clipboard", "dashlane", "export", "look", "sync", "privacy", "storage", "help", "about"]);    let titles: Vec<&str> = answer["groups"].as_array().unwrap().iter().map(|g| g["title"].as_str().unwrap()).collect();    assert_eq!(titles, ["Open with", "Lock after", "Clear copied after", "Bring in from Dashlane", "Take everything out", "Look", "Sync", "Privacy", "Storage", "Help", "About"]);    assert_eq!(answer["title"], "You");    assert_eq!(group(&answer, "open_with")["rows"][1]["title"], "Tap General, then AutoFill & Passwords.");    let android = call(&handle, "vault.settings", json!({"platform": "android"}));    assert!(group(&android, "open_with")["rows"][1]["title"].as_str().unwrap().contains("Passwords, passkeys"));    let chosen = |answer: &Value, id: &str| -> Vec<String> { group(answer, id)["rows"].as_array().unwrap().iter().filter(|r| r["tone"] == "accent").map(|r| r["id"].as_str().unwrap().to_string()).collect() };    assert_eq!(chosen(&answer, "lock"), ["lock.5"]);    assert_eq!(group(&answer, "dashlane")["rows"][0]["open"]["request"], json!({"act": "open_page", "page": "import"}));    let opened = call(&handle, "vault.act", json!({"act": "open_page", "page": "look"}));    assert_eq!(opened["platform"], json!({"action": "open_page", "page": "look"}));    assert!(group(&answer, "export")["rows"].as_array().unwrap().iter().all(|r| r["open"]["presence"] == true));    assert_eq!(group(&answer, "storage")["rows"][0]["title"], "0 secrets");    assert_eq!(group(&answer, "about")["rows"][0]["title"], "Secrets");    // SYNC SEEN: Sync says what every home says (signed out here), never a bare account word.    assert_eq!(group(&answer, "sync")["rows"][0]["title"], "Signed out", "every line filled: the home's own sync line");    assert!(!answer.to_string().contains("{phone}"), "no placeholder left unfilled");    let security = call(&handle, "vault.security", json!({}));    assert_eq!(group(&security, "devices")["empty"], "No device opens this vault yet. Sign in to back it up and add your devices.");    call(&handle, "vault.act", json!({"act": "set", "key": "clipboardSeconds", "value": 90}));    let made = call(&handle, "vault.generate", json!({}));    assert_eq!(made["clearAfter"], 90, "the generator copies under the Settings choice");    assert_eq!(made["copiedToast"], "Copied. It clears from the clipboard in 90 seconds.");    let picked = call(&handle, "vault.act", json!({"act": "import", "from": "apple"}));    assert_eq!(picked["platform"]["action"], "pick_csv");    assert_eq!(picked["platform"]["then"], "password.importCsv");}#[test]fn favourite_bin_and_put_back_round_trip_with_their_toasts() {    let (_dir, handle) = phone();    wrapped(&handle);    let id = login(&handle, "mail.invented.test", "ada", "SYNTHETIC-1");    let starred = call(&handle, "vault.act", json!({"act": "favourite", "id": id}));    assert_eq!(starred["toast"]["text"], "Added to favourites.");    assert_eq!(starred["item"]["favourite"], true);    let gone = call(&handle, "vault.act", json!({"act": "trash", "id": id}));    assert_eq!(gone["gone"], true);    assert_eq!(gone["toast"]["undo"]["request"]["act"], "restore");    let list = call(&handle, "vault.items", json!({}));    assert_eq!(list["total"], 0);    assert_eq!(list["bin"]["label"], "Recently deleted · 1");    let bin = call(&handle, "vault.items", json!({"filter": "bin"}));    assert_eq!(ids(section(&bin, "bin")), [id.clone()]);    let item = call(&handle, "vault.item", json!({"id": id}));    assert_eq!(item["inBin"], true);    assert_eq!(item["acts"][0]["id"], "restore");    let back = call(&handle, "vault.act", json!({"act": "restore", "id": id}));    assert_eq!(back["toast"]["text"], "Put back.");    assert_eq!(call(&handle, "vault.items", json!({}))["total"], 1);    // The list kept in memory follows every write: a rename that stamps nothing, and a row landed by a pass.    call(&handle, "vault.items", json!({}));    crate::phone::keys::over(&handle.client(), "keys.change", &json!({"id": id, "name": "Invented Renamed"})).unwrap();    assert_eq!(call(&handle, "vault.items", json!({}))["sections"][0]["rows"][0]["title"], "Invented Renamed");    exec(&handle, "UPDATE cotton_secrets SET name = 'Invented Synced' WHERE id = ?", &[&id]);    assert_eq!(call(&handle, "vault.items", json!({}))["sections"][0]["rows"][0]["title"], "Invented Synced");    let site = call(&handle, "vault.act", json!({"act": "open_site", "id": id}));    assert_eq!(site["platform"]["url"], "https://mail.invented.test");}// RULE: Settings' Sign out runs this device's own flow, the answer `tools.act` gives (`platform_action: open_flow`), handed to the phone as `platform`; Back up now says so in a toast.#[test]fn sign_out_hands_the_phone_its_own_flow_and_back_up_says_so() {    use crate::shell::client::phone_tests::attached;    let (_dir, client) = attached();    let answer = super::call(&client, "vault.act", &json!({"act": "sign_out"}), None).expect("sign_out");    assert_eq!(answer["platform"]["platform_action"], "open_flow");    assert_eq!(answer["platform"]["flow"], "signOut");    assert!(answer.get("toast").is_none());    let backed = super::call(&client, "vault.act", &json!({"act": "back_up"}), None).expect("back_up");    assert!(backed["platform"].is_null() && backed["toast"]["text"].is_string());}/// A range body as the breach service answers one: this suffix seen `count` times, among others.fn range_with(password: &str, count: u64) -> (String, String) {    let (prefix, suffix) = cotton_core::keys::health::breach_range(password);    (prefix, format!("0000000000000000000000000000000000A:3\r\n{}:{count}\r\n", suffix.as_str()))}#[test]fn a_breach_check_asks_prefixes_then_reads_the_ranges_and_marks_what_was_found() {    let (_dir, handle) = phone();    wrapped(&handle);    let seen = login(&handle, "seen.invented.test", "ada", "SYNTHETIC-Seen-Value-11!z");    let clean = login(&handle, "clean.invented.test", "ada", "SYNTHETIC-Clean-Value-22!y");    let asked = call(&handle, "vault.breach", json!({"privateKey": lent()}));    assert_eq!(asked["platform"]["action"], "fetch_ranges");    assert_eq!(asked["platform"]["then"], "vault.breach");    let prefixes: Vec<String> = asked["platform"]["prefixes"].as_array().unwrap().iter().map(|p| p.as_str().unwrap().to_string()).collect();    assert_eq!(prefixes.len(), 2);    assert!(prefixes.iter().all(|p| p.len() == 5), "only five characters leave the phone");    assert!(!asked.to_string().contains("SYNTHETIC"));    let (hit_prefix, hit_body) = range_with("SYNTHETIC-Seen-Value-11!z", 42);    let (miss_prefix, _) = range_with("SYNTHETIC-Clean-Value-22!y", 0);    let ranges = json!({hit_prefix: hit_body, miss_prefix: "0000000000000000000000000000000000B:1\r\n"});    let read = call(&handle, "vault.breach", json!({"ranges": ranges, "privateKey": lent()}));    assert_eq!(read["toast"]["text"], "1 password was found in a breach. Change it on the site, then here.");    let security = call(&handle, "vault.security", json!({}));    assert_eq!(security["health"]["breached"], 1);    assert_eq!(security["health"]["tone"], "danger");    assert_eq!(ids(group(&security, "breached")), [seen.clone()]);    assert_eq!(group(&security, "breached")["rows"][0]["detail"], "Seen 42 times in breaches");    assert!(group(&security, "breached")["detail"].as_str().unwrap().starts_with("Last checked "));    let list = call(&handle, "vault.items", json!({"filter": "login"}));    let marks = |id: &str| section(&list, "all")["rows"].as_array().unwrap().iter().find(|r| r["id"] == id).unwrap()["marks"].clone();    assert_eq!(marks(&seen)[0]["id"], "breached");    assert!(marks(&clean).as_array().unwrap().is_empty());    let item = call(&handle, "vault.item", json!({"id": seen}));    assert_eq!(item["banner"]["tone"], "danger");    // A password changed since the check is not called breached any more.    std::thread::sleep(std::time::Duration::from_millis(5));    crate::phone::keys::over(&handle.client(), "keys.change", &json!({"id": seen, "fields": {"password": "SYNTHETIC-Fresh-Value-33!x"}, "privateKey": lent()})).unwrap();    let after = call(&handle, "vault.security", json!({}));    assert_eq!(after["health"]["breached"], 0);    assert!(ids(group(&after, "breached")).is_empty());    assert_eq!(group(&after, "breached")["empty"], "None of your passwords was found in a known breach.");    let partial = call(&handle, "vault.breach", json!({"ranges": {}, "privateKey": lent()}));    assert_eq!(partial["toast"]["text"], "Some answers did not arrive. Check again in a moment.");}#[test]fn recovery_offers_the_code_this_phones_platform_copy_and_a_trusted_person() {    let none = serde_json::to_value(super::recovery_of(&json!({"signedIn": true, "code": null, "google": null, "apple": null, "trusted": null}), "android")).unwrap();    let rows: Vec<&str> = none["rows"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect();    assert_eq!(rows, ["code", "platform.google", "trusted"]);    assert_eq!(none["rows"][0]["acts"][0]["method"], "recovery.make");    assert_eq!(none["rows"][0]["acts"][0]["presence"], true);    assert_eq!(none["rows"][1]["title"], "Not kept in your Google account");    assert_eq!(none["rows"][1]["acts"][0]["request"]["store"], "google");    let trust = &none["rows"][2]["acts"][0];    assert_eq!(trust["method"], "recovery.trust");    assert_eq!(trust["input"]["key"], "number");    assert_eq!(trust["input"]["input"], "phone");    let held = json!({"signedIn": true,        "code": {"made": "2026-11-01", "current": true, "line": "Kept since 2026-11-01"},        "apple": {"made": "2026-10-01", "current": false, "line": "Kept since 2026-10-01"},        "trusted": {"helper": "+910000000000", "name": "An invented friend", "line": "An invented friend can help you back in"}});    let ios = serde_json::to_value(super::recovery_of(&held, "ios")).unwrap();    assert_eq!(ios["rows"][0]["title"], "Recovery code made");    assert_eq!(ios["rows"][0]["acts"][0]["method"], "recovery.show");    assert_eq!(ios["rows"][1]["id"], "platform.apple");    assert_eq!(ios["rows"][1]["tone"], "attention", "a copy from before a key change asks to be renewed");    assert_eq!(ios["rows"][1]["acts"][0]["label"], "Renew");    assert_eq!(ios["rows"][2]["title"], "An invented friend can help you back in");    assert_eq!(ios["rows"][2]["acts"][0]["label"], "Choose someone else");    let stale = serde_json::to_value(super::recovery_of(&json!({"signedIn": true, "code": {"current": false}}), "android")).unwrap();    assert_eq!(stale["rows"][0]["acts"][0]["label"], "Make a new code");    let asks = super::help_rows(&json!({"asks": [{"id": "help-1", "name": "An invented friend", "code": "1234", "line": "An invented friend asks: compare 1234"}]}));    let row = serde_json::to_value(&asks[0]).unwrap();    assert_eq!(row["id"], "help:help-1");    assert_eq!(row["acts"][0]["method"], "recovery.helpApprove");    assert_eq!(row["acts"][0]["presence"], true);    assert!(row["acts"][0]["confirm"]["body"].as_str().unwrap().contains("1234"), "the code to compare is said before Approve");    assert_eq!(row["acts"][1]["method"], "recovery.helpDecline");}#[test]fn the_look_is_the_kit_data_whole() {    let (_dir, handle) = phone();    let look = call(&handle, "vault.look", json!({}));    assert_eq!(look["id"], "vault");    assert!(look["colours"]["dark"]["background"].is_string());    assert_eq!(look["fonts"]["mono"]["family"], "JetBrains Mono");}/// 2,000 invented logins, plain columns only: the list and a search on a release build./// `cargo test --release -p cotton-ffi --lib vault_app::tests::two_thousand -- --ignored --nocapture`#[test]#[ignore]fn two_thousand_items_list_and_search_fast() {    let (_dir, handle) = phone();    let workspace = handle.client().with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap();    handle        .client()        .with_writer(|replica| {            for n in 0..2000 {                let id = format!("00000000-0000-4000-8000-{n:012}");                let args: Vec<rusqlite::types::Value> = [id.as_str(), workspace.as_str(), &format!("Invented site {n:04}"), &format!("site{n}.invented.test"), &format!("person{n}"), "2026-11-11T09:00:00Z"]                    .iter()                    .map(|v| rusqlite::types::Value::Text(v.to_string()))                    .collect();                replica                    .driver                    .run("INSERT INTO cotton_secrets (id, workspace_id, kind, name, site, username, created_at, updated_at, last_used_at) VALUES (?, ?, 'login', ?, ?, ?, ?, ?, ?)", &[args.clone(), vec![args[5].clone(), args[5].clone()]].concat())                    .map_err(|e| e.to_string())?;            }            Ok(())        })        .expect("seeded");    // The best of twenty: the box is shared, and a figure is the code's, not its neighbours'.    let time = |request: Value| {        call(&handle, "vault.items", request.clone());        let mut best = f64::MAX;        let mut answer = Value::Null;        for _ in 0..20 {            let start = std::time::Instant::now();            answer = call(&handle, "vault.items", request.clone());            best = best.min(start.elapsed().as_secs_f64() * 1000.0);        }        (best, answer)    };    let client = handle.client();    let phase = |label: &str, work: &dyn Fn()| {        let mut best = f64::MAX;        for _ in 0..20 {            let start = std::time::Instant::now();            work();            best = best.min(start.elapsed().as_secs_f64() * 1000.0);        }        println!("  {label}: {best:.1} ms");    };    let (secrets, passkeys) = super::all_rows(&client).unwrap();    let entries = super::entries(&secrets, &passkeys);    phase("read rows", &|| drop(super::all_rows(&client).unwrap()));    phase("  with_file alone", &|| client.with_file(|_| Ok(())).unwrap());    phase("  query alone", &|| {        client.with_file(|replica| { replica.driver.all("SELECT id, kind, name, site, username, favourite_at, last_used_at, changed_at, created_at, updated_at, uses, passkey_id, trashed_at FROM cotton_secrets WHERE workspace_id = ?", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())]).map(|_| ()).map_err(|e| e.to_string()) }).unwrap()    });    phase("  fingerprint", &|| {        client.with_file(|replica| { replica.driver.get("SELECT count(*) AS n, max(updated_at) AS at FROM cotton_secrets WHERE workspace_id = ?", &[rusqlite::types::Value::Text(replica.workspace_id.to_string())]).map(|_| ()).map_err(|e| e.to_string()) }).unwrap()    });    phase("health (shut)", &|| drop(super::reading(&client, &secrets, &json!({})).unwrap()));    phase("decide", &|| drop(cotton_core::keys::app::list::items(&entries, &Default::default(), &cotton_core::keys::app::list::Ask::default(), false)));    let decided = cotton_core::keys::app::list::items(&entries, &Default::default(), &cotton_core::keys::app::list::Ask::default(), false);    phase("to json", &|| drop(serde_json::to_value(&decided).unwrap()));    let (list_ms, list) = time(json!({}));    let (search_ms, found) = time(json!({"q": "site19"}));    println!("vault.items over 2000: list {list_ms:.1} ms, search {search_ms:.1} ms");    assert_eq!(list["total"], 2000);    assert_eq!(found["total"], 111);    if !cfg!(debug_assertions) {        assert!(list_ms < 30.0 && search_ms < 30.0, "list {list_ms:.1} ms, search {search_ms:.1} ms");    }}#[test]fn a_card_a_token_and_a_file_say_their_second_line_only_while_open() {    let (_dir, handle) = phone();    wrapped(&handle);    let card = add(&handle, json!({"kind": "card", "name": "Invented card", "fields": {"number": "4111111111114821", "cvv": "123"}}));    let token = add(&handle, json!({"kind": "api_key", "name": "Invented deploy key", "fields": {"key": "sk_test_SYNTHETIC00000004f2a"}}));    let file = add(&handle, json!({"kind": "file", "name": "Invented env", "fields": {"content": "U1lOVEhFVElDPTEKQj0yCg==", "file_name": "invented.env"}}));    let subtitle = |answer: &Value, id: &str| -> (String, bool) {        let row = answer["sections"].as_array().unwrap().iter().flat_map(|s| s["rows"].as_array().unwrap().iter()).find(|row| row["id"] == id).unwrap().clone();        (row["subtitle"].as_str().unwrap().to_string(), row["mono"].as_bool().unwrap())    };    let shut = call(&handle, "vault.items", json!({}));    assert_eq!(subtitle(&shut, &card).0, "Card", "shut: the plain columns only");    assert!(!shut.to_string().contains("4821") && !shut.to_string().contains("4f2a"), "nothing of a value while shut");    unlock(&handle);    let open = call(&handle, "vault.items", json!({}));    assert_eq!(subtitle(&open, &card), ("Card ending 4821".to_string(), false));    assert_eq!(subtitle(&open, &token), ("sk_test_…4f2a".to_string(), true));    assert_eq!(subtitle(&open, &file), ("invented.env · 2 lines".to_string(), true));    assert!(!open.to_string().contains("SYNTHETIC"), "never the value itself");    let developer = call(&handle, "vault.items", json!({"kind": "developer"}));    let ids: Vec<&str> = developer["sections"][0]["rows"].as_array().unwrap().iter().map(|row| row["id"].as_str().unwrap()).collect();    assert_eq!(ids.len(), 2, "the developer group holds the token and the file");}// RULE (owner, DELETE EVERYWHERE, 25 Nov 2026; DELETE ACCOUNT LEFT, 26 Nov): Delete account is the shell's own part// on both phones (DeleteAccountPart, last on You while signed in), its words from `account.deletePage` in Secrets' name.// You carries no group of its own for it, so no phone draws it twice.#[test]fn delete_account_is_the_shells_part_and_you_never_draws_it_twice() {    let (_dir, handle) = phone();    let ids = |answer: &Value| -> Vec<String> { answer["groups"].as_array().unwrap().iter().map(|g| g["id"].as_str().unwrap().to_string()).collect() };    assert!(!ids(&call(&handle, "vault.settings", json!({}))).contains(&"delete_account".to_string()), "signed out");    let workspace = handle.client().with_file(|file| Ok(file.workspace_id.to_string())).unwrap();    handle.client().keep_signed_in(Some(workspace));    assert!(!ids(&call(&handle, "vault.settings", json!({}))).contains(&"delete_account".to_string()), "signed in: the part draws it, not a group");    let words = crate::methods::dispatch(&handle, "account.deletePage", &json!({"app": "Cotton Secrets"})).expect("the delete page's words");    assert!(words["row"].as_str().is_some_and(|row| !row.is_empty()), "{words}");    assert!(words["otherApps"].as_str().is_some_and(|line| line.contains("Cotton Secrets")), "said in the app the person is in: {words}");}/// RULE (SYNC SEEN, owner 25 Nov 2026): Secrets' You says sync in the line every app's home and Sync page say/// (`shell_account::sync_said`), never a bare "Signed in".#[test]fn you_says_sync_as_every_home_says_it() {    let (_dir, handle) = phone();    let said = crate::methods::shell_account::sync_said(&handle.client());    let answer = call(&handle, "vault.settings", json!({}));    let row = &group(&answer, "sync")["rows"][0];    assert_eq!(row["title"], said["title"], "{row}");    assert!(row["title"].as_str().is_some_and(|t| !t.is_empty()));    let workspace = handle.client().with_file(|file| Ok(file.workspace_id.to_string())).unwrap();    handle.client().keep_signed_in(Some(workspace));    let said = crate::methods::shell_account::sync_said(&handle.client());    let answer = call(&handle, "vault.settings", json!({}));    let row = &group(&answer, "sync")["rows"][0];    assert_eq!(row["title"], said["title"], "signed in: {row}");    assert_eq!(row["detail"], said["last"]);}/// RULE (the Android Secrets walk, 26 Nov 2026: "kv-3e_9a3IKp…" stood under Devices): a device is never named by its/// key's id; with no name anywhere, this device is "This device".#[test]fn devices_never_say_a_key_id() {    let (_dir, handle) = phone();    let answer = call(&handle, "vault.security", json!({}));    let Some(devices) = answer["groups"].as_array().and_then(|groups| groups.iter().find(|g| g["id"] == "devices")) else { return };    for row in devices["rows"].as_array().into_iter().flatten() {        let title = row["title"].as_str().unwrap_or_default();        assert!(!title.is_empty() && title != row["id"].as_str().unwrap_or_default() && !title.starts_with("kv-"), "{row}");    }}/// RULE (UNSENT HEAL, coordinator 26 Nov 2026): a change that cannot be sent and will not go by itself is said on/// the Sync line and on Secrets' You with Send again and Let go (behind its confirm); Send again offers it as new,/// Let go writes it down and stops sending it. A write held two days for a key that never came (the owner's Comms)/// is one of them.#[test]fn a_change_that_cannot_be_sent_is_said_with_send_again_and_let_go() {    let (_dir, handle) = phone();    let client = handle.client();    assert!(crate::methods::shell_account::sync_said(&client)["stuck"].is_null(), "nothing waits");    let now = client.now();    let two_days_ago = (now - chrono::Duration::days(2)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    let just_now = now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    let seed = || {        client            .with_writer(|file| {                for (op, row, at, error) in [("op-stuck-1", "note-a", &just_now, "seal_column_clash: an invented clash"), ("op-stuck-2", "note-b", &two_days_ago, "seal_key_missing: no key for an invented table")] {                    file.driver                        .run(                            "INSERT OR REPLACE INTO _outbox (op_id, kind, author, tbl, row_id, hlc, schema_version, queued_at, bytes, last_error, attempts) VALUES (?, 'change', 'device:invented', 'cotton_notes', ?, '0', 1, ?, x'00', ?, 3)",                            &[rusqlite::types::Value::Text(op.into()), rusqlite::types::Value::Text(row.into()), rusqlite::types::Value::Text(at.clone()), rusqlite::types::Value::Text(error.into())],                        )                        .map_err(|error| error.to_string())?;                    let code = error.split_once(':').map(|(code, _)| code);                    cotton_store::outbox::note_refused(file.driver, op, code, at).map_err(|error| error.to_string())?;                }                Ok(())            })            .expect("queued")    };    seed();    let said = crate::methods::shell_account::sync_said(&client);    let stuck = &said["stuck"];    assert_eq!(stuck["title"], "2 changes can't be sent", "{stuck}");    assert_eq!(stuck["acts"][0]["method"], "sync.stuck.again");    assert_eq!(stuck["acts"][1]["method"], "sync.stuck.letGo");    assert!(stuck["acts"][1]["confirm"]["title"].as_str().is_some_and(|t| !t.is_empty()));    let you = call(&handle, "vault.settings", json!({}));    let row = &group(&you, "sync")["rows"][1];    assert_eq!(row["title"], stuck["title"], "{row}");    assert_eq!(row["acts"].as_array().map(Vec::len), Some(2));    let listed = crate::methods::dispatch(&handle, "sync.stuck", &json!({})).expect("sync.stuck");    assert!(!listed.to_string().contains("note-a") && !listed.to_string().contains("invented clash"), "tables and codes only: {listed}");    // The acts name what the screen showed; a stale screen is refused, and draws again (review item 2).    assert_eq!(crate::methods::dispatch(&handle, "sync.stuck.again", &json!({})).expect_err("no ids").code, "bad_request");    assert_eq!(crate::methods::dispatch(&handle, "sync.stuck.letGo", &json!({"ids": ["op-stuck-1"]})).expect_err("not what is stuck").code, "stuck_changed");    let again = crate::methods::dispatch(&handle, "sync.stuck.again", &stuck["acts"][0]["request"]).expect("sync.stuck.again");    assert_eq!(again["sent"], 2, "{again}");    assert!(crate::methods::shell_account::sync_said(&client)["stuck"].is_null(), "offered as new");    seed();    let shown = crate::methods::shell_account::sync_said(&client)["stuck"]["acts"][1]["request"].clone();    let gone = crate::methods::dispatch(&handle, "sync.stuck.letGo", &shown).expect("sync.stuck.letGo");    assert_eq!(gone["letGo"], 2, "{gone}");    assert!(crate::methods::shell_account::sync_said(&client)["stuck"].is_null());    let workspace = client.with_file(|file| Ok(file.workspace_id.to_string())).unwrap();    let written = cotton_client::unsent::discarded(client.layout(), &workspace);    assert_eq!(written.last().map(|d| d.changes.len()), Some(2), "written down for Feedback, even a receipt that does not read");    assert!(!serde_json::to_string(&written).unwrap().contains("invented"), "codes only, never the words (review item 6)");}