Cotton code
2431 lines · 107.2 KB · RustRaw
//! The vault family, against a paired phone.//!//! Everything here runs on `shell::client::phone_tests::attached_on_a_clock` —//! the one place a paired phone is assembled, a synthetic file at the build's//! own schema version, a FIXED clock and a seeded RNG. The clock is handed back//! because half of what this module promises is about TIME, and a five-minute//! unlock measured against a wall clock would be a test with a computable//! detonation date.//!//! **Every fixture is invented.** A workspace of zeroes, a site nobody hosts, a//! password nobody uses ([nothing-real-ever-goes-in-cotton-s-public-tree]). The//! strings below are the ones a form on the simulator types too, so what the//! screenshots hold and what these cases hold are the same nonsense.use std::sync::Arc;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use chrono::{DateTime, Duration, Utc};use serde_json::{json, Map, Value};use cotton_core::vault::{seal, wrap, SecretKind, Vmk};use super::{self as vault, VaultSession, VAULT_UNLOCK_TTL_SECONDS};use crate::shell::client::phone_tests::attached_on_a_clock;use crate::shell::client::ClientController;// ── invented fixtures ──────────────────────────────────────────────────────/// A site nobody hosts and a password nobody uses.const SITE: &str = "portal.nowhere-invented.test";const USERNAME: &str = "nobody@nowhere-invented.test";const PASSWORD: &str = "correct-horse-INVENTED-42";const NAME: &str = "Nowhere portal";/// A device vault key that is fixed rather than minted, so the wrap in a/// fixture is reproducible. Not a key anything holds: 32 bytes counting up.fn device_secret() -> [u8; 32] {    let mut bytes = [0u8; 32];    for (index, byte) in bytes.iter_mut().enumerate() {        *byte = index as u8;    }    bytes}/// The workspace's master key, fixed for the same reason.fn fixture_vmk() -> Vmk {    let mut bytes = [0u8; 32];    for (index, byte) in bytes.iter_mut().enumerate() {        *byte = 200u8.wrapping_sub(index as u8);    }    Vmk::from_bytes(bytes)}fn b64(bytes: &[u8]) -> String {    URL_SAFE_NO_PAD.encode(bytes)}// ── the harness ────────────────────────────────────────────────────────────struct Phone {    _dir: tempfile::TempDir,    client: Arc<ClientController>,    clock: Arc<cotton_client::seams::FixedClock>,}fn phone() -> Phone {    let (dir, client, clock) = attached_on_a_clock();    // A signed-in phone that has synced: it read the object's vault rows.    client.note_pull_for_test("2026-09-08T09:00:00.000Z");    Phone {        _dir: dir,        client,        clock,    }}impl Phone {    fn call(&self, method: &str, request: Value) -> Result<Value, crate::methods::MethodError> {        vault::over(&self.client, method, &request)    }    fn ok(&self, method: &str, request: Value) -> Value {        self.call(method, request)            .unwrap_or_else(|error| panic!("{method} refused: {} {}", error.code, error.message))    }    fn refusal(&self, method: &str, request: Value) -> crate::methods::MethodError {        self.call(method, request)            .expect_err("this call is supposed to be refused")    }    fn read(&self, name: &str, args: &[(&str, Value)]) -> Value {        let entry = crate::phone::reads::read_for(name).unwrap_or_else(|| panic!("{name} is declared"));        let args: Map<String, Value> = args            .iter()            .map(|(key, value)| ((*key).to_string(), value.clone()))            .collect();        crate::phone::answer_read(&self.client, entry, &args)            .unwrap_or_else(|reason| panic!("{name} answered: {reason}"))    }    fn workspace(&self) -> String {        self.client            .with_writer(|replica| Ok(replica.workspace_id.to_string()))            .expect("the workspace id")    }    /// THE ID THE SERVER ADMITS THIS PHONE BY, which is what every    /// `cotton_vault_keys` row in here is filed under — never    /// `replica.device_id`, which is the author id this file's OPS carry.    fn device(&self) -> String {        self.client            .self_device_id()            .expect("a paired phone knows the id its server admits it by")    }    fn exec(&self, sql: &str, params: &[&str]) {        self.client            .with_writer(|replica| {                let bound: Vec<rusqlite::types::Value> = params                    .iter()                    .map(|value| rusqlite::types::Value::Text((*value).to_string()))                    .collect();                replica                    .driver                    .run(sql, &bound)                    .map(|_| ())                    .map_err(|error| error.to_string())            })            .expect("the seed");    }    fn column(&self, sql: &str, id: &str) -> Option<String> {        self.client            .with_writer(|replica| {                Ok(replica                    .driver                    .get(sql, &[rusqlite::types::Value::Text(id.to_string())])                    .map_err(|error| error.to_string())?                    .and_then(|row| row.text("v").map(str::to_string)))            })            .expect("the column")    }    /// The state a phone is in AFTER its Mac has wrapped for it: a published    /// key, a wrap at version 1, and a workspace at version 1.    fn wrapped(&self) {        self.wrapped_under(&fixture_vmk());    }    /// [`Self::wrapped`] for the database the calling thread has named, under    /// THAT database's master key.    fn wrapped_under(&self, vmk: &Vmk) {        let now = "2026-09-08T09:00:00.000Z";        self.exec(            "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at)             VALUES (?, 1, ?, ?, ?)",            &[&self.workspace(), now, now, now],        );        let public = wrap::public_of(&device_secret());        let wrapped = wrap::wrap(&public, vmk.expose()).expect("a wrap");        self.exec(            "INSERT INTO cotton_vault_keys               (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)             VALUES ('vk-1', ?, ?, ?, ?, 1, ?, ?)",            &[                &self.workspace(),                &self.device(),                &b64(&public),                &wrapped,                now,                now,            ],        );    }    /// Unlock the way the app does: the private half, base64url.    fn unlock(&self) -> Value {        self.ok(            "vault.unlock",            json!({ "privateKey": b64(&device_secret()) }),        )    }    fn create_login(&self) -> String {        let answer = self.ok(            "vault.create",            json!({                "kind": "login",                "name": NAME,                "site": SITE,                "username": USERNAME,                "fields": { "password": PASSWORD },            }),        );        answer["id"].as_str().expect("an id").to_string()    }}// ── the session, as a pure thing ───────────────────────────────────────────fn instant(text: &str) -> DateTime<Utc> {    DateTime::parse_from_rfc3339(text)        .expect("a literal instant")        .with_timezone(&Utc)}#[test]fn an_unlock_lasts_exactly_five_minutes_and_then_the_key_is_gone() {    let session = Arc::new(VaultSession::default()).of("a-database");    let start = instant("2026-09-13T10:00:00Z");    let until = session.unlock(fixture_vmk(), 1, start);    assert_eq!(        until,        start + Duration::seconds(VAULT_UNLOCK_TTL_SECONDS),        "the deadline is the spec's VAULT_UNLOCK_TTL and nothing else"    );    // A second before the deadline it is still open …    assert!(session.until(until - Duration::seconds(1)).is_some());    assert_eq!(session.version(until - Duration::seconds(1)), Some(1));    // … and AT the deadline it is not. The boundary is closed on the far side:    // a key that lives for one more instant than it was promised is a key with    // no deadline anybody can reason about.    assert!(session.until(until).is_none());    assert!(session.with_vmk(until, |_, _| ()).is_none());}#[test]fn reading_the_state_after_the_deadline_forgets_the_key_rather_than_merely_hiding_it() {    let session = Arc::new(VaultSession::default()).of("a-database");    let start = instant("2026-09-13T10:00:00Z");    session.unlock(fixture_vmk(), 1, start);    // One read past the deadline …    assert!(session.until(start + Duration::seconds(600)).is_none());    // … and the key is GONE, not merely out of date: a clock that went    // backwards (a manual change, a time-zone database update) must not bring    // an expired unlock back.    assert!(session        .with_vmk(start + Duration::seconds(1), |_, _| ())        .is_none());}#[test]fn locking_forgets_the_key_now() {    let session = Arc::new(VaultSession::default()).of("a-database");    let start = instant("2026-09-13T10:00:00Z");    session.unlock(fixture_vmk(), 1, start);    session.lock();    assert!(session.until(start).is_none());}#[test]fn the_session_never_prints_the_key() {    let session = Arc::new(VaultSession::default()).of("a-database");    session.unlock(fixture_vmk(), 7, instant("2026-09-13T10:00:00Z"));    let printed = format!("{session:?}");    assert!(printed.contains("version: 7"), "{printed}");    // The `Vmk`'s own `Debug` is `Vmk(…)`; this is the guard that a struct    // holding one did not derive its way past that.    assert!(!printed.contains("200"), "{printed}");}#[test]fn a_key_unlocked_for_one_database_is_no_other_databases_key() {    let session = Arc::new(VaultSession::default());    let start = instant("2026-09-13T10:00:00Z");    session.of("a-database").unlock(fixture_vmk(), 1, start);    assert!(session.of("a-database").until(start).is_some());    assert!(session.of("another").until(start).is_none());    assert!(session.of("another").with_vmk(start, |_, _| ()).is_none());    // Locking one leaves the other; locking all leaves none.    session.of("another").unlock(family_vmk(), 3, start);    session.of("a-database").lock();    assert_eq!(session.of("another").version(start), Some(3));    session.lock_all();    assert!(session.of("another").until(start).is_none());}// ── one vault per database ─────────────────────────────────────────────────/// A second database this phone holds. Synthetic.const FAMILY: &str = "22222222-2222-4222-8222-222222222222";/// FAMILY's master key — a different key from [`fixture_vmk`], because every/// database has its own.fn family_vmk() -> Vmk {    Vmk::from_bytes([91u8; 32])}/// [`phone`], holding FAMILY beside its own database: a place on the/// connection record, a file of its own, and this device's row in it.fn phone_holding_family() -> Phone {    let phone = phone();    let layout = cotton_client::layout::Layout::new(phone._dir.path());    let record = layout.connection_json();    let mut connection: Value =        serde_json::from_slice(&std::fs::read(&record).expect("the record")).expect("json");    connection["places"] = json!([        { "id": FAMILY, "name": "Family", "available": true, "unavailableSince": null },    ]);    std::fs::write(&record, serde_json::to_vec_pretty(&connection).expect("json"))        .expect("the record");    let path = layout.replica(FAMILY);    std::fs::create_dir_all(path.parent().expect("a parent")).expect("the replica folder");    let text = |value: &str| rusqlite::types::Value::Text(value.to_string());    let at = "2026-09-08T09:00:00.000Z";    let db = cotton_store::test_template::create_workspace_for_test(        &path,        &cotton_store::meta::Meta {            workspace_id: FAMILY.to_string(),            owner_id: crate::fixture::OWNER.to_string(),            device_id: crate::fixture::DEVICE.to_string(),            last_server_seq: 0,            last_hlc: None,        },    )    .expect("a synthetic database");    db.run(        "INSERT OR IGNORE INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[text(FAMILY), text("Family"), text(crate::fixture::OWNER), text(at)],    )    .expect("the workspace row");    db.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \         approved_by_device, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",        &[            text(&cotton_tools::devices::approval_row_id(                FAMILY,                crate::fixture::SELF_DEVICE_ID,                at,            )),            text(FAMILY),            text(crate::fixture::SELF_DEVICE_ID),            text("An invented phone"),            text(at),            text("self"),            text(at),            text(at),        ],    )    .expect("this device's row");    cotton_tools::test_fixtures::reconcile(&db, "cotton_devices");    drop(db);    phone}impl Phone {    /// Mark FAMILY on the connection record as made here and not yet taken by    /// the server, or as taken.    fn set_family_pending(&self, pending: bool) {        let record = cotton_client::layout::Layout::new(self._dir.path()).connection_json();        let mut connection: Value =            serde_json::from_slice(&std::fs::read(&record).expect("the record")).expect("json");        connection["places"][0]["pending"] = json!(pending);        std::fs::write(&record, serde_json::to_vec_pretty(&connection).expect("json"))            .expect("the record");    }    /// Answer `work` from FAMILY, the way a call carrying `database` is.    fn in_family<T>(&self, work: impl FnOnce() -> T) -> T {        let _named = self.client.name_database(Some(FAMILY)).expect("FAMILY is held");        work()    }}// RULE: A vault key unlocked in one database opens and seals nothing in another: each database's passwords are sealed under that database's own key, and a database that is not unlocked refuses as locked.#[test]fn an_unlock_opens_only_its_own_database() {    let phone = phone_holding_family();    phone.wrapped();    phone.in_family(|| phone.wrapped_under(&family_vmk()));    // Unlocked in its own database …    phone.unlock();    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(true));    // … FAMILY is still locked, and a password made there is REFUSED rather    // than sealed under the personal database's key.    phone.in_family(|| {        assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(false));        let refusal = phone.refusal(            "vault.create",            json!({ "kind": "login", "name": NAME, "fields": { "password": PASSWORD } }),        );        assert_eq!(refusal.code, "vault_locked");    });    // Unlocked in FAMILY, a password made there is sealed under FAMILY's key    // and no other; the personal database stays unlocked beside it.    let id = phone.in_family(|| {        phone.unlock();        phone.create_login()    });    let sealed = phone.in_family(|| {        phone            .column("SELECT value_enc AS v FROM cotton_secrets WHERE id = ?", &id)            .expect("the sealed value")    });    assert!(seal::open(&family_vmk(), &id, 1, &sealed).is_some());    assert!(        seal::open(&fixture_vmk(), &id, 1, &sealed).is_none(),        "FAMILY's password was sealed under another database's key"    );    assert_eq!(        phone.column("SELECT value_enc AS v FROM cotton_secrets WHERE id = ?", &id),        None,        "the password was written into the personal database"    );    let mine = phone.create_login();    let sealed = phone        .column("SELECT value_enc AS v FROM cotton_secrets WHERE id = ?", &mine)        .expect("the sealed value");    assert!(seal::open(&fixture_vmk(), &mine, 1, &sealed).is_some());    // Locking is the person putting the phone down: every database locks.    phone.in_family(|| phone.ok("vault.lock", json!({})));    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(false));    phone.in_family(|| {        assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(false));    });}// ── vault.publishKey ───────────────────────────────────────────────────────#[test]fn publishing_a_key_writes_this_devices_row_and_saying_it_twice_changes_nothing() {    let phone = phone();    let public = b64(&wrap::public_of(&device_secret()));    let first = phone.ok("vault.publishKey", json!({ "publicKey": public }));    assert_eq!(first["changed"], json!(true));    assert_eq!(first["deviceId"], json!(phone.device()));    let again = phone.ok("vault.publishKey", json!({ "publicKey": public }));    assert_eq!(        again["changed"],        json!(false),        "publishing the same key twice is a no-op — the join carries it AND the \         app publishes it, and both paths can happen"    );    assert_eq!(        first["databases"][0]["id"], again["databases"][0]["id"],        "one row, not two"    );}// RULE: A device's vault public key is published into every database the device holds, whichever database the call names; a database made on the device and not yet taken by the server gets it on the pass after it is taken.#[test]fn vault_key_published_into_every_database() {    let phone = phone_holding_family();    let public = b64(&wrap::public_of(&device_secret()));    let key_row = "SELECT public_key AS v FROM cotton_vault_keys WHERE device_id = ?";    // Asked with FAMILY named — and the device's own database gets it too.    let answer = phone.in_family(|| phone.ok("vault.publishKey", json!({ "publicKey": public })));    assert_eq!(answer["changed"], json!(true));    let named: Vec<&str> = answer["databases"]        .as_array()        .expect("a row per database")        .iter()        .filter_map(|row| row["databaseId"].as_str())        .collect();    assert_eq!(named, vec![phone.workspace().as_str(), FAMILY]);    assert_eq!(phone.column(key_row, &phone.device()).as_deref(), Some(public.as_str()));    assert_eq!(        phone.in_family(|| phone.column(key_row, &phone.device())).as_deref(),        Some(public.as_str()),    );    assert!(phone.client.vault_key_published(FAMILY));    assert!(        vault::publish_owed(&phone.client).is_none(),        "every database holds the key, so a pass owes nothing and writes nothing"    );}#[test]fn a_database_not_yet_taken_gets_the_key_on_the_pass_after_it_is_taken() {    let phone = phone_holding_family();    phone.set_family_pending(true);    let public = b64(&wrap::public_of(&device_secret()));    let key_row = "SELECT public_key AS v FROM cotton_vault_keys WHERE device_id = ?";    phone.ok("vault.publishKey", json!({ "publicKey": public }));    assert_eq!(        phone.in_family(|| phone.column(key_row, &phone.device())),        None,        "a database the server has not taken has no vault to publish into"    );    assert!(vault::publish_owed(&phone.client).is_none(), "and nothing is owed while it waits");    // The server takes it; the next pass publishes there without being asked.    phone.set_family_pending(false);    let owed = vault::publish_owed(&phone.client)        .expect("FAMILY is owed the key")        .expect("and takes it");    assert_eq!(owed["databases"][0]["databaseId"], json!(FAMILY));    assert_eq!(        phone.in_family(|| phone.column(key_row, &phone.device())).as_deref(),        Some(public.as_str()),    );}/// THE 0.3.0 DEFECT, as a test.////// `vault.publishKey` filed this phone's key row under `replica.device_id` —/// the AUTHOR id (`device:<ulid>`) that names a device to a FILE — while/// `POST /v1/devices/pending/approve` files it under the Ed25519 id the/// registry admits. So the row the phone published named a device the server/// had never heard of, and `rotate::pending_rotation` reads exactly that as a/// REVOKED device: every boot deleted the row and rotated the master key, and/// the phone read "Waiting for your Mac to share the key" for ever.////// `cotton_client::replica::resolve_device_id` says in as many words that the/// two ids must not be conflated. This is the test that says it in the vault.#[test]fn a_published_key_is_filed_under_the_id_the_server_admits_never_the_author_id() {    let phone = phone();    let public = b64(&wrap::public_of(&device_secret()));    phone.ok("vault.publishKey", json!({ "publicKey": public }));    let author = phone        .client        .with_writer(|replica| Ok(replica.device_id.to_string()))        .expect("the author id");    assert!(        author.starts_with("device:"),        "the author id is the ulid-shaped one: {author}"    );    assert_ne!(author, phone.device(), "two ids, two questions");    let filed: Vec<String> = phone        .client        .with_writer(|replica| {            Ok(replica                .driver                .all("SELECT device_id FROM cotton_vault_keys", &[])                .map_err(|error| error.to_string())?                .iter()                .filter_map(|row| row.text("device_id").map(str::to_string))                .collect())        })        .expect("the rows");    assert_eq!(        filed,        vec![phone.device()],        "one row, under the id the server admits — never {author}"    );}#[test]fn publishing_a_different_key_clears_the_wrap_that_was_for_the_old_one() {    let phone = phone();    phone.wrapped();    // The Keychain item was lost and the phone minted again.    let fresh = wrap::public_of(&[9u8; 32]);    let answer = phone.ok("vault.publishKey", json!({ "publicKey": b64(&fresh) }));    assert_eq!(answer["changed"], json!(true));    let wrapped = phone.column(        "SELECT wrapped_vmk AS v FROM cotton_vault_keys WHERE device_id = ?",        &phone.device(),    );    assert!(        wrapped.is_none(),        "the old wrap was sealed to a key this phone no longer has — keeping it \         would be a row claiming this phone can open the vault when it cannot"    );    // And the phone now reads as waiting, which is what asks the worker to wrap.    assert_eq!(phone.ok("vault.status", json!({}))["wrapped"], json!(false));}#[test]fn a_public_key_that_is_not_thirty_two_bytes_is_refused_under_the_field() {    let phone = phone();    for bad in ["", "not-base64url!!", &b64(&[1u8; 31]), &b64(&[1u8; 33])] {        let error = phone.refusal("vault.publishKey", json!({ "publicKey": bad }));        assert_eq!(error.code, "bad_request", "{bad} was accepted");    }}// ── vault.unlock ───────────────────────────────────────────────────────────#[test]fn a_phone_whose_mac_has_not_wrapped_for_it_yet_is_told_to_wait() {    let phone = phone();    // A vault another device holds, and no row of this device's at all: the    // need publishes the key it holds (12 Nov 2026)    // and waits for the holder to approve it. (A vault nobody holds is    // founded here: see below.)    let theirs = wrap::wrap(&wrap::public_of(&[9u8; 32]), fixture_vmk().expose()).expect("a wrap");    phone.exec(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)         VALUES ('vault-key-holder', ?, 'device-holder', ?, ?, 1, '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z')",        &[&phone.workspace(), &b64(&wrap::public_of(&[9u8; 32])), &theirs],    );    phone.exec(        "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at) VALUES (?, 1, ?, ?, ?)",        &[&phone.workspace(), "2026-09-08T09:00:00.000Z", "2026-09-08T09:00:00.000Z", "2026-09-08T09:00:00.000Z"],    );    let error = phone.refusal(        "vault.unlock",        json!({ "privateKey": b64(&device_secret()) }),    );    assert_eq!(error.code, "vault_not_wrapped_yet");    assert_eq!(        error.message,        "Waiting for a device that holds your passwords to share the key"    );    assert_eq!(        phone.column("SELECT public_key AS v FROM cotton_vault_keys WHERE device_id = ?", &phone.device()),        Some(b64(&wrap::public_of(&device_secret()))),        "the key the need held is published"    );    assert_eq!(phone.own_wrap(), None, "and nothing is founded over the holder's vault");    // A published row with no wrap yet — the ordinary state until that    // device approves this one — says the same thing.    phone.ok(        "vault.publishKey",        json!({ "publicKey": b64(&wrap::public_of(&device_secret())) }),    );    assert_eq!(        phone            .refusal(                "vault.unlock",                json!({ "privateKey": b64(&device_secret()) })            )            .code,        "vault_not_wrapped_yet"    );}impl Phone {    fn publish(&self) {        self.ok("vault.publishKey", json!({ "publicKey": b64(&wrap::public_of(&device_secret())) }));    }    fn own_wrap(&self) -> Option<String> {        self.column("SELECT wrapped_vmk AS v FROM cotton_vault_keys WHERE device_id = ?", &self.device())    }    fn count(&self, sql: &str) -> i64 {        self.client            .with_writer(|replica| Ok(replica.driver.get(sql, &[]).map_err(|error| error.to_string())?.and_then(|row| row.int("n")).unwrap_or(0)))            .expect("a count")    }    /// What a pass does when the object takes the queued key writes.    fn object_takes_the_key(&self) {        self.exec("DELETE FROM _outbox WHERE tbl = 'cotton_vault_keys'", &[]);    }    /// What a pass does when the object refuses them `vault_founded`: parked    /// push-side, and the founder's row arrives with its own wrap.    fn object_refuses_the_founding(&self) {        self.exec(            "INSERT INTO _parked (op_id, direction, class, reason, tbl, row_id)             SELECT op_id, 'push', 'conflict', 'Another device already holds this vault''s key', tbl, row_id FROM _outbox WHERE tbl = 'cotton_vault_keys'",            &[],        );        self.exec("DELETE FROM _outbox WHERE tbl = 'cotton_vault_keys'", &[]);        let theirs = wrap::wrap(&wrap::public_of(&[9u8; 32]), fixture_vmk().expose()).expect("a wrap");        self.exec(            "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)             VALUES ('vault-key-founder', ?, 'device-founder', ?, ?, 1, '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z')",            &[&self.workspace(), &b64(&wrap::public_of(&[9u8; 32])), &theirs],        );    }}/// RULE (8 Nov 2026): a signed-in copy whose object holds no vault founds it the first time it needs it — the unlock before a passkey write or an import — and the wrap opens nothing until the object has taken it, so no row is sealed under a key that could lose a race.#[test]fn a_fresh_signed_in_copy_founds_on_its_first_unlock_and_opens_once_the_object_has_the_key() {    let phone = phone();    phone.publish();    assert_eq!(phone.own_wrap(), None, "signing in and publishing mint nothing");    let first = phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!((first.code.as_str(), first.message.as_str()), ("vault_not_wrapped_yet", "Setting up this device's vault: it opens once Cotton has its key."));    assert!(phone.own_wrap().is_some(), "the first need founded: a wrap for this device's own key");    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(false));    phone.object_takes_the_key();    phone.ok("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(true));    phone.ok("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(phone.count("SELECT COUNT(*) AS n FROM _outbox WHERE tbl = 'cotton_vault_keys'"), 0, "asked again, nothing is minted");}/// RULE (12 Nov 2026): a signed-in copy that never published its key (the launch's publish found no cached public half) publishes it on its first vault need, from the private key that need holds, and founds: it never waits on a Mac for a row no database holds.#[test]fn a_need_on_a_copy_that_never_published_publishes_the_key_it_holds_and_founds() {    let phone = phone();    assert_eq!(phone.count("SELECT COUNT(*) AS n FROM cotton_vault_keys"), 0, "nothing published at the launch");    let first = phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!((first.code.as_str(), first.message.as_str()), ("vault_not_wrapped_yet", "Setting up this device's vault: it opens once Cotton has its key."));    assert!(phone.own_wrap().is_some(), "published and founded on the first need");    phone.object_takes_the_key();    phone.ok("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(true));}/// RULE (8 Nov 2026): Keys › Devices is a first need too: opening it on a copy whose object holds no vault founds it.#[test]fn opening_the_devices_list_founds_the_vault_on_a_signed_in_copy() {    let phone = phone();    phone.publish();    let keys = phone.ok("vault.keys", json!({}));    assert_eq!(keys["devices"][0]["pending"], json!(false), "{keys}");    assert!(phone.own_wrap().is_some());}/// RULE (8 Nov 2026): a device whose founding the object refused (`vault_founded`: another device founded first) lets its wrap go, says so in words, and waits for a device that holds the vault; it never founds again.#[test]fn a_founding_the_object_refused_is_let_go_and_the_device_waits_in_words() {    let phone = phone();    phone.publish();    assert_eq!(phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) })).message, "Setting up this device's vault: it opens once Cotton has its key.");    phone.object_refuses_the_founding();    let refused = phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(        (refused.code.as_str(), refused.message.as_str()),        ("vault_not_wrapped_yet", "Another device set up this vault first. Waiting for it to let this device in.")    );    assert_eq!(phone.own_wrap(), None, "the minted key's wrap is gone");    assert_eq!(phone.count("SELECT COUNT(*) AS n FROM _parked WHERE tbl = 'cotton_vault_keys'"), 0, "the refused founding is not offered again");    let waiting = phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(waiting.code, "vault_not_wrapped_yet");    assert_eq!(phone.own_wrap(), None, "a vault another device holds is never founded again");}/// RULE (8 Nov 2026): every vault need founds — a passkey's CXF import with a lent key founds a signed-in copy that holds no wrap, as the unlock does, with no Keys › Devices first.#[test]fn a_first_passkey_import_with_a_lent_key_founds_the_vault() {    let phone = phone();    phone.publish();    let asked = json!({ "json": include_str!("../../../cotton-core/tests/fixtures/cxf/minimal.json"), "privateKey": b64(&device_secret()) });    let refused = crate::phone::passkeys::over(&phone.client, "passkey.importCxf", &asked).expect_err("the founding is still on its way");    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("vault_not_wrapped_yet", "Setting up this device's vault: it opens once Cotton has its key."));    assert!(phone.own_wrap().is_some(), "the import founded: a wrap for this device's own key");}const OBJECT_AUTHOR: &str = "device:01OBJECTSERVEDFOUNDER00000000";/// RULE (8 Nov 2026): a device's vault key is its public key, not its row id. A phone that founded before it signed in finds its founder row (its own public key, an older id) parked against its signed-in row; the next pass takes that wrap over its own row, ends the park, never founds again, and opens the vault once the object has the re-wrap.#[test]fn a_parked_pull_of_this_devices_own_founder_row_heals_and_the_vault_opens() {    let phone = phone();    phone.publish();    let public = b64(&wrap::public_of(&device_secret()));    let founded = wrap::wrap(&wrap::public_of(&device_secret()), fixture_vmk().expose()).expect("a wrap");    let now = cotton_client::seams::Clock::now(phone.clock.as_ref()).timestamp_millis();    let fact = cotton_tools::test_fixtures::author_fact(crate::fixture::WORKSPACE, OBJECT_AUTHOR, &stamp(now - 1_000, OBJECT_AUTHOR));    let fields = json!({        "id": "founder:synthetic-device-key",        "workspace_id": crate::fixture::WORKSPACE,        "device_id": phone.device(),        "public_key": public,        "wrapped_vmk": founded,        "vmk_version": 1,        "created_at": "2026-11-07T23:28:02.000Z",        "updated_at": "2026-11-07T23:28:02.000Z",    })    .as_object()    .cloned()    .expect("an object");    let change = cotton_store::mint::Change::create("cotton_vault_keys", "founder:synthetic-device-key", fields);    let op = cotton_tools::test_fixtures::peer_op(&change, &stamp(now, OBJECT_AUTHOR), OBJECT_AUTHOR, "mcp", "op-founder-row");    let ops = vec![fact, cotton_store::fixtures::signed_by_author(crate::fixture::WORKSPACE, op)];    // Pulled as a page is: the founder row collides with this device's own row and parks.    phone        .client        .with_writer(|file| {            let result = cotton_store::fold::fold_pulled_judged(file.driver, &ops, Some(now)).map_err(|error| error.to_string())?;            for rejection in &result.rejected {                let op = ops.iter().find(|op| op.op_id == rejection.op_id).expect("the refused op");                cotton_store::rejected::park(file.driver, op, cotton_store::rejected::Direction::Pull, cotton_store::rejected::Class::of_refusal(&rejection.reason), &rejection.reason, "2026-11-08T00:00:00.000Z")                    .map_err(|error| error.to_string())?;            }            Ok(())        })        .expect("the pull");    let parked = "SELECT COUNT(*) AS n FROM _parked WHERE direction = 'pull' AND tbl = 'cotton_vault_keys'";    assert_eq!(phone.count(parked), 1, "the collision parks, as on the standing phone");    assert_eq!(phone.own_wrap(), None);    // The pass's after-step takes the wrap the object holds for this device's own key.    assert!(vault::take_own_key(&phone.client).expect("taken"), "the founder row's wrap is this device's");    assert_eq!(phone.count(parked), 0, "the park ended");    assert_eq!(phone.own_wrap().as_deref(), Some(founded.as_str()), "the object's wrap, not a new founding");    assert_eq!(phone.count("SELECT COUNT(*) AS n FROM cotton_vault_keys WHERE device_id = (SELECT device_id FROM cotton_vault_keys WHERE wrapped_vmk IS NOT NULL)"), 1, "one row for this device");    assert!(!vault::take_own_key(&phone.client).expect("asked again"), "taken once");    // The re-wrap goes up; once the object has it, the vault opens.    phone.object_takes_the_key();    phone.ok("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(true));    assert_eq!(phone.own_wrap().as_deref(), Some(founded.as_str()), "never founded again");}/// RULE (8 Nov 2026): a copy standing local is not founded on need — it founds at the key's publish, as before (`founding::local_personal`) — and its wrap needs no object to take it.#[test]fn a_local_copy_is_not_founded_on_need() {    let (_dir, client, clock) = crate::shell::client::phone_tests::attached_on_a_clock_in("local");    let phone = Phone { _dir, client, clock };    phone.client.set_receipt_signer(Arc::new(cotton_store::signed::KeySigner::of_seed(9)));    phone.client.set_vault_public(&b64(&wrap::public_of(&device_secret())));    phone.exec(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)         VALUES ('vault-key-self', ?, ?, ?, NULL, 0, '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z')",        &[&phone.workspace(), &phone.device(), &b64(&wrap::public_of(&device_secret()))],    );    phone.ok("vault.keys", json!({}));    assert_eq!(phone.own_wrap(), None, "not founded on a need that holds no key");    // Its unlock holds the key and founds as the publish does (`secrets_app::tests::    // a_signed_out_phone_founds_its_own_vault_at_unlock`); this fixture's signer is not its device's, so the    // founding lands on another row and the unlock says how out, never "waiting" for ever.    assert_eq!(phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) })).code, "vault_needs_sign_in");}/// RULE (launch-ios on dev, 25 Nov 2026): a local copy holding a vault this phone has no key to (as after Sign out,/// or a reinstall that minted a new device key) is never a dead end: Unlock names it, and the Secrets gate offers/// Sign in and Getting in on a new phone. Nothing sealed is replaced.#[test]fn a_local_copy_whose_vault_this_phone_cannot_open_offers_a_way_out() {    let (_dir, client, clock) = crate::shell::client::phone_tests::attached_on_a_clock_in("local");    let phone = Phone { _dir, client, clock };    phone.client.set_receipt_signer(Arc::new(cotton_store::signed::KeySigner::of_seed(9)));    phone.wrapped();    // A new device key: the wrap was for the old one, so its publish cleared it (as `vault.publishKey` does).    phone.exec("UPDATE cotton_vault_keys SET public_key = ?, wrapped_vmk = NULL WHERE device_id = ?", &[&b64(&wrap::public_of(&[7u8; 32])), &phone.device()]);    assert_eq!(phone.own_wrap(), None);    let error = phone.refusal("vault.unlock", json!({ "privateKey": b64(&[7u8; 32]) }));    assert_eq!(error.code, "vault_needs_sign_in");    assert!(error.message.contains("Sign in"), "{}", error.message);    assert_eq!(phone.column("SELECT CAST(vmk_version AS TEXT) AS v FROM cotton_vault_state WHERE workspace_id = ?", &phone.workspace()).as_deref(), Some("1"), "the vault that holds the sealed rows is kept");    let gate = crate::phone::secrets_app::call(&phone.client, "secrets.gate", &json!({ "passcode": true })).unwrap();    assert_eq!(gate["stuck"]["acts"][0]["request"], json!({ "act": "sign_in" }));    assert_eq!(gate["stuck"]["acts"][1]["request"], json!({ "act": "open_page", "page": "recovery" }));    assert!(!gate["stuck"]["line"].as_str().unwrap().is_empty());}#[test]fn a_wrap_at_an_older_version_than_the_workspace_reads_as_waiting_too() {    let phone = phone();    phone.wrapped();    // A revoke rotated the workspace to v2 and this phone has not been    // re-wrapped yet. Its v1 key would open nothing that was re-sealed, and    // half a vault is worse than a named wait.    phone.exec(        "UPDATE cotton_vault_state SET vmk_version = 2 WHERE workspace_id = ?",        &[&phone.workspace()],    );    assert_eq!(        phone            .refusal(                "vault.unlock",                json!({ "privateKey": b64(&device_secret()) })            )            .code,        "vault_not_wrapped_yet"    );}#[test]fn the_wrong_private_key_is_named_a_mismatch_and_nothing_is_unlocked() {    let phone = phone();    phone.wrapped();    let error = phone.refusal("vault.unlock", json!({ "privateKey": b64(&[3u8; 32]) }));    assert_eq!(error.code, "vault_key_mismatch");    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(false));}#[test]fn unlocking_answers_the_instant_it_runs_out_and_the_status_agrees() {    let phone = phone();    phone.wrapped();    let answer = phone.unlock();    assert_eq!(answer["unlocked"], json!(true));    assert_eq!(        answer["until"],        json!("2026-09-08T10:05:00.000Z"),        "the fixed clock's start plus the five minutes the spec promises"    );    let status = phone.ok("vault.status", json!({}));    assert_eq!(status["unlocked"], json!(true));    assert_eq!(status["until"], answer["until"]);    assert_eq!(status["hasKey"], json!(true));    assert_eq!(status["wrapped"], json!(true));}#[test]fn a_private_key_never_appears_in_a_refusal() {    let phone = phone();    let secret = b64(&[7u8; 32]);    let error = phone.refusal("vault.unlock", json!({ "privateKey": secret.clone() }));    let printed = format!("{} {} {}", error.code, error.message, error.details);    assert!(        !printed.contains(&secret),        "a refusal written beside a private key must name the shape and nothing \         of what arrived: {printed}"    );}// ── vault.create, and what a list shows ────────────────────────────────────#[test]fn creating_a_login_seals_it_locally_and_the_row_carries_no_plaintext() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    let sealed = phone        .column("SELECT value_enc AS v FROM cotton_secrets WHERE id = ?", &id)        .expect("a sealed value");    assert!(        sealed.starts_with(seal::SEAL_PREFIX),        "the value is sealed under the vault's own scheme: {sealed}"    );    assert!(        !sealed.contains(PASSWORD),        "the password is in the row in the clear: {sealed}"    );    // And it opens with the key this phone is holding, for THIS row and no    // other — the associated data is the id and the version.    let opened = seal::open(&fixture_vmk(), &id, 1, &sealed).expect("it opens");    assert_eq!(        serde_json::from_slice::<Value>(&opened).expect("json"),        json!({ "kind": "login", "password": PASSWORD })    );    assert!(        seal::open(&fixture_vmk(), "another-id", 1, &sealed).is_none(),        "a sealed value is bound to its row"    );}// RULE: a phone seals only at the highest version the file holds; when a rotation folds in after its unlock it ends the session and asks for unlock again, never sealing under the retired key.#[test]fn device_seals_only_at_the_highest_version_it_holds_and_asks_for_unlock_after_a_rotation() {    let phone = phone();    phone.wrapped();    phone.unlock();    phone.create_login();    let rows = |phone: &Phone| phone.column("SELECT CAST(count(*) AS TEXT) AS v FROM cotton_secrets WHERE id != ?", "").unwrap_or_default();    let before = rows(&phone);    phone.exec(        "UPDATE cotton_vault_state SET vmk_version = 2 WHERE workspace_id = ?",        &[&phone.workspace()],    );    let error = phone.refusal(        "vault.create",        json!({ "kind": "login", "name": NAME, "fields": { "password": PASSWORD } }),    );    assert_eq!(error.code, "vault_rotated");    assert_eq!(rows(&phone), before, "nothing was sealed under the retired key");    assert_eq!(        phone.refusal("vault.create", json!({ "kind": "login", "name": NAME, "fields": { "password": PASSWORD } })).code,        "vault_locked",        "the session was ended"    );}// RULE: vault settings count values sealed under an older key the chain reaches and values under a key this vault no longer has, locked and unlocked alike.#[test]fn vault_settings_count_values_at_older_and_unreachable_versions() {    let phone = phone();    phone.wrapped();    phone.unlock();    let reached = phone.create_login();    let lost = phone.create_login();    let current = phone.create_login();    phone.ok("vault.lock", json!({}));    // Rotate 1 → 3 by hand: the device's wrap and the state move to a new key,    // version 1 is retired under it, and one value claims a version 2 no link    // names — a key this vault no longer has.    let newer = Vmk::from_bytes([9u8; 32]);    let workspace = phone.workspace();    let wrapped = wrap::wrap(&wrap::public_of(&device_secret()), newer.expose()).expect("a wrap");    phone.exec("UPDATE cotton_vault_state SET vmk_version = 3 WHERE workspace_id = ?", &[&workspace]);    phone.exec("UPDATE cotton_vault_keys SET wrapped_vmk = ?, vmk_version = 3 WHERE workspace_id = ?", &[&wrapped, &workspace]);    let link = cotton_core::vault::chain::retire(&fixture_vmk(), 1, &newer, 3, &workspace).expect("a link");    phone.exec(        "INSERT INTO cotton_vault_retired_keys (id, workspace_id, version, under_version, under_kcv, wrapped, retired_at, actor)         VALUES ('rk-1', ?, 1, 3, ?, ?, '2026-09-08T09:30:00.000Z', 'test')",        &[&workspace, &link.under_kcv, &link.wrapped],    );    phone.exec("UPDATE cotton_secrets SET vmk_version = 2 WHERE id = ?", &[&lost]);    phone.exec("UPDATE cotton_secrets SET vmk_version = 3 WHERE id = ?", &[&current]);    for unlocked in [false, true] {        if unlocked {            phone.unlock();        }        let status = phone.ok("vault.status", json!({}));        assert_eq!(status["unlocked"], json!(unlocked));        assert_eq!(status["olderCount"], json!(1), "unlocked {unlocked}: {status}");        assert_eq!(status["older"], json!([reached]), "unlocked {unlocked}");        assert_eq!(status["unreachableCount"], json!(1), "unlocked {unlocked}: {status}");        assert_eq!(status["unreachable"], json!([lost]), "unlocked {unlocked}");    }}/// A take-over by hand (slice 12): the backup knew the vault at version 1;/// the old Mac rotated to 2 after its last backup (K″, never seen by the/// backup) and the phone sealed a change under it; the new Mac's act mints/// 65537 and retires only version 1 under it. Answers (reached, lost, newer).fn taken_over_with_an_unbacked_version(phone: &Phone) -> (String, String, Vmk) {    phone.wrapped();    phone.unlock();    let reached = phone.create_login();    let lost = phone.create_login();    phone.ok("vault.lock", json!({}));    let newer = Vmk::from_bytes([9u8; 32]);    let workspace = phone.workspace();    let wrapped = wrap::wrap(&wrap::public_of(&device_secret()), newer.expose()).expect("a wrap");    phone.exec("UPDATE cotton_vault_state SET vmk_version = 65537 WHERE workspace_id = ?", &[&workspace]);    phone.exec("UPDATE cotton_vault_keys SET wrapped_vmk = ?, vmk_version = 65537 WHERE workspace_id = ?", &[&wrapped, &workspace]);    let link = cotton_core::vault::chain::retire(&fixture_vmk(), 1, &newer, 65537, &workspace).expect("a link");    phone.exec(        "INSERT INTO cotton_vault_retired_keys (id, workspace_id, version, under_version, under_kcv, wrapped, retired_at, actor)         VALUES ('rk-take-over', ?, 1, 65537, ?, ?, '2026-09-08T09:30:00.000Z', 'test')",        &[&workspace, &link.under_kcv, &link.wrapped],    );    // The outage change, sealed under K″ (version 2) — a key the backup never saw.    let unbacked = Vmk::from_bytes([5u8; 32]);    let sealed = seal::seal(&unbacked, &lost, 2, br#"{"kind":"login","password":"changed in the outage"}"#)        .expect("sealed under K''");    phone.exec("UPDATE cotton_secrets SET value_enc = ?, vmk_version = 2 WHERE id = ?", &[&sealed, &lost]);    (reached, lost, newer)}// RULE: a secret sealed under a key the backup never saw is listed as one this vault no longer has, and reveal refuses it by name without trying it under any other key.#[test]fn secret_sealed_under_a_key_the_backup_never_saw_is_listed_as_lost() {    let phone = phone();    let (reached, lost, _) = taken_over_with_an_unbacked_version(&phone);    phone.unlock();    let status = phone.ok("vault.status", json!({}));    assert_eq!(status["unreachable"], json!([lost]), "{status}");    assert_eq!(status["older"], json!([reached]), "{status}");    let error = phone.refusal("vault.reveal", json!({ "id": lost }));    assert_eq!(error.code, "vault_key_lost", "{}", error.message);    let opened = phone.ok("vault.reveal", json!({ "id": reached }));    assert!(opened.to_string().contains(PASSWORD), "the reached older value still opens");}// RULE: a phone's change sealed under an unbacked key during the outage is shown and counted as sealed under a key this vault no longer has, locked and unlocked.#[test]fn outage_seals_under_an_unbacked_key_are_listed_or_grafted() {    let phone = phone();    let (_, lost, _) = taken_over_with_an_unbacked_version(&phone);    for unlocked in [false, true] {        if unlocked {            phone.unlock();        }        let status = phone.ok("vault.status", json!({}));        assert_eq!(status["unreachableCount"], json!(1), "unlocked {unlocked}: {status}");        assert_eq!(status["unreachable"], json!([lost]), "unlocked {unlocked}");    }}#[test]fn creating_needs_the_vault_open_and_says_so_by_name() {    let phone = phone();    phone.wrapped();    let error = phone.refusal(        "vault.create",        json!({ "kind": "login", "name": NAME, "fields": { "password": PASSWORD } }),    );    assert_eq!(error.code, "vault_locked");}#[test]fn a_kind_the_vault_does_not_have_is_refused_before_anything_is_written() {    let phone = phone();    phone.wrapped();    phone.unlock();    let error = phone.refusal(        "vault.create",        json!({ "kind": "passport-ish", "name": NAME, "fields": { "number": "0000" } }),    );    assert_eq!(error.code, "bad_request");    assert_eq!(phone.read("read.secrets", &[])["secrets"], json!([]));}#[test]fn fields_that_do_not_match_the_kind_are_refused_without_naming_what_arrived() {    let phone = phone();    phone.wrapped();    phone.unlock();    // A login needs a password; this hands it a card's number.    let error = phone.refusal(        "vault.create",        json!({ "kind": "login", "name": NAME, "fields": { "number": PASSWORD } }),    );    assert_eq!(error.code, "bad_request");    assert!(        !format!("{} {}", error.message, error.details).contains(PASSWORD),        "the one parser standing beside a plaintext credential named it: {}",        error.message    );}#[test]fn the_list_shows_the_hint_and_never_a_fragment_of_the_value() {    let phone = phone();    phone.wrapped();    phone.unlock();    phone.create_login();    let answer = phone.read("read.secrets", &[]);    let row = &answer["secrets"][0];    assert_eq!(row["name"], json!(NAME));    assert_eq!(row["site"], json!(SITE));    assert_eq!(row["username"], json!(USERNAME));    assert_eq!(row["kind"], json!("login"));    assert_eq!(row["isSet"], json!(true));    assert_eq!(row["legacy"], json!(false));    assert_eq!(        row["hint"],        json!("D-42"),        "the last four characters of the password and nothing more"    );    // A sweep over the WHOLE serialised answer, not one key: the failure this    // guards against is a column arriving somewhere nobody was looking.    let printed = answer.to_string();    assert!(!printed.contains("value_enc") && !printed.contains("valueEnc"), "{printed}");    assert!(!printed.contains(PASSWORD), "{printed}");    // And no run of it longer than the hint either, so a truncated leak is    // caught too.    let window = 5;    for start in 0..=PASSWORD.len() - window {        let fragment = &PASSWORD[start..start + window];        assert!(            !printed.contains(fragment),            "the list carries {fragment:?} of the password"        );    }}#[test]fn the_list_counts_every_kind_including_the_ones_with_nothing_in_them() {    let phone = phone();    phone.wrapped();    phone.unlock();    phone.create_login();    let counts = phone.read("read.secrets", &[])["kinds"].clone();    assert_eq!(counts["login"], json!(1));    // A chip that vanishes when its list empties is a chip a person cannot find    // their way back to.    for empty in ["api_key", "note", "card", "identity", "document"] {        assert_eq!(counts[empty], json!(0), "{empty} is missing from the chips");    }}#[test]fn the_list_filters_by_kind_which_is_what_the_keys_screen_is() {    let phone = phone();    phone.wrapped();    phone.unlock();    phone.create_login();    phone.ok(        "vault.create",        json!({            "kind": "api_key",            "name": "Invented provider",            "service": "anthropic",            "fields": { "key": "sk-INVENTED-0000" },        }),    );    let keys = phone.read("read.secrets", &[("kind", json!("api_key"))]);    let names: Vec<&str> = keys["secrets"]        .as_array()        .expect("an array")        .iter()        .map(|row| row["name"].as_str().expect("a name"))        .collect();    assert_eq!(names, vec!["Invented provider"]);}#[test]fn search_runs_over_the_plain_columns_and_finds_a_word_half_typed() {    let phone = phone();    phone.wrapped();    phone.unlock();    phone.create_login();    let found = |query: &str| -> usize {        phone.read("read.secrets", &[("q", json!(query))])["secrets"]            .as_array()            .expect("an array")            .len()    };    assert_eq!(found("nowhere"), 1, "the name");    assert_eq!(found("portal.now"), 1, "the site, prefix-matched mid-word");    assert_eq!(found("nobo"), 1, "the username, while it is still being typed");    assert_eq!(found("zzz-nothing-here"), 0);    // THE PAYLOAD IS NOT INDEXED, which is the reason a search over passwords    // is safe to have at all.    assert_eq!(found(PASSWORD), 0, "the password is searchable");}// ── a document's password is not on the Passwords list ────────────────────//// The owner's call (2026-09-27): a document's password is only needed where// the document is, and ~125 of them buried his accounts. The read leaves them// out of the rows, the counts and the search; the secret itself is untouched.impl Phone {    /// One secret of `kind`, with its primary field set to an invented value.    fn create_kind(&self, kind: SecretKind, name: &str) -> String {        let mut fields = Map::new();        fields.insert(            kind.primary_field().to_string(),            json!(format!("INVENTED-{}-0000", kind.as_str())),        );        let answer = self.ok(            "vault.create",            json!({ "kind": kind.as_str(), "name": name, "fields": fields }),        );        answer["id"].as_str().expect("an id").to_string()    }    fn listed_kinds(&self, args: &[(&str, Value)]) -> Vec<String> {        self.read("read.secrets", args)["secrets"]            .as_array()            .expect("an array")            .iter()            .map(|row| row["kind"].as_str().expect("a kind").to_string())            .collect()    }}#[test]fn the_passwords_list_shows_every_kind_but_a_documents_password() {    // Exhaustive over the vault's kinds: the table IS the rule.    for kind in SecretKind::ALL {        let expected = !matches!(kind, SecretKind::Document);        assert_eq!(            vault::listed_on_passwords(kind),            expected,            "{} on the Passwords list",            kind.as_str()        );    }}#[test]fn a_mixed_vault_lists_and_counts_everything_but_the_document_passwords() {    let phone = phone();    phone.wrapped();    phone.unlock();    for kind in SecretKind::ALL {        phone.create_kind(kind, &format!("Invented {}", kind.as_str()));    }    phone.create_kind(SecretKind::Document, "Invented bank statement — March");    let answer = phone.read("read.secrets", &[]);    let mut kinds = phone.listed_kinds(&[]);    kinds.sort();    assert_eq!(kinds, vec!["address", "api_key", "card", "code", "file", "identity", "login", "note", "wifi"]);    let counts = &answer["kinds"];    for kind in SecretKind::ALL {        let expected = if vault::listed_on_passwords(kind) { 1 } else { 0 };        assert_eq!(counts[kind.as_str()], json!(expected), "{} count", kind.as_str());    }    // The map stays TOTAL: a client that refuses a partial one still reads it.    assert_eq!(counts.as_object().expect("an object").len(), SecretKind::ALL.len());}#[test]fn a_vault_holding_only_document_passwords_reads_as_empty_here() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_kind(SecretKind::Document, "Invented card statement — April");    let answer = phone.read("read.secrets", &[]);    assert_eq!(answer["secrets"], json!([]), "the empty state is what draws");    for kind in SecretKind::ALL {        assert_eq!(answer["kinds"][kind.as_str()], json!(0), "{}", kind.as_str());    }    // Asking for the kind by name does not bring it back either.    assert!(phone.listed_kinds(&[("kind", json!("document"))]).is_empty());    // NOTHING WAS DELETED: the secret is still there, on its own page.    assert_eq!(        phone.read("read.secret", &[("id", json!(id))])["secret"]["kind"],        json!("document")    );}#[test]fn an_empty_vault_is_still_an_empty_list_with_every_count_at_zero() {    let phone = phone();    phone.wrapped();    phone.unlock();    let answer = phone.read("read.secrets", &[]);    assert_eq!(answer["secrets"], json!([]));    for kind in SecretKind::ALL {        assert_eq!(answer["kinds"][kind.as_str()], json!(0), "{}", kind.as_str());    }}#[test]fn search_never_finds_a_documents_password() {    let phone = phone();    phone.wrapped();    phone.unlock();    phone.create_kind(SecretKind::Document, "Invented Bank savings statement");    phone.create_kind(SecretKind::Login, "Invented Bank netbanking");    assert_eq!(phone.listed_kinds(&[("q", json!("invented bank"))]), vec!["login"]);    assert!(phone.listed_kinds(&[("q", json!("statement"))]).is_empty());}// ── vault.reveal ───────────────────────────────────────────────────────────#[test]fn revealing_answers_the_typed_payload_and_stamps_when_it_was_used() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    let answer = phone.ok("vault.reveal", json!({ "id": id }));    assert_eq!(answer["id"], json!(id));    assert_eq!(        answer["payload"],        json!({ "kind": "login", "password": PASSWORD })    );    assert_eq!(        phone.column("SELECT last_used_at AS v FROM cotton_secrets WHERE id = ?", &id),        Some("2026-09-08T10:00:00.000Z".to_string()),        "a reveal is a use, and the row says when"    );}#[test]fn revealing_after_the_five_minutes_refuses_rather_than_quietly_working() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    phone.clock.advance(Duration::seconds(VAULT_UNLOCK_TTL_SECONDS + 1));    let error = phone.refusal("vault.reveal", json!({ "id": id }));    assert_eq!(error.code, "vault_locked");    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(false));}// RULE: Secrets locks after he LEAVES: kept while he is in the app, past the five minutes; as he leaves, held exactly as// long as Lock after says; a shut key is never reopened by keeping it.#[test]fn a_key_kept_while_in_the_app_outlives_five_minutes_and_leaving_holds_it_as_lock_after_says() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    for _ in 0..3 {        phone.clock.advance(Duration::seconds(240));        assert_eq!(phone.ok("vault.keep", json!({}))["open"], json!(true));    }    assert!(phone.ok("vault.reveal", json!({ "id": id }))["payload"].is_object(), "twelve minutes in the app, still open");    // Leaving with the default Lock after (5 minutes): held 5 minutes, then gone.    assert_eq!(phone.ok("vault.keep", json!({ "leaving": true }))["open"], json!(true));    phone.clock.advance(Duration::seconds(299));    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(true));    phone.clock.advance(Duration::seconds(2));    assert_eq!(phone.refusal("vault.reveal", json!({ "id": id })).code, "vault_locked");    assert_eq!(phone.ok("vault.keep", json!({}))["open"], json!(false), "keeping never reopens a shut key");}#[test]fn locking_by_hand_closes_it_immediately() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    assert_eq!(phone.ok("vault.lock", json!({}))["locked"], json!(true));    assert_eq!(        phone.refusal("vault.reveal", json!({ "id": id })).code,        "vault_locked"    );}#[test]fn revealing_a_row_still_sealed_under_the_old_key_says_which_wait_this_is() {    let phone = phone();    phone.wrapped();    phone.unlock();    // The shape the v5 scheme wrote — three base64 parts, no `v2:` prefix —    // standing in for a row the server's one-time sweep has not reached.    phone.exec(        "INSERT INTO cotton_secrets           (id, workspace_id, kind, name, service, value_enc, vmk_version, hint, created_at, updated_at)         VALUES ('legacy-1', ?, 'api_key', 'Invented old key', 'anthropic', 'AAAA:BBBB:CCCC', 0, '000f', ?, ?)",        &[&phone.workspace(), "2026-09-01T00:00:00.000Z", "2026-09-01T00:00:00.000Z"],    );    let error = phone.refusal("vault.reveal", json!({ "id": "legacy-1" }));    assert_eq!(error.code, "vault_sealed_under_the_old_key");    // And the list SAYS SO on the row, rather than offering a Reveal that    // refuses, and in the status line's count.    let answer = phone.read("read.secrets", &[("kind", json!("api_key"))]);    assert_eq!(answer["secrets"][0]["legacy"], json!(true));    assert_eq!(answer["status"]["legacyCount"], json!(1));}#[test]fn the_passwords_list_s_old_key_count_names_only_what_the_list_shows() {    let phone = phone();    phone.wrapped();    phone.unlock();    // Three rows still under the old key: an api key ON the list, a document    // password OFF it (#1027), and a login in the bin.    for (id, kind, trashed) in [        ("legacy-key", "api_key", Value::Null),        ("legacy-doc", "document", Value::Null),        ("legacy-binned", "login", json!("2026-09-02T00:00:00.000Z")),    ] {        phone.exec(            &format!(                "INSERT INTO cotton_secrets                   (id, workspace_id, kind, name, service, value_enc, vmk_version, hint,                    trashed_at, created_at, updated_at)                 VALUES (?, ?, '{kind}', 'Invented old row {id}', 'invented', 'AAAA:BBBB:CCCC', 0, '000f',                         {}, ?, ?)",                trashed                    .as_str()                    .map_or("NULL".to_string(), |at| format!("'{at}'"))            ),            &[id, &phone.workspace(), "2026-09-01T00:00:00.000Z", "2026-09-01T00:00:00.000Z"],        );    }    // The LIST's line counts what the list draws: one row on this side.    let listed = phone.read("read.secrets", &[]);    assert_eq!(listed["secrets"].as_array().expect("rows").len(), 1);    assert_eq!(listed["status"]["legacyCount"], json!(1));    // The bin's side counts the bin's row and nothing else.    let binned = phone.read("read.secrets", &[("trashed", json!(true))]);    assert_eq!(binned["secrets"].as_array().expect("rows").len(), 1);    assert_eq!(binned["status"]["legacyCount"], json!(1));    // Settings asks about the VAULT — the Mac's re-seal job is whole-vault, so    // the document password and the binned login count there.    assert_eq!(phone.ok("vault.status", json!({}))["legacyCount"], json!(3));    // And the document password's own page still says what it is.    let page = phone.read("read.secret", &[("id", json!("legacy-doc"))]);    assert_eq!(page["secret"]["legacy"], json!(true));    assert_eq!(page["status"]["legacyCount"], json!(3));}#[test]fn revealing_something_that_is_not_there_is_not_found() {    let phone = phone();    phone.wrapped();    phone.unlock();    assert_eq!(        phone            .refusal("vault.reveal", json!({ "id": "no-such-secret" }))            .code,        "not_found"    );}// ── vault.update ───────────────────────────────────────────────────────────#[test]fn renaming_needs_no_unlock_because_renaming_is_not_reading() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    phone.ok("vault.lock", json!({}));    let answer = phone.ok("vault.update", json!({ "id": id, "name": "Nowhere portal (old)" }));    assert_eq!(answer["changed"], json!(true));    assert_eq!(        phone.read("read.secret", &[("id", json!(id))])["secret"]["name"],        json!("Nowhere portal (old)")    );}#[test]fn changing_the_payload_does_need_the_vault_open_and_moves_the_hint_with_it() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    phone.ok("vault.lock", json!({}));    assert_eq!(        phone            .refusal(                "vault.update",                json!({ "id": id, "fields": { "password": "rotated-INVENTED-99" } })            )            .code,        "vault_locked"    );    phone.unlock();    phone.ok(        "vault.update",        json!({ "id": id, "fields": { "password": "rotated-INVENTED-99" } }),    );    assert_eq!(        phone.read("read.secret", &[("id", json!(id))])["secret"]["hint"],        json!("D-99"),        "the hint follows the value it is four characters of"    );    assert_eq!(        phone.ok("vault.reveal", json!({ "id": id }))["payload"]["password"],        json!("rotated-INVENTED-99")    );}#[test]fn an_update_never_changes_what_kind_a_secret_is() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    // A login that became a card would be a payload the page cannot draw and a    // hint taken from a field that is not there.    let error = phone.refusal(        "vault.update",        json!({ "id": id, "kind": "card", "fields": { "number": "4000-INVENTED" } }),    );    assert_eq!(error.code, "write_refused");    assert_eq!(        phone.read("read.secret", &[("id", json!(id))])["secret"]["kind"],        json!("login")    );}// ── the bin ────────────────────────────────────────────────────────────────/// RULE: Moving a password to the bin says so by name ("Moved <name> to the bin" while the Bin's tile is on Home, the default; "Deleted <name>" while it is not) and bringing it back says "Restored <name>".#[test]fn the_bin_takes_a_secret_out_of_the_list_and_restore_brings_it_back() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    let binned = phone.ok("vault.trash", json!({ "id": id }));    let name = phone.read("read.secrets", &[("trashed", json!(true))])["secrets"][0]["name"].as_str().map(str::to_string).expect("a name");    assert_eq!(binned["said"], json!(format!("Moved {name} to the bin")), "the Bin's tile is on Home by default: {binned}");    assert_eq!(phone.read("read.secrets", &[])["secrets"], json!([]));    assert_eq!(        phone.read("read.secrets", &[("trashed", json!(true))])["secrets"]            .as_array()            .expect("an array")            .len(),        1,        "it is in the bin, not gone — being wrong must cost a tap, not a password"    );    let restored = phone.ok("vault.restore", json!({ "id": id }));    assert_eq!(restored["said"], json!(format!("Restored {name}")), "{restored}");    assert_eq!(        phone.read("read.secrets", &[])["secrets"]            .as_array()            .expect("an array")            .len(),        1    );}/// RULE: The app's records.delete moves a password to the bin and says "Moved <name> to the bin" (the Bin's tile on Home, the default), and records.undo takes it back out with its fields and edited time as they were.#[test]fn records_delete_bins_a_password_and_records_undo_takes_it_back() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    let records = |method: &str, request: Value| {        crate::phone::records::call(&phone.client, method, &request)            .unwrap_or_else(|error| panic!("{method} refused: {} {}", error.code, error.message))    };    let was = records("records.get", json!({ "table": "secret", "id": id }));    phone.clock.advance(Duration::minutes(1));    let gone = records("records.delete", json!({ "table": "secret", "id": id }));    assert_eq!(gone["change"]["receipt"]["said"], json!(format!("Moved {NAME} to the bin")));    assert_eq!(gone["change"]["undoable"], json!(true), "{gone}");    assert_eq!(phone.read("read.secrets", &[])["secrets"], json!([]));    assert_eq!(        phone.read("read.secrets", &[("trashed", json!(true))])["secrets"]            .as_array()            .expect("an array")            .len(),        1,        "in the bin, not gone"    );    let undone = records("records.undo", json!({ "change_id": gone["change"]["id"] }));    assert_eq!(undone["change"]["receipt"]["said"], json!(format!("Put back {NAME}")));    assert_eq!(phone.read("read.secrets", &[])["secrets"].as_array().expect("an array").len(), 1);    let back = records("records.get", json!({ "table": "secret", "id": id }));    assert_eq!(back["data"], was["data"], "every field and its edited time as they were");}#[test]fn binning_something_that_is_not_there_is_not_found() {    let phone = phone();    assert_eq!(        phone.refusal("vault.trash", json!({ "id": "nothing" })).code,        "not_found"    );}// ── read.secret ────────────────────────────────────────────────────────────#[test]fn the_page_answers_the_plain_columns_and_never_the_payload() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    let answer = phone.read("read.secret", &[("id", json!(id))]);    assert_eq!(answer["secret"]["site"], json!(SITE));    assert_eq!(answer["placements"], json!([]));    assert_eq!(answer["projects"], json!([]));    assert_eq!(answer["status"]["unlocked"], json!(true));    let printed = answer.to_string();    assert!(!printed.contains(PASSWORD), "{printed}");    assert!(!printed.contains("value_enc") && !printed.contains("valueEnc"), "{printed}");}#[test]fn a_page_for_a_secret_that_is_gone_answers_nothing_rather_than_failing() {    let phone = phone();    assert_eq!(        phone.read("read.secret", &[("id", json!("no-such-secret"))])["secret"],        Value::Null    );}#[test]fn the_page_lists_the_machines_this_secret_is_written_onto() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    phone.exec(        "INSERT INTO cotton_secret_placements           (id, workspace_id, secret_id, device_id, path, mode, format, env_name, created_at, updated_at)         VALUES ('pl-1', ?, ?, 'invented-mac', '~/.config/nowhere/token', 384, 'raw', NULL, ?, ?)",        &[            &phone.workspace(),            &id,            "2026-09-01T00:00:00.000Z",            "2026-09-01T00:00:00.000Z",        ],    );    let placements = phone.read("read.secret", &[("id", json!(id))])["placements"].clone();    assert_eq!(placements[0]["path"], json!("~/.config/nowhere/token"));    assert_eq!(placements[0]["deviceId"], json!("invented-mac"));    assert_eq!(placements[0]["format"], json!("raw"));    // The applier's own bookkeeping says nothing a person reads.    assert_eq!(placements[0]["appliedHash"], Value::Null);}// ── the status line ────────────────────────────────────────────────────────#[test]fn a_phone_with_no_vault_key_reads_as_having_none_rather_than_as_broken() {    let phone = phone();    let status = phone.ok("vault.status", json!({}));    assert_eq!(status["hasKey"], json!(false));    assert_eq!(status["wrapped"], json!(false));    assert_eq!(status["unlocked"], json!(false));    assert_eq!(status["until"], Value::Null);    assert_eq!(status["legacyCount"], json!(0));}#[test]fn an_unknown_vault_method_is_named_rather_than_guessed_at() {    let phone = phone();    assert_eq!(        phone.refusal("vault.enumerate", json!({})).code,        "unknown_method"    );}// ── a device the server refused for good opens nothing ────────────────────#[test]fn a_refused_device_neither_unlocks_nor_reveals() {    // The app reads its copy under a banner; the vault is not part of what it    // reads. Both verbs answer the crate's sentence and the code the gate    // names, before a key is looked at.    let phone = phone();    let memory = Arc::new(cotton_client::transport::RefusalMemory::default());    memory.note(Some(cotton_client::transport::DeviceRefusal {        kind: cotton_client::transport::RefusalKind::NotApproved,        code: "device_not_approved".to_string(),        server_url: Some("https://server.invalid".to_string()),        server_name: None,        at: "2026-09-25T10:00:00.000Z".to_string(),        erase: false,        refuser: cotton_client::transport::Refuser::Unnamed,        serving_epoch: None,        device: None,    }));    phone.client.set_refusals(Some(memory));    let sentence = cotton_client::connection::terminal_device_sentence("device_not_approved")        .expect("a sentence");    let refused = phone.refusal(        "vault.unlock",        json!({ "privateKey": b64(&device_secret()) }),    );    assert_eq!(refused.code, vault::REFUSED_DEVICE);    assert_eq!(refused.message, sentence);    let refused = phone.refusal("vault.reveal", json!({ "id": "sec-1" }));    assert_eq!(refused.code, vault::REFUSED_DEVICE);    assert_eq!(refused.message, sentence);    // A create is a write and takes the same gate — proven where the gate    // is (`shell::client::phone_tests`); here the vault is locked first,    // which a refused device cannot change.}// ── the person key ─────────────────────────────────────────────────────────/// A person key from a fixed seed, so the fixture is reproducible. Nobody's.fn fixture_person_key() -> cotton_core::keys::PersonKey {    cotton_core::keys::PersonKey::from_seed(zeroize::Zeroizing::new([7u8; 32]))}/// Membership transport tests use the same locally unlocked person-key fixture.pub(crate) fn unlocked_person_client() -> (tempfile::TempDir, Arc<ClientController>, String) {    let phone = phone();    phone.wrapped();    let key = fixture_person_key();    let public = key.public_key();    let sealed = key.seal_private(&fixture_vmk(), 1).expect("a sealed half");    phone.person_key_row(&public, &sealed);    phone.unlock();    (phone._dir, phone.client, public)}impl Phone {    /// The row a serving Mac's first vault pass writes, as it reaches a phone.    fn person_key_row(&self, public_key: &str, sealed: &str) {        self.exec(            "INSERT INTO cotton_person_keys               (id, workspace_id, public_key, name, sealed_private, vmk_version, created_at)             VALUES (?, ?, ?, 'Nobody Invented', ?, 1, '2026-09-08T09:00:00.000Z')",            &[                &public_key[..cotton_core::keys::person::FINGERPRINT_LEN],                &self.workspace(),                public_key,                sealed,            ],        );    }}#[test]fn the_phone_signs_as_its_person_only_while_the_vault_is_unlocked() {    let phone = phone();    phone.wrapped();    let key = fixture_person_key();    let sealed = key.seal_private(&fixture_vmk(), 1).expect("a sealed half");    // Locked, and then unlocked with no row yet: two refusals, each by name.    let refused = vault::sign_as_person(&phone.client, b"a statement").expect_err("locked");    assert_eq!(refused.code, "vault_locked");    phone.unlock();    let refused = vault::sign_as_person(&phone.client, b"a statement").expect_err("no row");    assert_eq!(refused.code, "no_person_key");    phone.person_key_row(&key.public_key(), &sealed);    let (public_key, signature) =        vault::sign_as_person(&phone.client, b"a statement").expect("a signature");    assert_eq!(public_key, key.public_key());    assert!(cotton_core::keys::person::verify(&public_key, b"a statement", &signature));    assert!(!cotton_core::keys::person::verify(&public_key, b"another statement", &signature));    phone.ok("vault.lock", json!({}));    let refused = vault::sign_as_person(&phone.client, b"a statement").expect_err("locked again");    assert_eq!(refused.code, "vault_locked");}#[test]fn a_row_edited_to_name_another_person_signs_as_nobody() {    let phone = phone();    phone.wrapped();    phone.unlock();    let sealed = fixture_person_key()        .seal_private(&fixture_vmk(), 1)        .expect("a sealed half");    // The sealed half of one person under the public half of another.    let other = cotton_core::keys::PersonKey::from_seed(zeroize::Zeroizing::new([9u8; 32]));    phone.person_key_row(&other.public_key(), &sealed);    let refused = vault::sign_as_person(&phone.client, b"a statement").expect_err("refused");    assert_eq!(refused.code, "vault_stale");}fn ffi_sources(dir: &std::path::Path, found: &mut Vec<std::path::PathBuf>) {    for entry in std::fs::read_dir(dir).expect("the crate's source directory") {        let path = entry.expect("a directory entry").path();        if path.is_dir() {            ffi_sources(&path, found);        } else if path.extension().is_some_and(|extension| extension == "rs") {            found.push(path);        }    }}/// RULE: A person key's private half never crosses the FFI — only the phone vault's signing call reads `sealed_private`, that call is in no method table, and it answers a public key and a signature.#[test]fn person_key_private_half_never_crosses_ffi() {    let src = cotton_store::manifest::manifest_dir().join("src");    let mut sources = Vec::new();    ffi_sources(&src, &mut sources);    assert!(sources.len() > 50, "the scan found the crate's sources");    let column = ["sealed", "private"].join("_");    for path in &sources {        // phone/person_key.rs carries the sealed half between the copy and        // the object (window-phone), never to Swift: it is in no method        // table and opens the half only to check the object's key opens        // under this vault before the copy keeps it.        if path.ends_with("phone/vault.rs") || path.ends_with("phone/vault_tests.rs") || path.ends_with("phone/person_key.rs") || path.ends_with("phone/person_key_tests.rs") || path.ends_with("phone/unlock_tests.rs") {            continue;        }        let text = std::fs::read_to_string(path).expect("a source file");        assert!(            !text.contains(&column),            "{} reads `{column}`: only the phone vault's signing call may",            path.display()        );    }    // Inside the vault's own file the column is read in ONE function, and the    // dispatch never names that function — it is called from Rust alone.    let text = std::fs::read_to_string(src.join("phone/vault.rs")).expect("the vault's source");    let start = text        .find("pub(crate) fn sign_as_person(")        .expect("the signing call");    let end = start + text[start..].find("\n}\n").expect("the call's end");    for (at, _) in text.match_indices(&column) {        assert!(            (start..end).contains(&at),            "`{column}` is read outside the signing call, at byte {at}"        );    }    assert_eq!(        text.matches("sign_as_person(").count(),        1,        "the signing call is defined once and routed by no method"    );    assert!(        text[start..end].contains("Result<(String, [u8; 64]), MethodError>"),        "the signing call answers a public key and a signature, nothing else"    );    for &method in crate::methods::ALL_METHODS {        let name = method.to_lowercase();        assert!(            !name.contains("personkey") && !name.contains("signas"),            "`{method}` would be a person key method: signing is a Rust call"        );    }}// ── a client machine's key reaches the serving side ────────────────────────// ── placing a secret on a Mac, from the phone ──────────────────────────────#[test]fn a_phone_puts_a_secret_on_a_mac_and_the_row_says_where() {    let phone = phone();    phone.wrapped();    phone.unlock();    let secret = phone.create_login();    phone.ok("vault.lock", json!({}));    // Locked: writing WHERE a secret goes opens nothing.    let placed = phone.ok(        "vault.place",        json!({ "secretId": secret, "deviceId": "mac-1", "path": "~/.cotton-credentials/forgejo/token" }),    );    let id = placed["id"].as_str().expect("an id").to_string();    assert_eq!(        phone.column("SELECT path || '|' || format || '|' || mode || '|' || device_id AS v FROM cotton_secret_placements WHERE id = ?", &id),        Some("~/.cotton-credentials/forgejo/token|raw|384|mac-1".to_string())    );    // The same Mac and path again is the same row.    let again = phone.ok(        "vault.place",        json!({ "secretId": secret, "deviceId": "mac-1", "path": "~/.cotton-credentials/forgejo/token" }),    );    assert_eq!(again["id"], placed["id"]);    phone.ok("vault.unplace", json!({ "id": id }));    assert_eq!(        phone.column(            "SELECT id AS v FROM cotton_secret_placements WHERE id = ?",            &id        ),        None    );}#[test]fn a_placement_the_mac_would_refuse_is_refused_on_the_phone() {    let phone = phone();    let outside = phone.refusal(        "vault.place",        json!({ "secretId": "s", "deviceId": "mac-1", "path": "/etc/hosts" }),    );    assert_eq!(outside.code, "bad_request");    let nothing = phone.refusal(        "vault.place",        json!({ "secretId": "no-such-secret", "deviceId": "mac-1", "path": "~/x" }),    );    assert!(        nothing.message.contains("no such secret"),        "{}",        nothing.message    );}/// An op's stamp: its time, a counter and its author, as the object mints it.fn stamp(ms: i64, author: &str) -> String {    format!("{ms:013}:0000:{author}")}/// RULE: A phone reads the target Mac's synced failure without holding the Mac's vault key or pass, because only that Mac knows why its placement could not apply.#[test]fn a_phone_reads_the_target_macs_synced_placement_problem() {    let phone = phone();    phone.wrapped();    phone.unlock();    let id = phone.create_login();    phone.exec(        "INSERT INTO cotton_secret_placements (id, workspace_id, secret_id, device_id, path, apply_problem, created_at, updated_at)         VALUES ('problem-on-mac', ?, ?, ?, '~/phone-test/token', 'this Mac cannot open the passwords', ?, ?)",        &[&phone.workspace(), &id, &phone.device(), "2026-09-01T00:00:00.000Z", "2026-09-01T00:00:00.000Z"],    );    phone.ok("vault.lock", json!({}));    let page = phone.read("read.secret", &[("id", json!(id))]);    assert_eq!(        page["placements"][0]["problem"],        json!("this Mac cannot open the passwords")    );    let line = format!("Can't put {NAME} on this Mac · this Mac cannot open the passwords");    assert_eq!(page["placements"][0]["problemLine"], json!(line));    let devices = phone.read("read.devices", &[]);    let row = devices["devices"]        .as_array()        .unwrap()        .iter()        .find(|row| row["deviceId"] == phone.device())        .unwrap();    assert_eq!(row["columns"]["placement_problems"], json!(line));    assert!(!serde_json::to_string(&page).unwrap().contains(PASSWORD));}// ── the devices waiting for the vault ──────────────────────────────────────/// Another device's key: invented, as every key here is.const OTHER_DEVICE: &str = "mac-importer-invented";fn other_secret() -> [u8; 32] {    [27u8; 32]}impl Phone {    /// A device that published its key and waits: a row with no wrap.    fn pending_device(&self) {        let now = "2026-09-08T09:30:00.000Z";        self.exec(            "INSERT INTO cotton_vault_keys               (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)             VALUES ('vk-other', ?, ?, ?, NULL, 0, ?, ?)",            &[&self.workspace(), OTHER_DEVICE, &b64(&wrap::public_of(&other_secret())), now, now],        );    }    fn queued_for(&self, row: &str) -> usize {        self.client            .with_writer(|replica| {                Ok(replica                    .driver                    .all(                        "SELECT op_id FROM _outbox WHERE tbl = 'cotton_vault_keys' AND row_id = ?",                        &[rusqlite::types::Value::Text(row.to_string())],                    )                    .map_err(|error| error.to_string())?                    .len())            })            .expect("the outbox")    }}#[test]fn the_devices_list_puts_a_waiting_device_first_and_names_no_key() {    let phone = phone();    phone.wrapped();    phone.pending_device();    let listed = phone.ok("vault.keys", json!({}));    let devices = listed["devices"].as_array().expect("devices");    assert_eq!(devices.len(), 2);    assert_eq!(devices[0]["deviceId"], json!(OTHER_DEVICE));    assert_eq!(devices[0]["pending"], json!(true));    assert_eq!(devices[1]["pending"], json!(false));    assert_eq!(        devices[0]["fingerprint"],        json!(wrap::fingerprint(&b64(&wrap::public_of(&other_secret()))))    );    assert_eq!(listed["thisDevice"], json!(phone.device()));    assert!(!listed.to_string().contains("w1:"), "never a wrap");}// RULE (19 Nov 2026): no device is let into the vault on a tap. vault.approveDevice is refused// code_needed, with the key lent or the vault open, and writes nothing: a device comes in only by the typed-code compare// of a sign-in ask (signin.approve) or a sibling over the checked channel (signin.approveSibling).#[test]fn approve_device_is_refused_and_writes_nothing() {    let phone = phone();    phone.wrapped();    phone.pending_device();    let lent = phone.refusal("vault.approveDevice", json!({ "deviceId": OTHER_DEVICE, "privateKey": b64(&device_secret()) }));    assert_eq!(lent.code, "code_needed");    assert_eq!(lent.message, "A new device gets in when you scan the code it shows: tap Approve on its card here.");    assert!(!lent.message.contains(&b64(&device_secret())));    phone.unlock();    assert_eq!(phone.refusal("vault.approveDevice", json!({ "deviceId": OTHER_DEVICE })).code, "code_needed", "an open vault is no tap either");    assert!(phone.column("SELECT wrapped_vmk AS v FROM cotton_vault_keys WHERE id = ?", "vk-other").is_none());    assert_eq!(phone.queued_for("vk-other"), 0, "nothing goes up");}#[test]fn refusing_a_waiting_device_removes_its_row_and_syncs_the_removal() {    let phone = phone();    phone.wrapped();    phone.pending_device();    assert_eq!(        phone.refusal("vault.refuseDevice", json!({ "deviceId": phone.device() })).code,        "approved_stays"    );    let answer = phone.ok("vault.refuseDevice", json!({ "deviceId": OTHER_DEVICE }));    assert_eq!(answer["removed"], json!(true));    assert!(phone        .column("SELECT id AS v FROM cotton_vault_keys WHERE id = ?", "vk-other")        .is_none());    assert_eq!(phone.queued_for("vk-other"), 1);    assert_eq!(        phone.refusal("vault.refuseDevice", json!({ "deviceId": OTHER_DEVICE })).code,        "no_such_device"    );}#[test]fn publishing_names_the_device_once_the_copy_holds_the_objects_name_column() {    let phone = phone();    let public = b64(&wrap::public_of(&device_secret()));    // A fresh copy has no name column: the key lands, the name waits.    let first = phone.ok("vault.publishKey", json!({ "publicKey": public, "name": "Owner's phone" }));    assert_eq!(first["changed"], json!(true));    // The object's vault_key.name, as a pull adds it to the copy.    phone.exec(        &format!(            "ALTER TABLE \"cotton_vault_keys\" ADD COLUMN \"name\" TEXT {}",            cotton_store::schema::package_shape::SERVED_MARK        ),        &[],    );    let named = phone.ok("vault.publishKey", json!({ "publicKey": public, "name": "Owner's phone" }));    assert_eq!(named["changed"], json!(true), "the name is written once the column is there");    let row = named["databases"][0]["id"].as_str().expect("the row").to_string();    assert_eq!(        phone.column("SELECT name AS v FROM cotton_vault_keys WHERE id = ?", &row),        Some("Owner's phone".to_string())    );    let again = phone.ok("vault.publishKey", json!({ "publicKey": public, "name": "Owner's phone" }));    assert_eq!(again["changed"], json!(false));    let listed = phone.ok("vault.keys", json!({}));    assert_eq!(listed["devices"][0]["name"], json!("Owner's phone"));}/// The vault's own methods, as a device's handle runs a command's method.struct VaultMethods<'a>(&'a ClientController);impl crate::phone::records::AppMethods for VaultMethods<'_> {    fn call(&self, method: &str, request: &Value) -> Result<Value, crate::methods::MethodError> {        vault::over(self.0, method, request)    }}impl Phone {    /// Keys › Devices' Approve on the waiting device's row, as the deck runs it.    fn approve_from_the_list(&self, key: Option<&str>) -> Result<Value, crate::methods::MethodError> {        let request = json!({"table": "vault_key", "id": "vk-other", "command": "approve", "privateKey": key});        match key {            Some(_) => {                let lent = request["privateKey"].clone();                crate::phone::records::command(&self.client, &request, &crate::phone::records::KeyLent { methods: VaultMethods(&self.client), key: &lent })            }            None => crate::phone::records::command(&self.client, &request, &VaultMethods(&self.client)),        }    }}// RULE (19 Nov 2026; was Cotton Keys, 8 Nov 2026): Approve on a Devices row still runs// vault.approveDevice with the lent key, and is refused code_needed with nothing written: the row's line says how a// device is let in now.#[test]fn approve_on_a_devices_row_is_refused_with_the_line_saying_how() {    let phone = phone();    phone.wrapped();    phone.pending_device();    let refused = phone.approve_from_the_list(Some(&b64(&device_secret()))).expect_err("no tap lets a device in");    assert!(refused.message.contains("scan the code it shows"), "{} {}", refused.code, refused.message);    assert!(!refused.message.contains(&b64(&device_secret())), "the key never rides the answer");    assert!(phone.column("SELECT wrapped_vmk AS v FROM cotton_vault_keys WHERE id = ?", "vk-other").is_none());    assert_eq!(phone.ok("vault.status", json!({}))["unlocked"], json!(false), "nothing is held afterwards");}// RULE (Cotton Keys, 8 Nov 2026): a device key's row reads with its fingerprint, computed on the phone from the row's public half exactly as vault.keys says it; the waiting device's row shows the fingerprint the owner checks against that device's own screen.#[test]fn a_device_keys_row_reads_with_its_fingerprint() {    let phone = phone();    phone.wrapped();    phone.pending_device();    let listed = crate::phone::records::call(&phone.client, "records.list", &json!({"table": "vault_key"})).expect("the list reads");    let other = listed["records"].as_array().expect("rows").iter().find(|row| row["data"]["device_id"] == OTHER_DEVICE).cloned().expect("the waiting row");    assert_eq!(other["data"]["fingerprint"], json!(wrap::fingerprint(&b64(&wrap::public_of(&other_secret()))).expect("a fingerprint")));    let keys = phone.ok("vault.keys", json!({}));    assert_eq!(keys["devices"][0]["fingerprint"], other["data"]["fingerprint"]);}/// RULE (12 Nov 2026: Messages Dev founded over the vault Keys held): founding mints a new vault master key, so a copy that cannot tell an unfounded vault from one it has not read never founds: not before a pull has landed since launch, and not in an app whose kit does not sync `vault_key`. Its need publishes its key and waits for a device that holds the vault.#[test]fn a_copy_that_has_not_read_the_objects_vault_rows_never_founds() {    let (dir, client, clock) = attached_on_a_clock();    let phone = Phone { _dir: dir, client, clock };    phone.publish();    let first = phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(first.code, "vault_not_wrapped_yet");    assert_eq!(phone.own_wrap(), None, "no pull has landed: nothing is founded");    let keys = phone.ok("vault.keys", json!({}));    assert_eq!(phone.own_wrap(), None, "the Devices list founds nothing either: {keys}");    phone.client.note_pull_for_test("2026-09-08T09:00:00.000Z");    assert_eq!(phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) })).code, "vault_not_wrapped_yet");    assert!(phone.own_wrap().is_some(), "once it has read the object's rows and found none, the need founds");}// ── the approval card (`vault.approval`) ───────────────────────────────────// RULE (GETTING-IN.md, 22 Nov 2026): one card. A holder is asked by the new device's own ask on `signin.asks`// ("Your Mac wants to sign in to your Cotton", Approve to scan, Not me), so this card no longer says "asks to read// your private records" with only Refuse: its `waiting` is always null, whoever waits.#[test]fn a_holder_is_asked_by_the_one_card_not_this_one() {    let phone = phone();    phone.wrapped();    phone.pending_device();    let card = phone.ok("vault.approval", json!({}));    assert_eq!(card["waiting"], Value::Null);    assert_eq!(card["mine"], Value::Null, "a holder asks nobody");    assert_eq!(card["pollSeconds"], Value::Null);}#[test]fn a_refused_device_is_asked_about_no_more() {    let phone = phone();    phone.wrapped();    phone.pending_device();    phone.ok("vault.refuseDevice", json!({ "deviceId": OTHER_DEVICE }));    assert_eq!(phone.ok("vault.approval", json!({}))["waiting"], Value::Null);}// RULE: a device waiting on another that holds the vault says so, opens the waiting page, and syncs while it waits; a// device with no wrap is never asked to approve anyone; a lone founding waits on the object, not on a person.#[test]fn a_joining_device_shows_its_code_and_waits_for_a_holder() {    let phone = phone();    let now = "2026-09-08T09:00:00.000Z";    phone.exec(        "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at) VALUES (?, 1, ?, ?, ?)",        &[&phone.workspace(), now, now, now],    );    let mine = b64(&wrap::public_of(&device_secret()));    phone.exec(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)         VALUES ('vk-me', ?, ?, ?, NULL, 0, ?, ?)",        &[&phone.workspace(), &phone.device(), &mine, now, now],    );    let alone = phone.ok("vault.approval", json!({}));    assert_eq!((alone["mine"].clone(), alone["waiting"].clone()), (Value::Null, Value::Null), "a lone founding asks no person");    let theirs = wrap::wrap(&wrap::public_of(&other_secret()), fixture_vmk().expose()).expect("a wrap");    phone.exec(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)         VALUES ('vk-holder', ?, ?, ?, ?, 1, ?, ?)",        &[&phone.workspace(), OTHER_DEVICE, &b64(&wrap::public_of(&other_secret())), &theirs, now, now],    );    let card = phone.ok("vault.approval", json!({}));    assert_eq!(card["mine"]["deviceId"], json!(phone.device()));    assert_eq!(card["mine"]["line"], json!("Your things from other devices aren't here yet."));    assert_eq!(card["mine"]["act"], json!("Bring them here"), "the act opens the waiting page, which asks by itself");    assert_eq!(card["mine"]["ask"], json!("Bring them here"), "kept for a shell from before the page, whose button asks");    assert_eq!(card["mine"]["fingerprint"], Value::Null);    assert_eq!(card["pollSeconds"], json!(super::super::vault_approval::POLL_SECONDS));    assert_eq!(card["waiting"], Value::Null, "a device with no wrap approves nobody");    let wrapped = wrap::wrap(&wrap::public_of(&device_secret()), fixture_vmk().expose()).expect("a wrap");    phone.exec("UPDATE cotton_vault_keys SET wrapped_vmk = ?, vmk_version = 1 WHERE id = 'vk-me'", &[&wrapped]);    let let_in = phone.ok("vault.approval", json!({}));    assert_eq!((let_in["mine"].clone(), let_in["pollSeconds"].clone()), (Value::Null, Value::Null), "let in, it waits no more");}/// RULE (15 Nov 2026): `seal.status` says `founds` only where a vault need would found the/// vault (a new person's first sign-in: signed in, the object's vault rows read, none wrapped and no data key), so a/// shell founds there with no question; a copy that has not read the rows, or whose object holds a vault, never does.#[test]fn seal_status_says_founds_only_where_a_need_would_found() {    let (dir, client, clock) = attached_on_a_clock();    let unread = Phone { _dir: dir, client, clock };    assert_eq!(unread.seal_status()["founds"], json!(false), "no pull has landed: it cannot tell");    let fresh = phone();    let status = fresh.seal_status();    assert_eq!((status["needsKey"].clone(), status["founds"].clone()), (json!(true), json!(true)), "{status}");    fresh.publish();    assert_eq!(fresh.seal_status()["founds"], json!(true), "its own published key is no vault yet");    let first = fresh.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(first.code, "vault_not_wrapped_yet", "founded, on its way to the object");    assert_eq!(fresh.seal_status()["founds"], json!(true), "its own founding on its way still founds: asked again, no question");    let joining = phone();    joining.pending_device();    joining.exec("UPDATE cotton_vault_keys SET wrapped_vmk = 'w', vmk_version = 1 WHERE id = 'vk-other'", &[]);    joining.exec(        "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at) VALUES (?, 1, ?, ?, ?)",        &[&joining.workspace(), "2026-09-08T09:00:00.000Z", "2026-09-08T09:00:00.000Z", "2026-09-08T09:00:00.000Z"],    );    assert_eq!(joining.seal_status()["founds"], json!(false), "a vault another device holds is joined, not founded");}/// RULE (GETTING-IN.md step 2, walk on dev 22 Nov 2026): a signed-in device whose other device holds the vault is told/// `joins`, so its shell publishes this device's key with no question and the waiting page stands by itself. Before,/// the Android shell waited for a tap on Unlock, so a new phone signed in and sat on "locked on this phone" with no/// request made and no page. Never on a new person's first sign-in (`founds`), a copy that has not read the vault's/// rows, or a device that holds its own wrap.#[test]fn seal_status_says_joins_where_another_device_holds_the_vault() {    let (dir, client, clock) = attached_on_a_clock();    let unread = Phone { _dir: dir, client, clock };    assert_eq!(unread.seal_status()["joins"], json!(false), "no pull has landed: it cannot tell");    let fresh = phone();    assert_eq!(fresh.seal_status()["joins"], json!(false), "a first sign-in founds, it joins nobody");    let joining = phone();    joining.exec(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at) VALUES ('vk-other', ?, ?, 'pub', 'w', 1, ?, ?)",        &[&joining.workspace(), OTHER_DEVICE, "2026-09-08T09:00:00.000Z", "2026-09-08T09:00:00.000Z"],    );    let status = joining.seal_status();    assert_eq!((status["needsKey"].clone(), status["founds"].clone(), status["joins"].clone()), (json!(true), json!(false), json!(true)), "{status}");    joining.publish();    assert_eq!(joining.seal_status()["joins"], json!(true), "its own key published, no wrap yet: it still waits");    let card = joining.ok("vault.approval", json!({}));    assert!(card["mine"].is_object(), "published and waiting: the waiting page has its line {card}");    // Waiting, an empty list says the slim line and nothing says "Loading your data…" (walk on dev, 22 Nov 2026).    assert_eq!(crate::phone::getting_in::waiting_line(&joining.client).as_deref(), Some("Your things from other devices aren't here yet."));    joining.exec("UPDATE cotton_vault_keys SET wrapped_vmk = 'w' WHERE device_id = ?", &[&joining.device()]);    assert_eq!(joining.seal_status()["joins"], json!(false), "it holds its own wrap: nothing to join");    assert_eq!(crate::phone::getting_in::waiting_line(&joining.client), None, "let in, it waits no more");}impl Phone {    fn seal_status(&self) -> Value {        crate::phone::seal::call_on(&self.client, "seal.status", &json!({})).unwrap_or_else(|error| panic!("seal.status refused: {} {}", error.code, error.message))    }}/// RULE (iPhone walk, 23 Nov 2026): whether a copy knows its vault is asked of the database attached now. Signed out/// of one number and into another in the same run, the fresh copy took the earlier number's pass as its own, founded/// a second vault over the one the person's other device holds, and stood on "Unlock" after that device said yes.#[test]fn a_pass_of_another_number_never_lets_a_fresh_copy_found() {    let (dir, client, clock) = attached_on_a_clock();    client.note_pull_of_another_database_for_test("2026-11-23T20:08:00.000Z");    let phone = Phone { _dir: dir, client, clock };    phone.publish();    let refused = phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_ne!(refused.message, "Setting up this device's vault: it opens once Cotton has its key.", "it founded");    assert_eq!(phone.own_wrap(), None, "no second vault from a pass of another number");    // Once a pass for THIS database came, the copy knows the vault (here, none) and founds as before.    phone.client.note_pull_for_test("2026-11-23T20:10:30.000Z");    let first = phone.refusal("vault.unlock", json!({ "privateKey": b64(&device_secret()) }));    assert_eq!(first.code, "vault_not_wrapped_yet");    assert!(phone.own_wrap().is_some());}/// RULE (iPhone walk, 23 Nov 2026): a copy that has had no pass for its database and holds no device's key row says/// nothing about a locked key: it cannot tell yet whether it founds, waits or unlocks.#[test]fn a_copy_before_its_first_pass_says_no_locked_line() {    let (dir, client, clock) = attached_on_a_clock();    client.note_pull_of_another_database_for_test("2026-11-23T20:08:00.000Z");    let blind = Phone { _dir: dir, client, clock };    let status = blind.seal_status();    assert_eq!(status["said"], Value::Null, "{status}");    // Its own key published at the sign-in, still no pass: still nothing said.    blind.publish();    let status = blind.seal_status();    assert_eq!(status["said"], Value::Null, "own row published, nothing pulled: {status}");    // Another device holds the vault and this one has no wrap: it joins, and waits on the page with no locked line.    let joining = phone();    joining.exec(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at) VALUES ('vk-other', ?, ?, 'pub', 'w', 1, ?, ?)",        &[&joining.workspace(), OTHER_DEVICE, "2026-09-08T09:00:00.000Z", "2026-09-08T09:00:00.000Z"],    );    let status = joining.seal_status();    assert_eq!((status["joins"].clone(), status["said"].clone()), (json!(true), Value::Null), "{status}");    // Its own wrap here and the key not open: that is the one locked line, with Unlock.    joining.publish();    joining.exec("UPDATE cotton_vault_keys SET wrapped_vmk = 'w' WHERE device_id = ?", &[&joining.device()]);    let status = joining.seal_status();    assert!(status["said"]["line"].is_string() && status["said"]["act"] == "Unlock", "{status}");}/// GETTING IN REVIEW (coordinator, 26 Nov 2026, after 564e491564): the status's `joins` (no locked line: "the page/// will ask") and the page's own `getting_in::waits` (the page shows) are decided by two pieces of code. Where `joins`/// holds and `waits` does not, a signed-in phone has sealed data, no key and no ask: the "Loading your data…" lock-out./// Every state of this device's row (none, unwrapped, wrapped) against another device's (none, unwrapped, wrapped):/// whenever `joins` holds, the page shows.#[test]fn whenever_the_status_says_joins_the_getting_in_page_shows() {    use cotton_client::vault::devices;    for own in ["none", "unwrapped", "wrapped"] {        for other in ["none", "unwrapped", "wrapped"] {            let phone = phone();            let workspace = phone.workspace();            let device = phone.device();            let row = |id: &str, device: &str, public: &[u8; 32], wrapped: bool| {                let wrap = if wrapped { wrap::wrap(&wrap::public_of(public), fixture_vmk().expose()).expect("a wrap") } else { String::new() };                phone.exec(                    "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)                     VALUES (?, ?, ?, ?, NULLIF(?, ''), CASE WHEN ? = '' THEN 0 ELSE 1 END, '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z')",                    &[id, &workspace, device, &b64(&wrap::public_of(public)), &wrap, &wrap],                );            };            match own {                "unwrapped" => row("vk-own", &device, &device_secret(), false),                "wrapped" => row("vk-own", &device, &device_secret(), true),                _ => {}            }            match other {                "unwrapped" => row("vk-other", "another-device", &[5u8; 32], false),                "wrapped" => row("vk-other", "another-device", &[5u8; 32], true),                _ => {}            }            let joins = vault::joins_here(&phone.client).expect("joins");            let keys = phone.client.with_file(|replica| devices::keys(replica.driver, replica.workspace_id)).expect("the keys");            let page = crate::phone::getting_in::waits(phone.client.self_device_id().as_deref(), &keys);            assert_eq!(joins, page, "own {own}, other {other}: joins={joins} but the page shows={page}");            // The one state that joins: another holds the key and this device does not, its row published or not.            assert_eq!(joins, other == "wrapped" && own != "wrapped", "own {own}, other {other}");        }    }}/// GETTING IN REVIEW: a phone whose own row is wrapped for a key it no longer holds (its keychain item lost and/// minted again, the same device id) neither joins nor waits until it says its new key; saying it (the iPhone at/// every launch, Android at Unlock) clears the stale wrap, and then it joins and the page asks.#[test]fn a_stale_wrap_for_a_lost_key_is_cleared_by_the_new_key_and_the_page_asks() {    use cotton_client::vault::devices;    let phone = phone();    phone.wrapped();    let workspace = phone.workspace();    let held = wrap::wrap(&wrap::public_of(&[5u8; 32]), fixture_vmk().expose()).expect("a wrap");    phone.exec(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)         VALUES ('vk-other', ?, 'another-device', ?, ?, 1, '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z')",        &[&workspace, &b64(&wrap::public_of(&[5u8; 32])), &held],    );    let waits = || {        let keys = phone.client.with_file(|replica| devices::keys(replica.driver, replica.workspace_id)).expect("the keys");        crate::phone::getting_in::waits(phone.client.self_device_id().as_deref(), &keys)    };    assert!(!vault::joins_here(&phone.client).unwrap() && !waits(), "a wrap of its own, stale or not, is not a wait");    // The new key, as the shell says it: the stale wrap goes, and the page asks.    phone.ok("vault.publishKey", json!({ "publicKey": b64(&wrap::public_of(&[9u8; 32])) }));    assert_eq!(phone.own_wrap(), None, "the wrap for the lost key is cleared");    assert!(vault::joins_here(&phone.client).unwrap(), "now it joins");    assert!(waits(), "and the getting-in page asks");}