//! No finding people, a chat with someone not on Cotton yet, and profiles, over //! a scripted object. Every number, name and key is invented. use std::sync::Arc; use cotton_client::transport::object::ObjectAddress; use cotton_client::transport::scripted::{Reply, ScriptedExchange, Seen}; use cotton_core::chat::payload::{Payload, Profile}; use cotton_core::chat::seal; use cotton_core::vault::wrap::public_of; use serde_json::{json, Value}; use crate::handle::CottonHandle; use crate::phone::cotton_chat::over; use crate::phone::passwords::tests::phone; use crate::phone::personal_object::ObjectDoor; const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential"; const ME: &str = "+919876500000"; const ASHA: &str = "+919876543210"; const RAVI: &str = "+919876543211"; const NEW: &str = "+919876543212"; fn scalar(seed: u8) -> [u8; 32] { let mut bytes = [seed; 32]; bytes[0] = seed.wrapping_mul(7).wrapping_add(1); bytes } fn private(seed: u8) -> String { seal::key_text(&scalar(seed)) } fn with_door(handle: &CottonHandle, replies: impl IntoIterator) -> Arc { let exchange = ScriptedExchange::new(replies); let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: CREDENTIAL.to_string() }; handle.client().set_object_door(Some(Arc::new(door))); exchange } fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value { over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message)) } fn body(seen: &Seen) -> Value { serde_json::from_slice(&seen.body).expect("a JSON body") } fn sql(handle: &CottonHandle, query: &str, id: &str) -> Option> { handle .client() .with_writer(|replica| Ok(replica.driver.get(query, &[rusqlite::types::Value::Text(id.to_string())]).map_err(|e| e.to_string())?.map(|row| crate::phone::passwords::json_row(&row)))) .unwrap() } fn contact(handle: &CottonHandle, number: &str) -> Option> { sql(handle, "SELECT * FROM cotton_msg_contacts WHERE phone_e164 = ?", number.trim_start_matches('+')) } /// The contact table as the kit lays it (the profile column). fn hold_definitions(handle: &CottonHandle) { let thread: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/thread.json")).unwrap(); let contact: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/message_contact.json")).unwrap(); handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&thread, &contact]).map(|_| ())).unwrap(); } fn asha_keys() -> Reply { Reply::ok(&json!({ "me": ME, "devices": [{ "device": "theirhandle00000000000", "key": seal::key_text(&public_of(&scalar(1))) }], "own": [] }).to_string()) } fn book() -> Value { json!({ "contacts": [{ "name": "Asha", "numbers": ["098765 43210"] }] }) } // RULE (DISCOVERY OFF 1, 27 Nov 2026: no bulk contact discovery): there is no "Find people I know" and no "people can find me": the core answers both as unknown and sends nothing. #[test] fn finding_people_and_being_findable_are_gone() { let (_dir, handle) = phone(); hold_definitions(&handle); let exchange = with_door(&handle, []); for (method, request) in [("chat.discover", book()), ("chat.findable", json!({ "on": true })), ("chat.findable", json!({}))] { let error = over(&handle.client(), method, &request).expect_err(method); assert_eq!(error.code, "unknown_method", "{method}"); } assert_eq!(exchange.calls(), 0, "nothing asked of the server"); assert!(!crate::methods::ALL_METHODS.contains(&"chat.discover") && !crate::methods::ALL_METHODS.contains(&"chat.findable") && !crate::methods::CLIENT_METHODS.contains(&"chat.discover")); } // RULE: a new chat with a number not known here never asks the server whether it is on Cotton; the chat says "not on Cotton yet" and its person is asked once a message waits. #[test] fn a_new_chat_asks_nobody_whether_a_number_is_on_cotton() { let (_dir, handle) = phone(); hold_definitions(&handle); let exchange = with_door(&handle, []); let started = answer(&handle, "chat.start", json!({ "number": NEW })); assert_eq!(started["reach"], "notYet"); assert_eq!(exchange.calls(), 0); // Known on Cotton here (they wrote, or accepted), the chat is on Cotton at once. crate::phone::chat_people::hold_on_cotton(&handle.client(), ASHA); assert_eq!(answer(&handle, "chat.start", json!({ "number": ASHA }))["reach"], "on"); assert!(contact(&handle, NEW).is_none_or(|c| c["on_cotton_at"].is_null()), "nobody is marked on Cotton by a lookup"); assert_eq!(exchange.calls(), 0); assert_eq!(answer(&handle, "chat.contacts", json!({}))["people"].as_array().unwrap().iter().map(|p| p["number"].as_str().unwrap()).collect::>(), vec![ASHA]); } // RULE: a message to someone not on Cotton waits on the phone (no key nobody holds is sealed for) and goes, sealed for their device, once they can be written to. #[test] fn a_message_to_someone_not_on_cotton_waits_then_goes() { let (_dir, handle) = phone(); hold_definitions(&handle); // The chat starts: not known on Cotton here. with_door(&handle, []); let started = answer(&handle, "chat.start", json!({ "number": NEW })); assert_eq!(started["reach"], "notYet"); let thread = started["thread"].as_str().unwrap().to_string(); // Sent: the object is asked to wait for them, and nothing is sealed. let exchange = with_door(&handle, [Reply::ok(r#"{"state":"waiting"}"#)]); let sent = answer(&handle, "chat.send", json!({ "thread": thread, "body": "join me", "privateKey": private(2) })); assert_eq!(sent["state"], "queued", "its tick the clock: it waits, out of the queue"); assert_eq!(exchange.seen().iter().map(|s| s.path.as_str()).collect::>(), vec!["/v1/chat/wait"]); assert_eq!(body(&exchange.nth(0)), json!({ "number": NEW })); // A second message waits behind it without asking again... once the first waits, its chat is not on Cotton yet. let reach = crate::phone::chat_people::reach_of(&handle.client(), &thread).unwrap(); assert_eq!((reach["state"].as_str(), reach["waiting"].as_i64()), (Some("notYet"), Some(1))); // They join: the next pass hears it, and the message is sealed for their device and sent. let theirs = seal::key_text(&public_of(&scalar(1))); let exchange = with_door(&handle, [ Reply::ok(&json!({ "reached": [NEW], "waiting": [] }).to_string()), Reply::ok(&json!({ "me": ME, "devices": [{ "device": "theirhandle00000000000", "key": theirs }], "own": [] }).to_string()), Reply::ok(r#"{"ok":true,"id":"x","at":1763000000000}"#), ]); let pass = answer(&handle, "chat.flush", json!({ "privateKey": private(2) })); assert_eq!(pass["sent"].as_array().unwrap().len(), 1, "{pass}"); let paths: Vec = exchange.seen().iter().map(|s| s.path.clone()).collect(); assert_eq!(paths[0], "/v1/chat/reach"); assert_eq!(paths[2], "/v1/chat/send"); assert_eq!(crate::phone::chat_people::reach_of(&handle.client(), &thread).unwrap()["state"], "on"); } // RULE: the invite is words the person sends themselves (a text from their own phone, or the share sheet), with the link; asking for it asks the object to wait for that number. #[test] fn the_invite_is_the_persons_own_text() { let (_dir, handle) = phone(); hold_definitions(&handle); let exchange = with_door(&handle, [Reply::ok(r#"{"state":"waiting"}"#)]); let got = answer(&handle, "chat.invite", json!({ "number": NEW })); assert!(got["text"].as_str().unwrap().contains(got["link"].as_str().unwrap())); assert!(got["sms"].as_str().unwrap().starts_with(&format!("sms:{NEW}?&body="))); assert!(!got["sms"].as_str().unwrap().contains(' ')); assert_eq!(exchange.only().path, "/v1/chat/wait"); } // RULE: the person's own name and picture ride sealed in each message's box, never outside it; theirs, arriving, are kept on their contact (the newer stands) and shown on their page beside the name this phone knows them by. #[test] fn profiles_travel_sealed_and_are_kept_newest_first() { let (dir, handle) = phone(); hold_definitions(&handle); // Their message, carrying their own name. let mut hello = Payload::message("ffffffffffffffff", ASHA, ME, 10, Some("hello".into()), None, vec![]); hello.profile = Some(Profile { name: Some("Asha K".into()), picture: None, at: 50 }); let item = json!({ "id": hello.id, "kind": "message", "peer": ASHA, "out": false, "request": false, "box": seal::seal(&scalar(1), &public_of(&scalar(2)), &hello.bytes()).unwrap(), "at": 100 }); with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [item] }).to_string()), asha_keys(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]); let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(2) })); let thread = got["landed"][0]["thread"].as_str().unwrap_or_else(|| panic!("{got}")).to_string(); let page = answer(&handle, "chat.contact", json!({ "thread": thread })); assert_eq!((page["number"].as_str(), page["theirName"].as_str(), page["reach"].as_str()), (Some(ASHA), Some("Asha K"), Some("on"))); assert_eq!(page["mutes"].as_array().unwrap().len(), 3); assert!(page["mutes"][2]["until"].is_null(), "until turned back on"); assert_eq!(page["between"], json!({ "files": 0, "links": 0, "photos": 0, "videos": 0, "voice": 0 })); // An older one does not replace it. let mut later = Payload::message("eeeeeeeeeeeeeeee", ASHA, ME, 20, Some("again".into()), None, vec![]); later.profile = Some(Profile { name: Some("old".into()), picture: None, at: 10 }); let item = json!({ "id": later.id, "kind": "message", "peer": ASHA, "out": false, "request": false, "box": seal::seal(&scalar(1), &public_of(&scalar(2)), &later.bytes()).unwrap(), "at": 200 }); with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [item] }).to_string()), asha_keys(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]); answer(&handle, "chat.incoming", json!({ "privateKey": private(2) })); assert_eq!(answer(&handle, "chat.contact", json!({ "thread": thread }))["theirName"], "Asha K"); // The person names themselves and puts up a picture: the picture goes up sealed, and their next message carries both, inside the box alone. let picture = dir.path().join("me.jpg"); std::fs::write(&picture, b"a picture of me").unwrap(); let exchange = with_door(&handle, [Reply::ok(r#"{"file":"0123456789abcdef0123456789abcdef"}"#)]); let mine = answer(&handle, "chat.profile.set", json!({ "name": "Me Myself", "picture": picture.to_string_lossy() })); assert_eq!((mine["name"].as_str(), mine["number"].as_str()), (Some("Me Myself"), Some(ME))); assert!(mine["picture"]["path"].is_string()); let put = exchange.only(); assert_eq!((put.method.as_str(), put.path.as_str()), ("PUT", "/v1/chat/profile-picture")); assert!(put.body.starts_with(b"cf1") && !put.body.windows(5).any(|w| w == b"of me"), "sealed on the phone"); let theirs = seal::key_text(&public_of(&scalar(1))); let exchange = with_door(&handle, [Reply::ok(&json!({ "me": ME, "devices": [{ "device": "theirhandle00000000000", "key": theirs }], "own": [] }).to_string()), Reply::ok(r#"{"ok":true,"id":"x","at":1763000000000}"#)]); answer(&handle, "chat.send", json!({ "thread": thread, "body": "hi", "privateKey": private(2) })); let envelope = body(exchange.seen().iter().find(|s| s.path == "/v1/chat/send").expect("the message sent")); assert!(!envelope.to_string().contains("Me Myself")); let opened = seal::open(&scalar(1), envelope["boxes"]["theirhandle00000000000"].as_str().unwrap()).unwrap(); let said: Payload = serde_json::from_slice(&opened.payload).unwrap(); let carried = said.profile.expect("their box carries the person's profile"); assert_eq!(carried.name.as_deref(), Some("Me Myself")); assert_eq!(carried.picture.unwrap().file, "0123456789abcdef0123456789abcdef"); } // RULE: the blocked list is the object's, named as this phone knows each person. #[test] fn the_blocked_are_listed() { let (_dir, handle) = phone(); with_door(&handle, [Reply::ok(&json!({ "people": [], "asking": [], "blocked": [{ "number": RAVI, "name": "R", "at": "2026-11-20T10:00:00.000Z" }] }).to_string())]); assert_eq!(answer(&handle, "chat.blocked", json!({})), json!({ "people": [{ "number": RAVI, "name": "R", "at": "2026-11-20T10:00:00.000Z" }] })); } // RULE (DISCOVERY OFF 2): the file older builds kept of address-book digests found not on Cotton is erased at start, // and nothing beside it. #[test] fn the_old_finding_file_is_erased_at_start() { let dir = tempfile::tempdir().unwrap(); std::fs::write(dir.path().join("chat-discover.json"), br#"{"0000":1}"#).unwrap(); std::fs::write(dir.path().join("chat-profile-picture"), b"kept").unwrap(); crate::shell::client::erase_old_finding(dir.path()); assert!(!dir.path().join("chat-discover.json").exists()); assert!(dir.path().join("chat-profile-picture").exists()); crate::shell::client::erase_old_finding(dir.path()); }