//! `unlock.*` over a real attached copy and a scripted object door, on a//! fixed clock. Synthetic keys and rows only.use std::sync::Arc;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engineas _;use serde_json::{json, Value};use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_core::keys::PersonKey;use cotton_core::seal::grant::{open_grant, verify_grant, Grant};use cotton_core::seal::DataKey;use cotton_core::vault::{wrap, Vmk};usesuper::call_on;usecrate::phone::personal_object::ObjectDoor;usecrate::shell::client::phone_tests::attached_on_a_clock;usecrate::shell::client::ClientController;pub(crate) fn device_secret() -> [u8; 32] { std::array::from_fn(|i| i as u8)}pub(crate) fn fixture_vmk() -> Vmk {Vmk::from_bytes(std::array::from_fn(|i| 200u8.wrapping_sub(i as u8)))}fn worker_secret() -> [u8; 32] { [9; 32]}pub(crate) fn door(replies: implIntoIterator<Item = Reply>) -> (ObjectDoor, Arc<ScriptedExchange>) {let exchange = ScriptedExchange::new(replies);let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: "cred-phone".into() }; (door, exchange)}pub(crate) fn exec(client: &ClientController, sql: &str, params: &[&str]) { client .with_writer(|replica| {let bound: Vec<rusqlite::types::Value> = params.iter().map(|v| rusqlite::types::Value::Text((*v).to_string())).collect(); replica.driver.run(sql, &bound).map(|_| ()).map_err(|error| error.to_string()) }) .expect("the seed");}fn workspace(client: &ClientController) -> String { client.with_writer(|replica| Ok(replica.workspace_id.to_string())).expect("the workspace")}/// This device's wrap of the fixture vault key, at version 1.pub(crate) fn wrapped(client: &ClientController) {let now = "2026-11-11T08:00:00.000Z";let ws = workspace(client); exec(client, "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at) VALUES (?, 1, ?, ?, ?)", &[&ws, now, now, now]);let public = wrap::public_of(&device_secret());let wrapped = wrap::wrap(&public, fixture_vmk().expose()).expect("a wrap");let device = client.self_device_id().expect("a device id"); exec( client,"INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at) VALUES ('vk-1', ?, ?, ?, ?, 1, ?, ?)", &[&ws, &device, &URL_SAFE_NO_PAD.encode(public), &wrapped, now, now], );}/// A person key sealed under the fixture vault key, in the copy.fn person(client: &ClientController) -> PersonKey {let key = PersonKey::from_seed(zeroize::Zeroizing::new([5; 32]));let sealed = key.seal_private(&fixture_vmk(), 1).expect("sealed"); exec(client, "INSERT INTO cotton_person_keys (id, workspace_id, public_key, sealed_private, vmk_version, created_at) VALUES (?, ?, ?, ?, 1, '2026-11-11T08:00:00.000Z')", &[&key.fingerprint(), &workspace(client), &key.public_key(), &sealed]); key}/// The object's rows as a pull lays them in the served tables.fn served(client: &ClientController, sql: &str) {let file = rusqlite::Connection::open(client.layout().replica(&client.current_database().unwrap())).expect("the copy"); file.execute_batch(sql).expect("served rows");}fn request_row(client: &ClientController, state: &str) {let worker_pub = URL_SAFE_NO_PAD.encode(wrap::public_of(&worker_secret())); served( client, &format!("CREATE TABLE IF NOT EXISTS cotton_unlock_request (id TEXT PRIMARY KEY, workspace_id TEXT, token_id TEXT, token_name TEXT, client TEXT, tables TEXT, reason TEXT, minutes REAL, worker_pub TEXT, requested_at TEXT, expires_at TEXT, state TEXT); INSERT INTO cotton_unlock_request VALUES ('req-1', 'w', 'tok-1', 'Claude', 'Claude (claude.ai)', '[\"sealed_diary\",\"note\"]', 'To find what Asha wrote.', 15, '{worker_pub}', '2026-11-11T08:59:00.000Z', '2099-01-01T00:00:00.000Z', '{state}');" ), );}fn body(exchange: &ScriptedExchange, n: usize) -> Value { serde_json::from_slice(&exchange.nth(n).body).expect("json")}/// GOLDEN: the card comes from the waiting request, and the phone polls fast while one waits.#[test]fn the_card_is_the_waiting_request_and_the_phone_polls_while_it_waits() {let (_dir, client, _clock) = attached_on_a_clock(); assert_eq!(call_on(&client, "unlock.card", &json!({})).unwrap(), json!({"card": null, "pollSeconds": null})); request_row(&client, "waiting");let answer = call_on(&client, "unlock.card", &json!({})).unwrap(); assert_eq!(answer["pollSeconds"], 5); assert_eq!(answer["card"]["requestId"], "req-1");// The title names what is asked as groups a person knows (owner, 23 Nov 2026), never a table by its name. assert_eq!(answer["card"]["title"], "Let Claude (claude.ai) read some of what you keep?"); assert_eq!(answer["card"]["tables"][1], json!({"table": "note", "label": "Notes", "on": true})); assert_eq!(answer["card"]["face"], "unlock.card"); assert_eq!(answer["card"]["fields"]["title"], answer["card"]["title"], "the face's title place is the card's title"); assert_eq!(answer["card"]["acts"][0]["label"], "Allow");}/// RULE (12 Nov 2026): the card names a table the object defines by the object's own plural (a table the owner made, or one the object added), not its id; a table the kit ships still reads the kit's plural.#[test]fn the_card_names_an_object_defined_table_by_its_plural() {let (_dir, client, _clock) = attached_on_a_clock(); request_row(&client, "waiting");let definition = json!({"format_version": 1, "id": "sealed_diary", "name": "Sealed diary", "plural": "Sealed diaries", "columns": [{"key": "body", "type": "longtext"}]}).to_string(); served( &client, &format!("INSERT OR REPLACE INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at, _hlc) VALUES ('sealed_diary', '{}', '{definition}', 0, 0, '2026-11-11', '2026-11-11', '0001762851600000:0001:{}')",crate::fixture::WORKSPACE, cotton_client::transport::object::OBJECT_AUTHOR ), );let answer = call_on(&client, "unlock.card", &json!({})).unwrap(); assert_eq!(answer["card"]["tables"][0], json!({"table": "sealed_diary", "label": "Sealed diaries", "on": true}), "{answer}"); assert_eq!(answer["card"]["tables"][1]["label"], "Notes");}/// RULE (12 Nov 2026): a table this copy keeps nowhere (a Keys copy keeps only its kit's definitions, and the owner made sealed_diary) is named by the plural in the object's last served answer the passes hold, not its id.#[test]fn the_card_names_a_table_the_copy_keeps_nowhere_by_the_objects_served_plural() {let (_dir, client, _clock) = attached_on_a_clock(); request_row(&client, "waiting");let held = cotton_client::transport::object::HeldDefinitions::new();let served = [json!({"id": "sealed_diary", "name": "Sealed diary", "plural": "Sealed diaries"}), json!({"id": "note", "plural": "Notes"})]; held.name(served.iter()); client.set_served_definitions(Some(held));let answer = call_on(&client, "unlock.card", &json!({})).unwrap(); assert_eq!(answer["card"]["tables"][0]["label"], "Sealed diaries", "{answer}"); client.set_served_definitions(None);}/// RULE: Allow opens the vault for that call alone, builds the grant from every key version up to the table's current one, signs it with the person key, posts unlock_allow, and leaves no vault session open; the object's half opens it and verifies the signature.#[test]fn allow_posts_a_grant_the_object_opens_and_verifies_and_keeps_no_vault_open() {let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap(); wrapped(&client);let key = person(&client); request_row(&client, "waiting");// sealed_diary has moved to version 2 already.let file = rusqlite::Connection::open(client.layout().replica(&database)).unwrap(); cotton_client::seal::write_notes(&file, &[cotton_client::seal::Note::Key { id: "v:sealed_diary".into(), data: json!({"v": 2}).as_object().unwrap().clone() }]).unwrap(); drop(file);// No data key held and the copy has not yet read the object's seal_key rows: refused by name, nothing posted.let (object, exchange) = door([Reply::ok(r#"{"grant":"g-1","ends_at":"2026-11-11T09:20:00.000Z"}"#)]); client.set_object_door(Some(Arc::new(object)));let secret = URL_SAFE_NO_PAD.encode(device_secret()); assert_eq!(call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "privateKey": secret})).unwrap_err().code, "seal_key_not_learned"); assert_eq!(exchange.calls(), 0);// The object's DK row, as a pull keeps it: the allow opens it with the vault key it opened, and holds it.let (dk, row) = cotton_client::seal::mint_data_key(&fixture_vmk(), 1, "2026-11-11T09:00:00.000Z").unwrap();let file = rusqlite::Connection::open(client.layout().replica(&database)).unwrap(); cotton_client::seal::write_notes(&file, &[cotton_client::seal::Note::Key { id: "dk".into(), data: row }]).unwrap(); drop(file); assert_eq!(call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "tables": ["mail"], "privateKey": secret})).unwrap_err().code, "bad_tables"); assert_eq!(call_on(&client, "unlock.allow", &json!({"requestId": "nope", "privateKey": secret})).unwrap_err().code, "request_not_waiting");// A vault session the owner opened earlier is closed by the allow too. client.vault().unwrap().unlock(fixture_vmk(), 1, client.now());let answer = call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "tables": ["sealed_diary", "note"], "minutes": 60, "privateKey": secret})).expect("allowed"); assert_eq!(answer, json!({"grantId": "g-1", "endsAt": "2026-11-11T09:20:00.000Z", "tables": ["note", "sealed_diary"], "minutes": 60}));let posted = body(&exchange, 0); assert_eq!(posted["act"], "unlock_allow");let args = &posted["args"]; assert!(!exchange.nth(0).body.windows(secret.len()).any(|w| w == secret.as_bytes()), "the vault key never leaves");let grant = Grant { tables: vec!["note".into(), "sealed_diary".into()], minutes: 60, wrapped: args["wrapped"].as_str().unwrap().into(), signer: args["signer"].as_str().unwrap().into(), sig: args["sig"].as_str().unwrap().into(), }; assert_eq!(grant.signer, key.fingerprint()); assert!(verify_grant(&key.public_key(), &database, "req-1", "tok-1", &grant), "the person key signed this grant");let bundle = open_grant(&worker_secret(), "req-1", "tok-1", &grant.tables, &grant.wrapped).expect("the object opens it"); assert_eq!(bundle.keys["sealed_diary"].keys().copied().collect::<Vec<_>>(), vec![1, 2], "every version up to the current one"); assert_eq!(bundle.keys["note"].keys().copied().collect::<Vec<_>>(), vec![1]); assert!(client.vault().unwrap().until(client.now()).is_none(), "no vault session is left open");use cotton_client::seal::DataKeyStoreas _; assert_eq!(client.data_keys().data_key(&database).unwrap().map(|k| *k.expose()), Some(*dk.expose()), "the DK opened by the allow is held for the sealer"); client.set_object_door(None);}/// RULE: a phone that holds no data key and whose copy has read every seal_key row and found none mints it on Allow (the first vault device mints it), keeps its wrap on the object once, then posts the grant.#[test]fn allow_on_a_database_with_no_data_key_mints_it_first() {let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap(); wrapped(&client); person(&client); request_row(&client, "waiting");// The sync loop's sealer, as a pull that reached the object's end leaves it (the transport holds it while the copy is attached).let sealer = crate::phone::personal_object::sealer_of(&client, &database); sealer.learned_all(); client.note_pull_for_test("2026-11-11T09:00:00.000Z");let (object, exchange) = door([Reply::ok(r#"{"made":{"table":"seal_key","id":"dk"}}"#), Reply::ok(r#"{"grant":"g-1","ends_at":"2026-11-11T09:20:00.000Z"}"#)]); client.set_object_door(Some(Arc::new(object))); call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "privateKey": URL_SAFE_NO_PAD.encode(device_secret())})).expect("allowed");let minted = body(&exchange, 0); assert_eq!((minted["act"].as_str(), minted["args"]["table"].as_str(), minted["args"]["id"].as_str()), (Some("create"), Some("seal_key"), Some("dk")));let row = minted["args"]["data"].as_object().unwrap().clone();let opened = cotton_client::seal::open_data_key(&fixture_vmk(), 1, &row).expect("the kept wrap opens with the vault key");use cotton_client::seal::DataKeyStoreas _; assert_eq!(client.data_keys().data_key(&database).unwrap().map(|k| *k.expose()), Some(*opened.expose()), "the minted DK is the one held"); assert_eq!(body(&exchange, 1)["act"], "unlock_allow"); client.set_object_door(None); drop(sealer);}/// RULE: after a window ends, each table the phone handed keys for moves to its next seal version once; decline and end are one post each.#[test]fn an_ended_window_advances_each_handed_table_once_and_decline_and_end_post_their_acts() {let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap(); wrapped(&client); person(&client); request_row(&client, "waiting"); client.data_keys().hold(&database, &DataKey::from_bytes([7; 32]));let (object, exchange) = door([Reply::ok(r#"{"grant":"g-1","ends_at":"2026-11-11T09:20:00.000Z"}"#),Reply::ok(r#"{"made":{"table":"seal_key","id":"v:note"}}"#),Reply::ok(r#"{"made":{"table":"seal_key","id":"v:sealed_diary"}}"#),Reply::ok("{}"),Reply::ok("{}"), ]); client.set_object_door(Some(Arc::new(object))); call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "privateKey": URL_SAFE_NO_PAD.encode(device_secret())})).expect("allowed"); served(&client, "CREATE TABLE cotton_unlock_grant (id TEXT PRIMARY KEY, workspace_id TEXT, request_id TEXT, tables TEXT, ends_at TEXT, ended_at TEXT, ended_by TEXT); INSERT INTO cotton_unlock_grant VALUES ('g-1', 'w', 'req-1', '[\"note\",\"sealed_diary\"]', '2099-01-01T00:00:00.000Z', NULL, NULL);"); assert_eq!(call_on(&client, "unlock.windows", &json!({})).unwrap()["windows"], json!([{"grantId": "g-1", "requestId": "req-1", "tables": ["note", "sealed_diary"], "endsAt": "2099-01-01T00:00:00.000Z", "said": "Notes and sealed_diary · 633902 hours left", "client": null, "standing": false, "connectionId": null}])); assert_eq!(call_on(&client, "unlock.windows", &json!({})).unwrap()["heading"], "Open access", "the list's own title is the core's line"); assert!(super::advance_ended(&client).unwrap().is_empty(), "nothing moves while the window is open");// The sync loop holds the database's sealer for its passes.let sync_loops = crate::phone::personal_object::sealer_of(&client, &database); served(&client, "UPDATE cotton_unlock_grant SET ended_at = '2026-11-11T09:05:00.000Z', ended_by = 'phone'"); assert_eq!(super::advance_ended(&client).unwrap(), vec!["note".to_string(), "sealed_diary".to_string()]); assert_eq!(body(&exchange, 1), json!({"act": "create", "args": {"table": "seal_key", "id": "v:note", "data": {"v": 2}}})); assert_eq!(body(&exchange, 2), json!({"act": "create", "args": {"table": "seal_key", "id": "v:sealed_diary", "data": {"v": 2}}})); assert_eq!(sync_loops.version("note"), 2, "the sync loop's sealer seals under the new version at once"); assert!(super::advance_ended(&client).unwrap().is_empty(), "once"); assert_eq!(exchange.calls(), 3); call_on(&client, "unlock.decline", &json!({"requestId": "req-2"})).unwrap(); assert_eq!(body(&exchange, 3), json!({"act": "unlock_decline", "args": {"request_id": "req-2"}})); call_on(&client, "unlock.end", &json!({"grantId": "g-1"})).unwrap(); assert_eq!(body(&exchange, 4), json!({"act": "unlock_end", "args": {"grant_id": "g-1"}})); client.set_object_door(None);}/// RULE (12 Nov 2026): the first Allow on a device whose vault is not founded yet founds it and is HELD, not refused: the card says the setting-up line with no act to tap, a pass that has not landed the founding keeps it, and the pass that lands it posts the grant with no second tap; the held key goes with it.#[test]fn the_first_allow_on_an_unfounded_vault_is_held_and_completed_by_the_pass_that_lands_the_founding() {let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap(); request_row(&client, "waiting");let sealer = crate::phone::personal_object::sealer_of(&client, &database); sealer.learned_all(); client.note_pull_for_test("2026-11-11T09:00:00.000Z");// The founding's first open: the object holds no person key (made and published) and no data key (minted), then the grant.let (object, exchange) = door([Reply::ok(r#"{"rows":[]}"#),Reply::ok(r#"{"made":{"table":"person_key"}}"#),Reply::ok(r#"{"made":{"table":"seal_key","id":"dk"}}"#),Reply::ok(r#"{"grant":"g-1","ends_at":"2026-11-11T09:20:00.000Z"}"#), ]); client.set_object_door(Some(Arc::new(object)));let held = call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "tables": ["sealed_diary"], "minutes": 60, "privateKey": URL_SAFE_NO_PAD.encode(device_secret())})).expect("held, not refused"); assert_eq!(held, json!({"held": true, "requestId": "req-1", "said": "Setting up your account… The window opens by itself once this is done."})); assert_eq!(exchange.calls(), 0, "nothing is posted while the founding waits");let card = call_on(&client, "unlock.card", &json!({})).unwrap(); assert_eq!(card["card"]["status"], held["said"]); assert_eq!(card["card"]["acts"], json!([]), "no second tap to make");super::complete_held(&client); assert_eq!(exchange.calls(), 0, "a pass that has not landed the founding keeps the Allow held"); assert!(client.unlock_held().is_some());// The pass lands the founding: the object takes the vault key writes. exec(&client, "DELETE FROM _outbox WHERE tbl = 'cotton_vault_keys'", &[]);super::complete_held(&client);let posted = body(&exchange, 3); assert_eq!(posted["act"], "unlock_allow", "the held Allow is posted by the pass"); assert_eq!((posted["args"]["tables"].clone(), posted["args"]["minutes"].clone()), (json!(["sealed_diary"]), json!(60)), "as the person chose on the card"); assert!(client.unlock_held().is_none(), "the held key is dropped once posted"); assert!(client.vault().unwrap().until(client.now()).is_none(), "no vault session is left open"); client.set_object_door(None); drop(sealer);}/// The scripted door, reading the card at the moment the held Allow goes up.#[derive(Debug)]structPeekingAtThePost { inner: Arc<ScriptedExchange>, client: std::sync::Mutex<std::sync::Weak<ClientController>>, seen: std::sync::Mutex<Vec<Value>>,}impl cotton_client::transport::ExchangeforPeekingAtThePost {fn send(&self, origin: &cotton_client::transport::Origin, request: &cotton_client::transport::http1::Http1Request<'_>, ceiling: std::time::Duration) -> Result<Box<dyn cotton_client::transport::Answer>, String> {let posting = request.body.is_some_and(|body| String::from_utf8_lossy(body).contains("unlock_allow"));let client = self.client.lock().unwrap().upgrade();iflet (true, Some(client)) = (posting, client) {self.seen.lock().unwrap().push(call_on(&client, "unlock.card", &json!({})).unwrap()); }self.inner.send(origin, request, ceiling) }fn send_stream(&self, origin: &cotton_client::transport::Origin, request: &cotton_client::transport::http1::Http1Request<'_>, body: &mutdyn std::io::Read, length: u64, ceiling: std::time::Duration) -> Result<Box<dyn cotton_client::transport::Answer>, String> {self.inner.send_stream(origin, request, body, length, ceiling) }}/// RULE (12 Nov 2026): while the pass posts the held Allow, the card still says the setting-up line with no act to tap: on Keys Dev the card gave Allow and Not now back for the second and a half the post took, between the setting-up line and the open window.#[test]fn a_held_allow_offers_no_act_while_its_grant_goes_up() {let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap(); request_row(&client, "waiting");let sealer = crate::phone::personal_object::sealer_of(&client, &database); sealer.learned_all(); client.note_pull_for_test("2026-11-11T09:00:00.000Z");let inner = ScriptedExchange::new([Reply::ok(r#"{"rows":[]}"#),Reply::ok(r#"{"made":{"table":"person_key"}}"#),Reply::ok(r#"{"made":{"table":"seal_key","id":"dk"}}"#),Reply::ok(r#"{"grant":"g-1","ends_at":"2026-11-11T09:20:00.000Z"}"#), ]);let peeking = Arc::new(PeekingAtThePost { inner, client: std::sync::Mutex::new(Arc::downgrade(&client)), seen: std::sync::Mutex::new(Vec::new()) });let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: peeking.clone(), credential: "cred-phone".into() }; client.set_object_door(Some(Arc::new(door)));let held = call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "tables": ["sealed_diary"], "minutes": 60, "privateKey": URL_SAFE_NO_PAD.encode(device_secret())})).expect("held, not refused"); exec(&client, "DELETE FROM _outbox WHERE tbl = 'cotton_vault_keys'", &[]);super::complete_held(&client);let seen = peeking.seen.lock().unwrap().clone(); assert_eq!(seen.len(), 1, "the card was read once, as the grant went up"); assert_eq!(seen[0]["card"]["status"], held["said"], "{}", seen[0]); assert_eq!(seen[0]["card"]["acts"], json!([]), "no act while the grant goes up: {}", seen[0]); assert!(client.unlock_held().is_none(), "the held key is dropped once posted"); client.set_object_door(None); drop(sealer);}/// RULE (12 Nov 2026): a held Allow lives only within its request's life: once the request is answered elsewhere, declined or expired, the pass drops it (its key wiped) and posts nothing.#[test]fn a_held_allow_whose_request_stopped_waiting_is_dropped_unposted() {let (_dir, client, _clock) = attached_on_a_clock(); client.note_pull_for_test("2026-11-11T09:00:00.000Z"); request_row(&client, "waiting");let (object, exchange) = door([]); client.set_object_door(Some(Arc::new(object))); assert_eq!(call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "privateKey": URL_SAFE_NO_PAD.encode(device_secret())})).unwrap()["held"], true); served(&client, "UPDATE cotton_unlock_request SET state = 'declined'"); exec(&client, "DELETE FROM _outbox WHERE tbl = 'cotton_vault_keys'", &[]);super::complete_held(&client); assert!(client.unlock_held().is_none()); assert_eq!(exchange.calls(), 0); client.set_object_door(None);}/// RULE (ruling R4, 15 Nov 2026): the card, the open windows and the read log stand in every Cotton app, not only one whose kit carries unlock_request: a Journal phone shows the card with its four durations, a standing window says it stays until turned off with the assistant's name, Allow takes the person's pick over the suggestion, and the reads come newest first.#[test]fn every_app_shows_the_card_windows_and_reads_and_allow_takes_any_duration() {let (_dir, client, _clock) = attached_on_a_clock();let journal = cotton_core::kit::AppKit::named("journal").expect("the journal kit ships"); assert!(!journal.tables.iter().any(|t| t == "unlock_request"), "Journal's kit does not carry the request");for table in ["unlock_request", "unlock_grant", "assistant_read"] { assert!(journal.pulled().iter().any(|t| t == table) && journal.keeps_table(table), "every app pulls and keeps {table}"); } cotton_core::kit::AppKit::keep(Some(&journal), client.layout().root()).expect("kept"); request_row(&client, "waiting");let card = call_on(&client, "unlock.card", &json!({})).unwrap(); assert_eq!(card["pollSeconds"], 5); assert_eq!(card["card"]["minutes"], 15); assert_eq!( card["card"]["durations"], json!([ {"minutes": 15, "label": "15 minutes", "on": true}, {"minutes": 60, "label": "1 hour", "on": false}, {"minutes": 1440, "label": "1 day", "on": false}, {"minutes": 0, "label": "Until I turn it off", "on": false}, ]) ); served( &client,"CREATE TABLE cotton_unlock_grant (id TEXT PRIMARY KEY, workspace_id TEXT, request_id TEXT, tables TEXT, ends_at TEXT, ended_at TEXT, ended_by TEXT, standing INTEGER, client TEXT, connection_id TEXT); INSERT INTO cotton_unlock_grant VALUES ('g-1', 'w', 'req-0', '[\"note\"]', '9999-12-31T23:59:59.999Z', NULL, NULL, 1, 'Claude (claude.ai)', 'conn-1'); INSERT INTO cotton_unlock_grant VALUES ('g-0', 'w', 'req-9', '[\"note\"]', '9999-12-31T23:59:59.999Z', '2026-11-11T08:00:00.000Z', 'phone', 1, 'Claude (claude.ai)', 'conn-1'); CREATE TABLE cotton_assistant_read (id TEXT PRIMARY KEY, workspace_id TEXT, grant_id TEXT, client TEXT, tables TEXT, tool TEXT, rows REAL, read_at TEXT); INSERT INTO cotton_assistant_read VALUES ('a-1', 'w', 'g-1', 'Claude (claude.ai)', '[\"note\"]', 'list_records', 12, '2026-11-11T08:00:00.000Z'); INSERT INTO cotton_assistant_read VALUES ('a-2', 'w', 'g-1', 'Claude (claude.ai)', '[\"note\"]', 'get_record', 1, '2099-01-01T00:00:00.000Z');", );let windows = call_on(&client, "unlock.windows", &json!({})).unwrap(); assert_eq!( windows["windows"], json!([{"grantId": "g-1", "requestId": "req-0", "tables": ["note"], "endsAt": "9999-12-31T23:59:59.999Z", "said": "Notes · until you turn it off", "client": "Claude (claude.ai)", "standing": true, "connectionId": "conn-1"}]),"an ended standing grant is gone" ); assert_eq!(windows["acts"][0]["label"], "End");let reads = call_on(&client, "unlock.reads", &json!({})).unwrap(); assert_eq!(reads["heading"], "What assistants read");let ids: Vec<&str> = reads["reads"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect(); assert_eq!(ids, ["a-2", "a-1"], "newest first"); assert!(reads["reads"][1]["said"].as_str().unwrap().starts_with("Claude (claude.ai) read 12 items from Notes · "), "{reads}");// The person's pick wins over the suggestion: a standing grant on a request that suggested 15. wrapped(&client); person(&client); client.data_keys().hold(&client.current_database().unwrap(), &DataKey::from_bytes([7; 32]));let (object, exchange) = door([Reply::ok(r#"{"grant":"g-2","ends_at":"9999-12-31T23:59:59.999Z"}"#)]); client.set_object_door(Some(Arc::new(object)));let secret = URL_SAFE_NO_PAD.encode(device_secret()); assert_eq!(call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "minutes": 30, "privateKey": secret})).unwrap_err().code, "bad_minutes");let answer = call_on(&client, "unlock.allow", &json!({"requestId": "req-1", "minutes": 0, "privateKey": secret})).expect("allowed"); assert_eq!(answer["minutes"], 0); assert_eq!(body(&exchange, 0)["args"]["minutes"], 0); client.set_object_door(None);}/// RULE: Allow on the one card for your Claude posts assistant_allow: the tables left on wrapped to the member key, the rest withheld with saved secrets, the policy and member key signed by the person key; no duration, no vault left open. After a pass the phone hands a table the grant lacks on its own, with the data key it holds.#[test]fn the_account_card_grants_the_member_key_and_the_pass_tops_it_up() {use cotton_core::seal::agent::{open_agent_wrap, verify_agent_grant, AgentGrant};let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap(); wrapped(&client);let key = person(&client);let member_pub = URL_SAFE_NO_PAD.encode(wrap::public_of(&worker_secret())); served( &client, &format!("CREATE TABLE IF NOT EXISTS cotton_unlock_request (id TEXT PRIMARY KEY, workspace_id TEXT, token_id TEXT, token_name TEXT, client TEXT, tables TEXT, reason TEXT, minutes REAL, worker_pub TEXT, requested_at TEXT, expires_at TEXT, state TEXT, account INTEGER, member_id TEXT, member_pub TEXT); INSERT INTO cotton_unlock_request VALUES ('req-a', 'w', 'tok-1', 'coordinator', 'Claude', '[\"note\",\"sealed_diary\",\"money_entry\"]', 'Let your Claude read your data', 0, '{member_pub}', '2026-11-11T08:59:00.000Z', '2099-01-01T00:00:00.000Z', 'waiting', 1, 'mem-1', '{member_pub}');" ), );let (dk, row) = cotton_client::seal::mint_data_key(&fixture_vmk(), 1, "2026-11-11T09:00:00.000Z").unwrap();let file = rusqlite::Connection::open(client.layout().replica(&database)).unwrap(); cotton_client::seal::write_notes(&file, &[cotton_client::seal::Note::Key { id: "dk".into(), data: row }]).unwrap(); drop(file);let card = call_on(&client, "unlock.card", &json!({})).unwrap(); assert_eq!(card["card"]["title"], "Let your Claude read your data"); assert_eq!(card["card"]["durations"], json!([]));let (object, exchange) = door([Reply::ok(r#"{"grant":"g-a","member":"mem-1"}"#), Reply::ok(r#"{}"#)]); client.set_object_door(Some(Arc::new(object)));let secret = URL_SAFE_NO_PAD.encode(device_secret());let answer = call_on(&client, "unlock.allow", &json!({"requestId": "req-a", "tables": ["note", "sealed_diary"], "minutes": 15, "privateKey": secret})).expect("allowed"); assert_eq!(answer["grantId"], "g-a");let posted = body(&exchange, 0); assert_eq!(posted["act"], "assistant_allow");let args = &posted["args"]; assert_eq!(args["withheld"], json!(["code_credential", "money_entry", "passkey", "secret"]));let grant = AgentGrant { withheld: serde_json::from_value(args["withheld"].clone()).unwrap(), wrapped: args["wrapped"].as_str().unwrap().into(), signer: args["signer"].as_str().unwrap().into(), sig: args["sig"].as_str().unwrap().into(), }; assert!(verify_agent_grant(&key.public_key(), &database, "mem-1", &wrap::public_of(&worker_secret()), &grant), "the person key signed this policy for this member key");let opened = open_agent_wrap(&worker_secret(), "mem-1", &grant.withheld, &grant.wrapped).expect("the member key opens it"); assert_eq!(opened.tables(), ["note", "sealed_diary"]); assert!(client.vault().unwrap().until(client.now()).is_none(), "no vault session is left open");// The object's grant row lands; a table the kit added since (photo, sealed by its definition) is handed on the next pass, unasked. served( &client,"CREATE TABLE IF NOT EXISTS cotton_unlock_grant (id TEXT PRIMARY KEY, workspace_id TEXT, request_id TEXT, token_id TEXT, tables TEXT, minutes REAL, standing INTEGER, granted_at TEXT, ends_at TEXT, ended_at TEXT, client TEXT, account INTEGER, member_id TEXT, member_pub TEXT, withheld TEXT, ask TEXT, off TEXT);", ); served( &client, &format!("INSERT INTO cotton_unlock_grant VALUES ('g-a', 'w', 'req-a', 'mem-1', '[\"note\",\"sealed_diary\"]', 0, 1, '2026-11-11T09:00:00.000Z', '9999-12-31T23:59:59.999Z', NULL, 'Claude', 1, 'mem-1', '{member_pub}', '[\"code_credential\",\"money_entry\",\"passkey\",\"secret\"]', '[]', '[]');"), );let screen = super::super::assistants::call_on(&client, "assistant.screen", &json!({})).unwrap(); assert_eq!(screen["connections"][0]["grantId"], "g-a"); assert_eq!(screen["heading"], "Your Claude"); assert!(screen.get("connect").is_none(), "connected: Connect Claude is not offered: {screen}");// How it reads, said for the page and for the row on You; an app whose kit names no groups chooses by the core's. assert_eq!(screen["reading"]["state"], "standing"); assert_eq!(screen["reading"]["row"], "Can read any time"); assert_eq!(screen["reading"]["act"]["label"], "Ask each time instead");// This copy keeps no sealed definitions, so there is nothing to group (the core's groups: rules::unlock groups_of). assert_eq!(screen["groups"], json!([]));// Widening asks the phone's lock (coordinator, 22 Nov 2026). Notes on, asked without the device key the lock// releases (the lock cancelled), is refused and nothing is posted; stepping down to Ask each time asks no lock;// through the lock, Notes on goes.let (object, exchange) = door([Reply::ok(r#"{"table":"note","access":"ask"}"#), Reply::ok(r#"{}"#), Reply::ok(r#"{"table":"note","access":"on"}"#)]); client.set_object_door(Some(Arc::new(object)));let scope = |request: Value| super::super::assistants::call_on(&client, "assistant.scope", &request);let refused = scope(json!({"table": "note", "access": "on"})).expect_err("widening without the lock"); assert_eq!(refused.code, "bad_request"); assert_eq!(exchange.calls(), 0, "a lock not given changes nothing"); scope(json!({"table": "note", "access": "ask"})).expect("stepping down asks no lock"); assert_eq!((body(&exchange, 0)["act"].clone(), body(&exchange, 0)["args"].clone()), (json!("assistant_scope"), json!({"table": "note", "access": "ask"}))); scope(json!({"table": "note", "access": "on", "privateKey": secret})).expect("through the lock"); assert_eq!(body(&exchange, 2)["args"], json!({"table": "note", "access": "on"}));let _ = dk; client.set_object_door(None);}/// RULE (owner, 23 Nov 2026: the card is groups a person knows, not forty tables): Allow with the groups picked under/// Choose what grants exactly the asked tables of those groups, nothing hidden; Everything grants every table asked./// The grant given is the grant chosen: the member key opens those tables and no others.#[test]fn allow_by_groups_grants_exactly_the_tables_of_the_groups_chosen() {use cotton_core::seal::agent::open_agent_wrap;let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap(); wrapped(&client);let _key = person(&client);let member_pub = URL_SAFE_NO_PAD.encode(wrap::public_of(&worker_secret())); served( &client, &format!("CREATE TABLE IF NOT EXISTS cotton_unlock_request (id TEXT PRIMARY KEY, workspace_id TEXT, token_id TEXT, token_name TEXT, client TEXT, tables TEXT, reason TEXT, minutes REAL, worker_pub TEXT, requested_at TEXT, expires_at TEXT, state TEXT, account INTEGER, member_id TEXT, member_pub TEXT, connected_at TEXT); INSERT INTO cotton_unlock_request VALUES ('req-a', 'w', 'tok-1', 'MyClaude', 'Claude', '[\"assistant_read\",\"email\",\"journal_entry\",\"note\"]', 'Let your Claude read your data', 0, '{member_pub}', '2026-11-11T08:59:00.000Z', '2099-01-01T00:00:00.000Z', 'waiting', 1, 'mem-1', '{member_pub}', '2026-11-11T08:58:00.000Z');" ), );let (_dk, row) = cotton_client::seal::mint_data_key(&fixture_vmk(), 1, "2026-11-11T09:00:00.000Z").unwrap();let file = rusqlite::Connection::open(client.layout().replica(&database)).unwrap(); cotton_client::seal::write_notes(&file, &[cotton_client::seal::Note::Key { id: "dk".into(), data: row }]).unwrap(); drop(file);let card = call_on(&client, "unlock.card", &json!({})).unwrap();let ask = &card["card"]["ask"]; assert_eq!(ask["everything"]["label"], "Everything you keep in Cotton"); assert!(ask["who"].as_str().unwrap().starts_with("My Claude · connected "), "{ask}");let offered: Vec<&str> = ask["groups"].as_array().unwrap().iter().map(|g| g["id"].as_str().unwrap()).collect(); assert_eq!(offered, ["notes", "mail"], "what assistants read is the system's own: never offered");let secret = URL_SAFE_NO_PAD.encode(device_secret());let granted = |args: Value| -> (Vec<String>, Vec<String>) {let (object, exchange) = door([Reply::ok(r#"{"grant":"g-a","member":"mem-1"}"#), Reply::ok(r#"{}"#)]); client.set_object_door(Some(Arc::new(object))); call_on(&client, "unlock.allow", &args).expect("allowed");let posted = body(&exchange, 0)["args"].clone();let withheld: Vec<String> = serde_json::from_value(posted["withheld"].clone()).unwrap();let opened = open_agent_wrap(&worker_secret(), "mem-1", &withheld, posted["wrapped"].as_str().unwrap()).expect("the member key opens it");let tables: Vec<String> = serde_json::from_value(posted["tables"].clone()).unwrap(); assert_eq!(opened.tables(), tables.iter().map(String::as_str).collect::<Vec<_>>(), "what is wrapped is what is posted"); (tables, withheld) };let (tables, withheld) = granted(json!({"requestId": "req-a", "groups": ["notes"], "privateKey": secret})); assert_eq!(tables, ["journal_entry", "note"]); assert!(withheld.contains(&"email".to_string()) && withheld.contains(&"assistant_read".to_string()), "{withheld:?}");let (tables, _) = granted(json!({"requestId": "req-a", "everything": true, "privateKey": secret})); assert_eq!(tables, ["assistant_read", "email", "journal_entry", "note"], "Everything is every table asked");let refused = call_on(&client, "unlock.allow", &json!({"requestId": "req-a", "groups": [], "privateKey": secret})).unwrap_err(); assert_eq!(refused.code, "bad_tables"); client.set_object_door(None);}/// RULE (owner, 23 Nov 2026: three cards from his own machines came one after another): Allow all allows, with one/// vault key handed in, each named request that waits and is his own Claude Code machine's timed ask, as it asked;/// an assistant connected by sign-in named among them is left to its own card.#[test]fn allow_all_allows_each_of_his_own_machines_asks_and_leaves_the_rest() {let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap(); wrapped(&client); person(&client);let worker_pub = URL_SAFE_NO_PAD.encode(wrap::public_of(&worker_secret())); served( &client, &format!("CREATE TABLE IF NOT EXISTS cotton_unlock_request (id TEXT PRIMARY KEY, workspace_id TEXT, token_id TEXT, token_name TEXT, client TEXT, tables TEXT, reason TEXT, minutes REAL, worker_pub TEXT, requested_at TEXT, expires_at TEXT, state TEXT, asker TEXT, machine TEXT); INSERT INTO cotton_unlock_request VALUES ('req-a', 'w', 'tok-a', 'Lane words', 'Lane words', '[\"note\"]', NULL, 15, '{worker_pub}', '2026-11-11T08:57:00.000Z', '2099-01-01T00:00:00.000Z', 'waiting', 'code', 'mac-c'); INSERT INTO cotton_unlock_request VALUES ('req-b', 'w', 'tok-b', 'Lane days', 'Lane days', '[\"note\"]', NULL, 60, '{worker_pub}', '2026-11-11T08:58:00.000Z', '2099-01-01T00:00:00.000Z', 'waiting', 'code', 'mac-d'); INSERT INTO cotton_unlock_request VALUES ('req-c', 'w', 'tok-c', 'Claude', 'Claude (claude.ai)', '[\"note\"]', NULL, 15, '{worker_pub}', '2026-11-11T08:59:00.000Z', '2099-01-01T00:00:00.000Z', 'waiting', 'app', NULL);" ), );let (_, row) = cotton_client::seal::mint_data_key(&fixture_vmk(), 1, "2026-11-11T09:00:00.000Z").unwrap();let file = rusqlite::Connection::open(client.layout().replica(&database)).unwrap(); cotton_client::seal::write_notes(&file, &[cotton_client::seal::Note::Key { id: "dk".into(), data: row }]).unwrap(); drop(file);let card = call_on(&client, "unlock.card", &json!({})).unwrap(); assert_eq!(card["card"]["fields"]["asker"], "Claude Code on mac-c", "{card}"); assert_eq!(card["card"]["allowAll"]["requestIds"], json!(["req-a", "req-b"]));let (object, exchange) = door([Reply::ok(r#"{"grant":"g-a","ends_at":"2026-11-11T09:15:00.000Z"}"#), Reply::ok(r#"{"grant":"g-b","ends_at":"2026-11-11T10:00:00.000Z"}"#)]); client.set_object_door(Some(Arc::new(object)));let secret = URL_SAFE_NO_PAD.encode(device_secret());let answer = call_on(&client, "unlock.allowAll", &json!({"requestIds": ["req-a", "req-c", "req-b"], "privateKey": secret})).expect("allowed"); assert_eq!(answer, json!({"allowed": ["req-a", "req-b"], "refused": []})); assert_eq!(exchange.calls(), 2, "the sign-in assistant's card is left alone"); assert_eq!(body(&exchange, 0)["args"]["request_id"], "req-a"); assert_eq!(body(&exchange, 1)["args"]["request_id"], "req-b"); assert_eq!(body(&exchange, 1)["args"]["minutes"], 60, "each its own suggested time"); assert_eq!(call_on(&client, "unlock.allowAll", &json!({"requestIds": ["req-c"], "privateKey": secret})).unwrap_err().code, "request_not_waiting");}/// RULE (HANDING STUCK, coordinator, 25 Nov 2026): a pass tops a live grant up with every table the object serves/// sealed, not only the tables this app's kit keeps. Words keeps no session table, yet once the object seals the session/// tables (the open tables lock) its pass hands their keys; without the object's whole answer held, it hands none.#[test]fn the_pass_hands_a_table_the_kit_keeps_nowhere_once_the_object_serves_it_sealed() {use cotton_core::seal::agent::open_agent_wrap;let (_dir, client, _clock) = attached_on_a_clock();let database = client.current_database().unwrap();let member_pub = URL_SAFE_NO_PAD.encode(wrap::public_of(&worker_secret())); served( &client,"CREATE TABLE IF NOT EXISTS cotton_unlock_grant (id TEXT PRIMARY KEY, workspace_id TEXT, request_id TEXT, token_id TEXT, tables TEXT, minutes REAL, standing INTEGER, granted_at TEXT, ends_at TEXT, ended_at TEXT, client TEXT, account INTEGER, member_id TEXT, member_pub TEXT, withheld TEXT, ask TEXT, off TEXT);", ); served( &client, &format!("INSERT INTO cotton_unlock_grant VALUES ('g-w', 'w', 'connect:mem-w', 'mem-w', '[\"note\"]', 0, 1, '2026-11-11T09:00:00.000Z', '9999-12-31T23:59:59.999Z', NULL, 'Claude', 1, 'mem-w', '{member_pub}', '[\"code_credential\",\"money_entry\",\"passkey\",\"secret\"]', '[]', '[]');"), ); client.data_keys().hold(&database, &DataKey::from_bytes([7; 32]));// Before: the copy's own definitions seal nothing and no whole answer is held: nothing to hand.let (object, exchange) = door([Reply::ok(r#"{}"#)]); client.set_object_door(Some(Arc::new(object)));super::super::assistants::top_up(&client).expect("a pass with nothing to hand"); assert_eq!(exchange.calls(), 0, "nothing sealed that the grant lacks");// The object's whole answer, as a launch's first page takes it: session sealed, a table this copy keeps nowhere.let held = cotton_client::transport::object::HeldDefinitions::new();let whole = [json!({"id": "session", "plural": "Sessions", "seal": {"clear": ["id"], "blind": []}}), json!({"id": "note", "plural": "Notes"}), json!({"id": "secret", "seal": {"clear": ["id"], "blind": []}})]; held.name(whole.iter()); assert_eq!(held.sealed(), ["secret", "session"]); client.set_served_definitions(Some(held));let (object, exchange) = door([Reply::ok(r#"{}"#)]); client.set_object_door(Some(Arc::new(object)));super::super::assistants::top_up(&client).expect("the pass tops the grant up");let posted = body(&exchange, 0); assert_eq!(posted["act"], "assistant_add"); assert_eq!(posted["args"]["grant_id"], "g-w");// The passwords are withheld by the grant's own policy: never handed. assert_eq!(posted["args"]["tables"], json!(["session"]));let withheld: Vec<String> = ["code_credential", "money_entry", "passkey", "secret"].map(String::from).to_vec();let opened = open_agent_wrap(&worker_secret(), "mem-w", &withheld, posted["args"]["wrapped"].as_str().unwrap()).expect("the member key opens the addition"); assert_eq!(opened.tables(), ["session"]);// Handed once: the next pass hands nothing more.let (object, exchange) = door([Reply::ok(r#"{}"#)]); client.set_object_door(Some(Arc::new(object)));super::super::assistants::top_up(&client).expect("a pass with nothing more"); assert_eq!(exchange.calls(), 0, "handed already"); client.set_served_definitions(None); client.set_object_door(None);}