//! The phone against a personal object under `wrangler dev`, end to end: run //! by `apps/business/scripts/__tests__/e2e-phone.ts`, which starts the Worker, //! imports an invented life into it and hands this test the address, the //! owner's credential and the database (`COTTON_E2E_*`). Ignored otherwise — //! it never dials anything but the address it is handed. use std::sync::Arc; use cotton_client::transport::object::ObjectAddress; use cotton_client::transport::{Exchange, SocketExchange}; use serde_json::{json, Value}; use super::tests::phone; use super::*; use crate::phone::media::MediaFetch as _; fn given(name: &str) -> String { std::env::var(name).unwrap_or_else(|_| panic!("{name} is set by e2e-phone.ts or e2e-device.ts")) } fn level(handle: &CottonHandle) { let pass = handle.client().sync_now_until_level().expect("a pass with the object"); assert_ne!(pass["behind"], json!(true), "level after the pass: {pass}"); } fn count(replica: &rusqlite::Connection, sql: &str) -> i64 { replica.query_row(sql, [], |row| row.get(0)).expect("a count") } #[test] #[ignore = "run by apps/business/scripts/__tests__/e2e-phone.ts against wrangler dev"] fn the_phone_reads_and_writes_its_personal_object() { let (base, credential, database) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_CREDENTIAL"), given("COTTON_E2E_DATABASE")); let (_dir, handle) = phone(); let connected = call(&handle, "personal.connect", &json!({"server": base, "databaseId": database, "credential": credential, "windows": {"message": 90}})).expect("connected"); assert_eq!(connected["databaseId"], json!(database)); level(&handle); let replica_file = handle.client().layout().replica(&database); assert!(replica_file.is_file(), "the pass made the copy"); let replica = rusqlite::Connection::open(&replica_file).expect("the copy"); let parked: Vec = replica .prepare("SELECT reason FROM _parked") .and_then(|mut rows| rows.query_map([], |row| row.get::<_, String>(0)).and_then(|rows| rows.collect())) .expect("the parked rows"); assert!(parked.is_empty(), "every row the object sent folds: {parked:?}"); // The fan draws the object's tools: the invented life's three, not the // package's own, beside the app's; and its Home board as the object keeps it. let tools: Vec = replica .prepare("SELECT id FROM cotton_tool_definitions ORDER BY id") .and_then(|mut rows| rows.query_map([], |row| row.get::<_, String>(0)).and_then(|rows| rows.collect())) .expect("the copy's tools"); for tool in ["chores", "garden", "seeds", "todos"] { assert!(tools.iter().any(|held| held == tool), "the copy holds {tool}: {tools:?}"); } assert!(!tools.iter().any(|held| held == "personal"), "the package's own tool is no tool: {tools:?}"); let garden: String = replica.query_row("SELECT definition FROM cotton_tool_definitions WHERE id = 'garden'", [], |row| row.get(0)).expect("Garden"); let garden: Value = serde_json::from_str(&garden).expect("JSON"); assert_eq!(garden["name"], json!("Garden")); assert!(garden["picture"]["photo"].as_str().is_some_and(|photo| photo.starts_with("photo:")), "its picture is a photo record: {garden}"); let home: String = replica.query_row("SELECT definition FROM cotton_board_definitions WHERE id = 'home' AND builtin = 0", [], |row| row.get(0)).expect("the object's Home"); // The object names the tools whose tables hold no rows (`fan.ts`): the // invented life's Garden holds rows, so it is not among them. let home: Value = serde_json::from_str(&home).expect("JSON"); assert_eq!((home["id"].as_str(), home["parts"].as_array().map(Vec::len)), (Some("home"), Some(1)), "{home}"); let fan_part = &home["parts"][0]; assert_eq!((fan_part["kind"].as_str(), fan_part["face"].as_str()), (Some("tools"), Some("fan")), "{home}"); let empty = fan_part["empty"].as_array().expect("the object names the empty tools"); assert!(!empty.iter().any(|tool| tool == "garden"), "Garden holds rows: {home}"); let fan = cotton_tools::home_arrangement::tools(&cotton_store::driver::Driver::open(&replica_file).expect("the copy"), &database, None, true) .expect("the fan's tools read"); assert!(fan.iter().any(|tool| tool == "garden"), "{fan:?}"); // The object's tables are the copy's: the invented life's made table // `quota`, which the app ships no definition of, is held as the object's // and drawn; one this build cannot read (`reading`, no title) stays on it. let quota: i64 = replica.query_row("SELECT builtin FROM cotton_table_definitions WHERE id = 'quota'", [], |row| row.get(0)).expect("the object's quota table"); assert_eq!(quota, 0, "held as the object's"); let drawn = cotton_tools::definitions::table_definitions_from_driver(&cotton_store::driver::Driver::open(&replica_file).expect("the copy"), &database) .expect("the tables read"); assert!(drawn.definitions.iter().any(|table| table.id == "quota"), "quota draws: {:?}", drawn.refused); assert!(drawn.definitions.iter().any(|table| table.id == "todo"), "the app's own tables stay"); let tables: Vec = replica .prepare("SELECT id FROM cotton_table_definitions ORDER BY id") .and_then(|mut rows| rows.query_map([], |row| row.get::<_, String>(0)).and_then(|rows| rows.collect())) .expect("the copy's tables"); assert!(!tables.iter().any(|table| table == "reading"), "a table this build cannot read is left on the object: {tables:?}"); // And its rows come: the made table's live rows land in the table its // definition makes, and its tool's list draws them. let quotas: Vec = replica .prepare("SELECT id FROM cotton_quota ORDER BY id") .and_then(|mut rows| rows.query_map([], |row| row.get::<_, String>(0)).and_then(|rows| rows.collect())) .expect("the copy's quotas"); assert_eq!(quotas, ["q-1", "q-2"], "the object's live quota rows are the copy's"); let listed = crate::methods::dispatch(&handle, "records.list", &json!({"table": "quota"})).expect("the quota list"); assert!(listed.to_string().contains("Claude personal"), "{listed}"); // The decks read the copy: the object's todos are the phone's. let todos = crate::methods::dispatch(&handle, "read.todos", &json!({})).expect("the todo list"); assert!(todos.to_string().contains("Water the plants"), "{todos}"); assert_eq!(count(&replica, "SELECT COUNT(*) FROM cotton_msg_messages WHERE id = 'mm-1'"), 1, "a message of this week comes"); assert_eq!(count(&replica, "SELECT COUNT(*) FROM cotton_msg_messages WHERE id = 'mm-3'"), 0, "a message of January stays on the object"); assert!(count(&replica, "SELECT COUNT(*) FROM cotton_memories") >= 1, "and the rest comes whole"); // A picture is the object's original, drawn at the card's width. let sha: String = replica .query_row("SELECT sha256 FROM cotton_photos WHERE trashed_at IS NULL LIMIT 1", [], |row| row.get(0)) .expect("a photo came"); let media = ObjectMedia { transport: cotton_client::media::ObjectMediaTransport::new(ObjectAddress::open(&base).expect("the address"), Arc::new(SocketExchange) as Arc, credential.clone()), replica: handle.client().layout().replica(&database), stories: None, }; let pictures = tempfile::tempdir().expect("a folder"); let thumb = pictures.path().join("thumb"); media.fetch_to(&database, &format!("{database}/photos/{sha}.t256.jpg"), &thumb).expect("a thumbnail"); assert!(std::fs::metadata(&thumb).expect("written").len() > 0); // A write here is the object's: made, then changed. let made = crate::methods::dispatch(&handle, "records.create", &json!({"table": "todo", "data": {"title": "An errand the phone wrote"}})).expect("made"); let id = ["/record/id", "/id", "/after/id", "/change/after/id"] .iter() .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str)) .unwrap_or_else(|| panic!("the made todo's id: {made}")) .to_string(); level(&handle); crate::methods::dispatch(&handle, "records.update", &json!({"table": "todo", "id": id, "patch": {"status": "done"}})).expect("changed"); level(&handle); assert_eq!(count(&replica, "SELECT COUNT(*) FROM _outbox"), 0, "nothing is left to send"); assert_eq!(count(&replica, "SELECT COUNT(*) FROM _parked"), 0, "nothing was refused"); println!("E2E-PHONE {}", json!({"made": id, "tables": tables, "quotas": quotas})); } /// The phone signs in itself, syncs, loses its container and keeps its /// Keychain (a reinstall: the same `device_secret`, a new data folder), signs /// in with the credential it kept and syncs again: run by /// `apps/business/scripts/__tests__/e2e-device.ts`, which then reads the /// object's device rows and expects one row for this phone with its sync. #[test] #[ignore = "run by apps/business/scripts/__tests__/e2e-device.ts against wrangler dev"] fn the_phone_is_one_device_row_on_its_object_across_a_reinstall() { let (base, owner, database) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_PHONE"), given("COTTON_E2E_DATABASE")); let ask = |credential: &str| json!({"server": base, "databaseId": database, "credential": credential, "windows": {"message": 90}, "deviceName": "E2E phone", "appVersion": "1.0.0 (e2e)"}); // Signed in as Cotton signs in: at the open host, the number finding its database. let (container, before) = phone(); let code = call(&before, "personal.code", &json!({"server": base, "phone": owner})).expect("a code"); assert_eq!(code["databaseId"], json!(database), "the number's own database"); let challenge = code["challengeId"].as_str().expect("a challenge").to_string(); let signed = call(&before, "personal.signIn", &json!({"server": base, "databaseId": database, "challengeId": challenge, "code": "123456"})).expect("signed in"); let credential = signed["credential"].as_str().expect("a credential").to_string(); let device = before.client().self_device_id().expect("a device id"); call(&before, "personal.connect", &ask(&credential)).expect("connected"); level(&before); drop(before); drop(container); // The container is gone; the Keychain kept the key and the credential. let (_fresh, after) = phone(); assert_eq!(after.client().self_device_id().as_deref(), Some(device.as_str()), "the same device after the container is gone"); call(&after, "personal.connect", &ask(&credential)).expect("connected again"); level(&after); level(&after); let state = after.client().sync_progress().expect("the passes' progress").state(); assert!(state.device.is_some(), "the object names this phone's row: {state:?}"); println!("E2E-DEVICE {}", json!({"credential": credential, "device_id": device, "row": state.device})); } /// The data key and a sealed table's versions against a personal object /// under `wrangler dev`: run by /// `apps/business/scripts/__tests__/e2e-seal.ts`, which lays the synthetic /// sealed table `e2e_diary` first and reads the object afterwards. The /// phone mints the data key once (a second mint is refused), writes a row /// sealed at version 1, advances the table (the first advance makes /// `v:e2e_diary`, the next updates it, a stale one is refused), learns each /// version from its next pull and seals the next row under it, and opens /// the key again from the object's row once its key store forgets it. #[test] #[ignore = "run by apps/business/scripts/__tests__/e2e-seal.ts against wrangler dev"] fn the_phone_mints_the_data_key_and_seals_under_the_versions_the_object_learns() { use cotton_client::seal::Sealer; use cotton_client::transport::object::routes; let (base, credential, database) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_CREDENTIAL"), given("COTTON_E2E_DATABASE")); let (_dir, handle) = phone(); call(&handle, "personal.connect", &json!({"server": base, "databaseId": database, "credential": credential})).expect("connected"); level(&handle); let client = handle.client(); let door = client.object_door().expect("signed in to the object"); let replica_file = client.layout().replica(&database); // Mint once, with the vault unlocked; the key is held and the object keeps the wrap. client.vault().expect("a vault door").unlock(cotton_core::vault::Vmk::from_bytes([5; 32]), 1, client.now()); let minted = crate::methods::dispatch(&handle, "seal.mintKey", &json!({})).expect("the data key is minted"); let key = minted["key"].as_str().expect("the key for the shell").to_string(); level(&handle); let status = crate::methods::dispatch(&handle, "seal.status", &json!({})).expect("a status"); assert_eq!((status["keyHeld"].clone(), status["minted"].clone()), (json!(true), json!(true)), "{status}"); assert_eq!(crate::methods::dispatch(&handle, "seal.mintKey", &json!({})).expect_err("once").code, crate::phone::seal::MINTED_ALREADY); let write = |body: &str| -> String { let made = crate::methods::dispatch(&handle, "records.create", &json!({"table": "e2e_diary", "data": {"written_at": "2026-11-11", "body": body, "mood": "glad"}})).expect("made"); let id = ["/record/id", "/id", "/after/id", "/change/after/id"] .iter() .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str)) .unwrap_or_else(|| panic!("the made row's id: {made}")) .to_string(); level(&handle); id }; let stored = |id: &str| -> Value { let pulled = door.send("GET", &format!("{}?since=0&tables=e2e_diary", routes::SYNC), None).expect("the object's rows"); pulled["rows"].as_array().into_iter().flatten().find(|row| row["id"] == json!(id)).map(|row| row["data"].clone()).unwrap_or_else(|| panic!("the object holds {id}: {pulled}")) }; let first = write("Pumpkin whispers beside the compost"); assert_eq!(stored(&first)["seal_v"], json!(1), "before any advance"); // The first advance makes the version row; the phone's pass learns it. let keys = std::sync::Arc::clone(client.data_keys()) as std::sync::Arc; assert!(keys.data_key(&database).expect("the key store").is_some()); let advance = Sealer::new(database.clone(), std::sync::Arc::clone(&keys)).advance("e2e_diary"); assert_eq!(advance["act"], json!("create"), "{advance}"); door.send("POST", routes::ACT, Some(&advance)).expect("the first advance is taken"); level(&handle); let second = write("Quokka lanterns by the jetty"); assert_eq!(stored(&second)["seal_v"], json!(2), "sealed under the version the pull learned"); // The next advance, from what the copy keeps, updates it; a stale one is refused. let next = Sealer::new(database.clone(), std::sync::Arc::clone(&keys)); let file = rusqlite::Connection::open(&replica_file).expect("the copy"); for (id, data) in cotton_client::seal::kept_keys(&file).expect("the kept keys") { next.learn(&id, &data); } drop(file); let advance = next.advance("e2e_diary"); assert_eq!(advance, json!({"act": "update", "args": {"table": "seal_key", "id": "v:e2e_diary", "data": {"v": 3}}})); door.send("POST", routes::ACT, Some(&advance)).expect("the next advance is taken"); let stale = door.send("POST", routes::ACT, Some(&json!({"act": "update", "args": {"table": "seal_key", "id": "v:e2e_diary", "data": {"v": 2}}}))).expect_err("a version never goes back"); assert_eq!(stale.code, "seal_version_back", "{}", stale.message); level(&handle); let third = write("Saffron kites over Zanzibar"); assert_eq!(stored(&third)["seal_v"], json!(3)); // Every row opens back into the copy, and the key opens again from the object's row. let replica = rusqlite::Connection::open(&replica_file).expect("the copy"); assert_eq!(count(&replica, "SELECT COUNT(*) FROM _seal_parked"), 0, "every row opened"); assert_eq!(count(&replica, "SELECT COUNT(*) FROM _outbox"), 0, "nothing waits"); assert_eq!(crate::methods::dispatch(&handle, "seal.forgetKey", &json!({})).expect("forgotten")["forgotten"], json!(true)); let opened = crate::methods::dispatch(&handle, "seal.openKey", &json!({})).expect("opened with the vault"); assert_eq!(opened["key"].as_str(), Some(key.as_str()), "the same data key"); println!("E2E-SEAL {}", json!({"rows": [first, second, third]})); } /// One MCP tool call with an owner token, its parsed text answer and whether it was an error. fn mcp(base: &str, token: &str, name: &str, args: Value) -> (bool, Value) { let address = ObjectAddress::open(base).expect("the open host"); let body = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}}); let answer = address.send(&SocketExchange, "POST", "/mcp", vec![("authorization".to_string(), format!("Bearer {token}"))], Some(&body)).expect("the MCP answer"); let result = &answer["result"]; let text = result["content"][0]["text"].as_str().unwrap_or_default(); (result["isError"] == json!(true), serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.to_string()))) } /// The 15-minute unlock window end to end: the phone /// signs in, founds its vault, keeps and publishes its person key, mints the /// data key and writes a sealed synthetic row; an assistant's owner token /// asks over MCP (`request_unlock`); the phone core decides the card and /// allows it; the token reads the row in the clear inside the window; the /// phone ends it, the token is refused again and the table moves to its next /// seal version. Run by `apps/business/scripts/__tests__/e2e-unlock.ts`. #[test] #[ignore = "run by apps/business/scripts/__tests__/e2e-unlock.ts against wrangler dev"] fn an_unlock_window_opens_a_sealed_row_for_the_token_that_asked_and_ends() { let (base, owner, database, token) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_PHONE"), given("COTTON_E2E_DATABASE"), given("COTTON_E2E_TOKEN")); let (_dir, handle) = phone(); let client = handle.client(); let code = call(&handle, "personal.code", &json!({"server": base, "phone": owner})).expect("a code"); let challenge = code["challengeId"].as_str().expect("a challenge").to_string(); let signed = call(&handle, "personal.signIn", &json!({"server": base, "databaseId": database, "challengeId": challenge, "code": "123456"})).expect("signed in"); let credential = signed["credential"].as_str().expect("a credential").to_string(); call(&handle, "personal.connect", &json!({"server": base, "databaseId": database, "credential": credential, "windows": {"message": 90}})).expect("connected"); level(&handle); // The vault: this device's key published, founded on first need, taken by the object, opened. let secret = [42u8; 32]; let private = base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, secret); let public = base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, cotton_core::vault::wrap::public_of(&secret)); crate::phone::vault::call(&handle, "vault.publishKey", &json!({"publicKey": public, "name": "E2E phone"})).expect("published"); level(&handle); let first = crate::phone::vault::call(&handle, "vault.unlock", &json!({"privateKey": private})); if first.is_err() { level(&handle); crate::phone::vault::call(&handle, "vault.unlock", &json!({"privateKey": private})).expect("the vault opens once the object has its key"); } level(&handle); let person: String = rusqlite::Connection::open(client.layout().replica(&database)).unwrap().query_row("SELECT id FROM cotton_person_keys", [], |row| row.get(0)).expect("the person key was kept on the vault's first open"); // The data key, and a sealed synthetic row written by the phone. crate::phone::seal::call(&handle, "seal.mintKey", &json!({})).expect("the data key"); crate::phone::vault::call(&handle, "vault.lock", &json!({})).expect("locked"); level(&handle); let made = crate::phone::records::call(&client, "records.create", &json!({"table": "sealed_diary", "data": {"body": "zanzibar quokka marmalade", "mood": "pelican", "written_at": "2026-11-11"}})).expect("a sealed row"); let row_id = made.pointer("/record/id").and_then(Value::as_str).expect("an id").to_string(); level(&handle); // No window: the token is told to ask, and asks. let (refused, _) = mcp(&base, &token, "get_record_by_table", json!({"table": "sealed_diary", "id": row_id})); assert!(refused, "no window, no row"); let (_, asked) = mcp(&base, &token, "request_unlock", json!({"tables": ["sealed_diary"], "reason": "To read the diary entry.", "minutes": 5})); let request = asked["request_id"].as_str().unwrap_or_else(|| panic!("a request: {asked}")).to_string(); // The phone's card, and Allow. level(&handle); let card = crate::phone::unlock::call(&handle, "unlock.card", &json!({})).expect("the card"); assert_eq!(card["card"]["requestId"], json!(request), "the card is the request: {card}"); assert_eq!(card["pollSeconds"], json!(5)); let allowed = crate::phone::unlock::call(&handle, "unlock.allow", &json!({"requestId": request, "privateKey": private})).expect("allowed"); let grant = allowed["grantId"].as_str().expect("a grant").to_string(); assert!(client.vault().unwrap().until(client.now()).is_none(), "no vault session left open"); // In the window the token reads the row in the clear. let (error, read) = mcp(&base, &token, "get_record_by_table", json!({"table": "sealed_diary", "id": row_id})); assert!(!error, "the window opens the row: {read}"); let said = read.to_string(); assert!(said.contains("zanzibar quokka marmalade") && said.contains("pelican"), "the row in the clear: {said}"); // End: the token is refused again, and the table moves to its next seal version. crate::phone::unlock::call(&handle, "unlock.end", &json!({"grantId": grant})).expect("ended"); let (refused, after) = mcp(&base, &token, "get_record_by_table", json!({"table": "sealed_diary", "id": row_id})); assert!(refused, "the window is shut: {after}"); level(&handle); let moved = crate::phone::unlock::advance_ended(&client).expect("advanced"); level(&handle); let v: String = rusqlite::Connection::open(client.layout().replica(&database)).unwrap().query_row("SELECT data FROM _seal_key WHERE id = 'v:sealed_diary'", [], |row| row.get(0)).expect("the seal version row"); println!("E2E-UNLOCK {}", json!({"person": person, "row": row_id, "request": request, "grant": grant, "moved": moved, "seal_v": serde_json::from_str::(&v).unwrap()})); } /// MEDIA SEAL FINDINGS (coordinator, 27 Nov 2026), on an invented life: what the object holds of a person's picture /// (`/people//.`, `capture.avatar`), a WhatsApp profile picture /// (`/people//whatsapp/.`) and a chat picture (`/messages//.`), each put /// up through the drain's own upload with the phone's sealing on and its data key held, then read back raw. AVATAR SEAL /// (27 Nov 2026): the same three are also put up plain, as an app from before put them (a transport with no sealing), /// under keys of their own, and every one of the six is then read back opened as a reader opens it /// (`fetch_opened_to`). Run by `apps/business/scripts/__tests__/e2e-media-seal.ts`, which asserts on the answer. #[test] #[ignore = "run by apps/business/scripts/__tests__/e2e-media-seal.ts against wrangler dev"] fn what_the_object_holds_of_a_persons_picture_and_a_chat_picture() { use cotton_client::media::MediaDrainDeps as _; use sha2::{Digest as _, Sha256}; let (base, credential, database) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_CREDENTIAL"), given("COTTON_E2E_DATABASE")); let picture = std::fs::read(given("COTTON_E2E_PICTURE")).expect("the invented picture"); let (_dir, handle) = phone(); call(&handle, "personal.connect", &json!({"server": base, "databaseId": database, "credential": credential})).expect("connected"); level(&handle); let client = handle.client(); client.vault().expect("a vault door").unlock(cotton_core::vault::Vmk::from_bytes([7; 32]), 1, client.now()); crate::methods::dispatch(&handle, "seal.mintKey", &json!({})).expect("the data key is minted"); level(&handle); let sha = Sha256::digest(&picture).iter().map(|b| format!("{b:02x}")).collect::(); let here = tempfile::tempdir().expect("a folder"); let path = here.path().join("picture.jpg"); std::fs::write(&path, &picture).expect("written"); let address = ObjectAddress::open(&base).expect("the address"); let transport = cotton_client::media::ObjectMediaTransport::new(address.clone(), Arc::new(SocketExchange) as Arc, credential.clone()) .sealing(crate::phone::personal_object::person_files_of(&client, &database)); // An app from before: the same upload with no sealing, so what it puts is held plain. let before = cotton_client::media::ObjectMediaTransport::new(address, Arc::new(SocketExchange) as Arc, credential.clone()); let now = client.now().to_rfc3339(); let mut held = Vec::new(); for (what, key, put_by) in [ ("person_picture", format!("{database}/people/e2e-person/{sha}.jpg"), &transport), ("whatsapp_picture", format!("{database}/people/e2e-person/whatsapp/{sha}.jpg"), &transport), ("chat_picture", format!("{database}/messages/e2e-thread/{sha}.jpg"), &transport), ("person_picture_from_before", format!("{database}/people/e2e-before/{sha}.jpg"), &before), ("whatsapp_picture_from_before", format!("{database}/people/e2e-before/whatsapp/{sha}.jpg"), &before), ("chat_picture_from_before", format!("{database}/messages/e2e-before/{sha}.jpg"), &before), ] { let row = cotton_store::media_ledger::MediaRow { key: key.clone(), workspace_id: database.clone(), sha256: sha.clone(), content_type: "image/jpeg".into(), size_bytes: picture.len() as i64, local_path: Some(path.display().to_string()), state: "pending".into(), after: None, after_row_id: None, attempts: 0, last_error: None, next_attempt_at: None, tier: None, captured_here: true, pinned: false, last_viewed_at: None, last_code: None, network: "any".into(), asked_by: None, source: None, created_at: now.clone(), updated_at: now.clone(), }; let landed = put_by.upload(&row, &path).map(|_| "landed".to_string()).unwrap_or_else(|refused| format!("refused: {}", refused.message)); let raw = here.path().join(format!("{what}.raw")); transport.fetch_to(&key, None, &raw).expect("read back raw"); let bytes = std::fs::read(&raw).expect("the raw bytes"); // As a reader opens it: a sealed file opened, a plain one from before taken when its bytes match its name. let opened = here.path().join(format!("{what}.opened")); let opened_is_the_picture = transport.fetch_opened_to(&key, &opened).ok().and_then(|_| std::fs::read(&opened).ok()).is_some_and(|b| b == picture); held.push(json!({ "what": what, "key": key, "landed": landed, "held_bytes": bytes.len(), "held_is_the_picture": bytes == picture, "held_is_sealed": cotton_client::media::sealed::looks_sealed(&raw).unwrap_or(false), "key_names_the_pictures_sha256": key.contains(&sha), "opened_is_the_picture": opened_is_the_picture, })); } println!("E2E-MEDIA-SEAL {}", json!({ "sha256": sha, "held": held })); } /// A phone of its own: its own container and device key (`device`), so two phones are two devices. fn phone_with_device(device: u8) -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, [device; 32])), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("Cotton's manifest")), }) .expect("an open core"); (dir, handle) } fn b64(bytes: &[u8]) -> String { base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, bytes) } /// Before sign-in: the phone stands on a database of its own, founds its local vault, and saves a login. Answers its id. fn local_password(handle: &CottonHandle, secret: &[u8; 32], word: &str) -> String { crate::methods::dispatch(handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started here"); crate::phone::vault::call(handle, "vault.publishKey", &json!({"publicKey": b64(&cotton_core::vault::wrap::public_of(secret))})).expect("the local vault founded"); crate::phone::vault::call(handle, "vault.unlock", &json!({"privateKey": b64(secret)})).expect("the local vault opens"); let made = crate::phone::vault::call(handle, "vault.create", &json!({"kind": "login", "name": "An invented login", "site": "example.com", "username": "someone", "fields": {"password": word}})).expect("a login"); made["id"].as_str().expect("an id").to_string() } /// RULE (KEPT FOUR 3 B, against the REAL Worker): two phones, each with a password saved before sign-in, sign in to a /// NEW account at once. Both hear no vault, and both post their founding; the object keeps one. The other hears /// `vault_founded`, drops its founding (never kept, never refused on screen), keeps its key in its own file, and goes /// on as into an account with a vault. Once it is let in (the typed-code approval), its next unlock seals its password /// again under the account's key; afterwards each phone reads the other's password. #[test] #[ignore = "run by apps/business/scripts/__tests__/e2e-vault-race.ts against wrangler dev"] fn two_phones_founding_at_once_read_each_others_passwords() { let (base, owner, database) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_PHONE"), given("COTTON_E2E_DATABASE")); let secrets = [[31u8; 32], [32u8; 32]]; let phones = [phone_with_device(41), phone_with_device(42)]; let words = ["an-invented-password-a", "an-invented-password-b"]; let ids: Vec = phones.iter().zip(&secrets).zip(&words).map(|(((_, handle), secret), word)| local_password(handle, secret, word)).collect(); // Both sign in at once, and both adopts hear the vault before either posts: the adopt begins at sign-in. *crate::phone::adopt::HEARD_THE_VAULT.lock().unwrap() = Some(Arc::new(std::sync::Barrier::new(2))); let _credentials: Vec = std::thread::scope(|scope| { let signing: Vec<_> = phones .iter() .map(|(_, handle)| { let base = base.clone(); let database = database.clone(); let owner = owner.clone(); scope.spawn(move || { let code = call(handle, "personal.code", &json!({"server": base, "phone": owner})).expect("a code"); let signed = call(handle, "personal.signIn", &json!({"server": base, "databaseId": database, "challengeId": code["challengeId"], "code": "123456"})).expect("signed in"); let credential = signed["credential"].as_str().expect("a credential").to_string(); call(handle, "personal.connect", &json!({"server": base, "databaseId": database, "credential": credential})).expect("connected"); let adopting = handle.client().adopting(); eprintln!("[race] an adopt was running after connect: {}", adopting.is_some()); if let Some(adopting) = adopting { adopting.join(); } credential }) }) .collect(); signing.into_iter().map(|thread| thread.join().expect("a phone signed in")).collect() }); *crate::phone::adopt::HEARD_THE_VAULT.lock().unwrap() = None; // The winner's key founded the account (its file let go); the loser's waits in its own file, quietly. for (i, (_, handle)) in phones.iter().enumerate() { for file in cotton_client::vault_keep::key_files(handle.client().layout()).unwrap() { eprintln!("[race] phone {i}: key file founded={} rows_known={} sealed={} keys={}", file.founded, file.rows_known, file.sealed.len(), file.keys.len()); } } let waiting: Vec = phones.iter().map(|(_, handle)| !cotton_client::vault_keep::key_files(handle.client().layout()).unwrap().is_empty()).collect(); assert_eq!(waiting.iter().filter(|w| **w).count(), 1, "one founding kept, one given way: {waiting:?}"); let (w, l) = if waiting[0] { (1, 0) } else { (0, 1) }; let loser = &phones[l].1; let winner = &phones[w].1; let layout = loser.client().layout().clone(); assert!(!cotton_client::unsent::kept_rows(&layout, &database).iter().any(|row| cotton_client::founding::is_founding(&row.table)), "the founding given way is never a kept row"); assert!(!serde_json::to_string(&cotton_client::unsent::discarded(&layout, &database)).unwrap().contains("cotton_vault_keys"), "nor said as refused"); assert!(!cotton_client::copy_keep::kept_changes(&layout, &database).iter().any(|change| change.table == "cotton_secrets"), "nothing on the Sync screen"); for (_, handle) in &phones { level(handle); } // The winner opens the account's vault and lets the loser in by the typed-code compare. crate::phone::vault::call(winner, "vault.unlock", &json!({"privateKey": b64(&secrets[w])})).expect("the winner opens the account's vault"); let asked = crate::methods::dispatch(loser, "personal.ask", &json!({"server": base, "phone": owner, "privateKey": b64(&secrets[l]), "deviceName": "The other invented phone"})).expect("an ask"); let ask_id = asked["askId"].as_str().expect("an ask id").to_string(); level(winner); crate::methods::dispatch(winner, "signin.show", &json!({"askId": ask_id})).expect("shown"); let polled = crate::methods::dispatch(loser, "personal.askPoll", &json!({"server": base, "askId": ask_id})).expect("polled"); let code = polled["code"].as_str().unwrap_or_else(|| panic!("a code: {polled}")).to_string(); crate::methods::dispatch(winner, "signin.approve", &json!({"askId": ask_id, "code": code, "privateKey": b64(&secrets[w])})).expect("approved, the key handed over"); let _ = crate::methods::dispatch(loser, "personal.askPoll", &json!({"server": base, "askId": ask_id})); // The loser's next unlock seals its password again under the account's key; the server holds it; the key goes. level(loser); crate::phone::vault::call(loser, "vault.unlock", &json!({"privateKey": b64(&secrets[l])})).expect("the loser opens the account's vault"); level(loser); crate::phone::vault_carry::settle_after_pass(&loser.client()); assert!(cotton_client::vault_keep::key_files(&layout).unwrap().is_empty(), "the server holds the password sealed again: the local key is let go"); // Each reads the other's. level(winner); crate::phone::vault::call(winner, "vault.unlock", &json!({"privateKey": b64(&secrets[w])})).expect("opens"); crate::phone::vault::call(loser, "vault.unlock", &json!({"privateKey": b64(&secrets[l])})).expect("opens"); let by_winner = crate::phone::vault::call(winner, "vault.reveal", &json!({"id": ids[l]})).expect("the winner reads the loser's password"); let by_loser = crate::phone::vault::call(loser, "vault.reveal", &json!({"id": ids[w]})).expect("the loser reads the winner's password"); assert!(by_winner.to_string().contains(words[l]), "{by_winner}"); assert!(by_loser.to_string().contains(words[w]), "{by_loser}"); println!("E2E-VAULT-RACE {}", json!({"winner": w, "loser": l})); } /// The synthetic table of the narrowing walk under one of its three clear lists (LOCK TABLES 2): `wide`, a build's /// before the narrowing, with a column a later definition drops; `mid`, that column gone; `narrow`, `mood` sealed. fn narrow_table(list: &str) -> Value { let mut columns = vec![json!({"key": "written_at", "name": "Written", "type": "date"}), json!({"key": "body", "name": "Body", "type": "longtext"}), json!({"key": "mood", "name": "Mood", "type": "text"})]; let clear = match list { "wide" => { columns.push(json!({"key": "old_rating", "name": "Rating", "type": "text"})); json!(["written_at", "mood", "old_rating"]) } "mid" => json!(["written_at", "mood"]), _ => json!(["written_at"]), }; json!({ "format_version": 1, "id": "e2e_narrow", "name": "Jot", "plural": "Jots", "title": "body", "date": "written_at", "columns": columns, "slip": {"title": "body", "subtitle": null, "trailing": "written_at", "photo": null, "toggle": null}, "tile": {"face": "slip-list"}, "page": [{"heading": null, "columns": ["body", "mood", "written_at"]}], "instructions": "A synthetic sealed table for the narrowing walk.", "seal": {"clear": clear, "blind": ["body"]} }) } fn lay_narrow(base: &str, token: &str, list: &str) { let address = ObjectAddress::open(base).expect("the open host"); address .send(&SocketExchange, "POST", "/v1/admin/definitions/tables", vec![("authorization".to_string(), format!("Bearer {token}"))], Some(&json!({"tables": [narrow_table(list)]}))) .unwrap_or_else(|refusal| panic!("the {list} list is laid: {}", refusal.message)); } fn made_id(made: &Value) -> String { ["/record/id", "/id", "/after/id", "/change/after/id"] .iter() .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str)) .unwrap_or_else(|| panic!("the made row's id: {made}")) .to_string() } /// A phone holding the older, wider clear list, offline across the narrowing (LOCK TABLES 2, H1): every write it made /// lands, a newly sealed column with a value is held beside the seal for the reseal and an empty one is dropped, the /// same pass brings it the narrower list and its next write seals under it. Then it makes this database's Mac a vault /// device under a key file, for the real `seal-migrate` binary the script runs next. Run by /// `apps/business/scripts/__tests__/e2e-narrow.ts`. #[test] #[ignore = "run by apps/business/scripts/__tests__/e2e-narrow.ts against wrangler dev"] fn an_old_phone_writes_across_a_narrowing_and_is_never_refused() { use cotton_client::transport::object::routes; let (base, credential, database, token) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_CREDENTIAL"), given("COTTON_E2E_DATABASE"), given("COTTON_E2E_TOKEN")); let mac_key = std::path::PathBuf::from(given("COTTON_E2E_MAC_KEY")); lay_narrow(&base, &token, "wide"); let (_dir, handle) = phone(); call(&handle, "personal.connect", &json!({"server": base, "databaseId": database, "credential": credential})).expect("connected"); level(&handle); let client = handle.client(); let door = client.object_door().expect("signed in to the object"); client.vault().expect("a vault door").unlock(cotton_core::vault::Vmk::from_bytes([5; 32]), 1, client.now()); crate::methods::dispatch(&handle, "seal.mintKey", &json!({})).expect("the data key is minted"); level(&handle); let create = |data: Value| made_id(&crate::methods::dispatch(&handle, "records.create", &json!({"table": "e2e_narrow", "data": data})).expect("made")); let stored = |id: &str| -> serde_json::Map { let pulled = door.send("GET", &format!("{}?since=0&tables=e2e_narrow", routes::SYNC), None).expect("the object's rows"); pulled["rows"].as_array().into_iter().flatten().find(|row| row["id"] == json!(id)).and_then(|row| row["data"].as_object().cloned()).unwrap_or_else(|| panic!("the object holds {id}: {pulled}")) }; let copy_clear = || -> Value { let replica = rusqlite::Connection::open(client.layout().replica(&database)).expect("the copy"); let text: String = replica.query_row("SELECT definition FROM cotton_table_definitions WHERE id = 'e2e_narrow'", [], |row| row.get(0)).expect("the copy's definition"); serde_json::from_str::(&text).expect("JSON")["seal"]["clear"].clone() }; // A row from before any of it, holding a column a later definition drops: a key that is no column, beside its seal. let stray = create(json!({"written_at": "2026-11-20", "body": "Heron over the weir", "mood": "glad", "old_rating": "four-stars"})); let calm = create(json!({"written_at": "2026-11-20", "body": "Egret at dusk", "mood": "calm"})); level(&handle); assert_eq!(stored(&stray)["old_rating"], json!("four-stars")); lay_narrow(&base, &token, "mid"); level(&handle); assert_eq!(copy_clear(), json!(["written_at", "mood"])); // Offline: three writes under the list the copy holds; the narrowing lands on the object meanwhile. let tired = create(json!({"written_at": "2026-11-21", "body": "Crane in the rain", "mood": "tired"})); let empty = create(json!({"written_at": "2026-11-21", "body": "Kite without wind", "mood": null})); crate::methods::dispatch(&handle, "records.update", &json!({"table": "e2e_narrow", "id": calm, "patch": {"body": "Egret at dawn"}, "timezone": "Asia/Kolkata"})).expect("edited"); lay_narrow(&base, &token, "narrow"); level(&handle); let replica = rusqlite::Connection::open(client.layout().replica(&database)).expect("the copy"); assert_eq!(count(&replica, "SELECT COUNT(*) FROM _outbox"), 0, "every write left the queue"); let discarded = crate::methods::dispatch(&handle, "sync.rejected", &json!({})).expect("the rejected writes"); assert!(!discarded.to_string().contains("sealed_in_clear"), "nothing was refused: {discarded}"); // A value is held beside the seal for the reseal; an empty one is dropped; nothing of the row is lost. assert_eq!(stored(&tired)["mood"], json!("tired")); assert!(!stored(&empty).contains_key("mood"), "an empty newly sealed column is dropped: {:?}", stored(&empty)); // The edited row's mood is the row's still, beside the seal or (once this phone's sweep resealed it under the // narrow list) inside it: read back through the copy, never lost. let read = |id: &str| crate::methods::dispatch(&handle, "records.get", &json!({"table": "e2e_narrow", "id": id})).expect("reads").to_string(); assert!(read(&calm).contains("\"calm\"") && read(&calm).contains("Egret at dawn"), "the offline edit keeps its mood: {}", read(&calm)); for id in [&tired, &empty, &calm] { assert!(stored(id).contains_key("sealed_enc"), "{id} is sealed"); } // The same pass brought the narrower list; the next write seals mood. assert_eq!(copy_clear(), json!(["written_at"])); let sunny = create(json!({"written_at": "2026-11-22", "body": "Swift over the roofs", "mood": "sunny"})); level(&handle); assert!(!stored(&sunny).contains_key("mood"), "sealed under the narrow list: {:?}", stored(&sunny)); assert_eq!(count(&replica, "SELECT COUNT(*) FROM _outbox"), 0); // This database's Mac, a vault device under a key file (the founding of its own row: no device holds a wrap yet), // so the real seal-migrate opens the data key as it does on the owner's Mac. let secret: [u8; 32] = std::array::from_fn(|i| (i as u8).wrapping_mul(7).wrapping_add(3)); std::fs::write(&mac_key, secret).expect("the key file"); let public = cotton_core::vault::wrap::public_of(&secret); let wrapped = cotton_core::vault::wrap::wrap(&public, &[5u8; 32]).expect("the wrap"); use base64::Engine as _; let row = json!({"act": "create", "args": {"table": "vault_key", "data": { "device_id": "e2e", "name": "E2E Mac", "public_key": base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public), "wrapped_vmk": wrapped, "vmk_version": 1 }}}); door.send("POST", routes::ACT, Some(&row)).unwrap_or_else(|refusal| panic!("the Mac's vault row: {} {}", refusal.code, refusal.message)); println!("E2E-NARROW {}", json!({"stray": stray, "calm": calm, "tired": tired, "empty": empty, "sunny": sunny})); } /// After the real `seal-migrate` resealed the walk's rows, a fresh phone copy opens every one of them, each value as the /// old phone wrote it, and none is set aside (LOCK TABLES 2, M1: a key that is no column was sealed and its clear copy /// dropped in the same write). Run by `apps/business/scripts/__tests__/e2e-narrow.ts`. #[test] #[ignore = "run by apps/business/scripts/__tests__/e2e-narrow.ts against wrangler dev"] fn a_fresh_phone_opens_every_row_the_mac_resealed() { let (base, credential, database) = (given("COTTON_E2E_BASE"), given("COTTON_E2E_CREDENTIAL"), given("COTTON_E2E_DATABASE")); let ids: Value = serde_json::from_str(&given("COTTON_E2E_ROWS")).expect("the walk's rows"); let (_dir, handle) = phone(); call(&handle, "personal.connect", &json!({"server": base, "databaseId": database, "credential": credential})).expect("connected"); let client = handle.client(); client.vault().expect("a vault door").unlock(cotton_core::vault::Vmk::from_bytes([5; 32]), 1, client.now()); // The key row comes with the first pass; the data key opens from it, and the next pass opens every row. level(&handle); crate::methods::dispatch(&handle, "seal.openKey", &json!({})).expect("the data key opens with the vault"); level(&handle); let replica = rusqlite::Connection::open(client.layout().replica(&database)).expect("the copy"); assert_eq!(count(&replica, "SELECT COUNT(*) FROM _seal_parked"), 0, "every row opened"); let read = |id: &Value| crate::methods::dispatch(&handle, "records.get", &json!({"table": "e2e_narrow", "id": id})).unwrap_or_else(|error| panic!("{id} reads: {error:?}")).to_string(); for (key, mood) in [("calm", "calm"), ("tired", "tired"), ("sunny", "sunny"), ("stray", "glad")] { assert!(read(&ids[key]).contains(&format!("\"{mood}\"")), "{key} opens to its mood: {}", read(&ids[key])); } assert!(read(&ids["calm"]).contains("Egret at dawn"), "the offline edit is the row's"); println!("E2E-NARROW-OPEN {}", json!({"opened": 4})); }