//! Safety numbers between phones on one relay (22 Nov //! 2026). Invented numbers and keys. use super::*; /// Phones on one relay whose copies hold the contact table as the kit lays it (its safety columns). fn safety_world(numbers: &[&'static str], friends: &[(&str, &str)]) -> (Arc, Vec) { let (relay, phones) = world(numbers, friends); let contact: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/message_contact.json")).unwrap(); for p in &phones { p.handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&contact]).map(|_| ())).unwrap(); } (relay, phones) } impl Phone { fn safety(&self, number: &str) -> Value { let thread = self.start(number); self.call("chat.safety", json!({ "thread": thread })) } /// The safety lines of the one-to-one conversation with `number`. fn safety_lines(&self, number: &str) -> Vec { let thread = cotton_core::chat::ids::thread_id(&crate::phone::cotton_chat::namespace(&self.handle.client()).unwrap(), number); self.handle .client() .with_writer(|replica| { Ok(replica .driver .all("SELECT body FROM cotton_msg_messages WHERE thread_id = ? AND json_extract(meta, '$.cotton.safety') IS NOT NULL ORDER BY sent_at, id", &[rusqlite::types::Value::Text(thread.clone())]) .map_err(|e| e.to_string())? .iter() .map(|r| crate::phone::passwords::json_row(r)["body"].as_str().unwrap_or_default().to_string()) .collect()) }) .unwrap() } /// Every number's keys asked again at the next word (a later sync). fn later(&self) { crate::phone::cotton_chat::forget_keys(&self.handle.client()); } } /// Asha has written with Ben (whose phone speaks c2) and with Chen. fn chatting() -> (Arc, Vec) { let (relay, p) = safety_world(&[ASHA, BEN, CHEN], &[(ASHA, BEN), (ASHA, CHEN)]); p[1].register(true); p[0].write(BEN, "hello"); p[1].sync(); p[1].write(ASHA, "hi"); p[0].write(CHEN, "hello Chen"); p[2].sync(); p[2].write(ASHA, "hi Asha"); p[0].sync(); (relay, p) } // RULE: both phones show the same twelve groups of five digits and draw the same code; another pair's differ; asked again, the same. #[test] fn the_same_number_on_both_phones() { let (_relay, p) = chatting(); let (asha, ben) = (p[0].safety(BEN), p[1].safety(ASHA)); let groups = asha["number"].as_array().unwrap(); assert_eq!(groups.len(), 12); assert!(groups.iter().all(|g| g.as_str().is_some_and(|g| g.len() == 5 && g.bytes().all(|b| b.is_ascii_digit()))), "{asha}"); assert_eq!(asha["number"], ben["number"], "Asha's and Ben's phones agree"); assert_eq!(asha["code"], ben["code"]); assert!(asha["code"].as_str().unwrap().starts_with("cotton-safety:")); assert_eq!(asha["verified"], false); assert_eq!(p[0].safety(BEN)["number"], asha["number"], "stable"); assert_ne!(p[0].safety(CHEN)["number"], asha["number"], "another pair"); assert_eq!(asha["words"]["title"], "Safety number"); } // RULE: the screen names them as their chat does: their person in People, else the name their contact was given here. #[test] fn the_screen_names_them_as_their_chat_does() { let (_relay, p) = chatting(); assert_eq!(p[0].safety(BEN)["name"], BEN, "no name here: their number"); p[0].handle .client() .with_writer(|replica| { replica.driver.run("UPDATE cotton_msg_contacts SET display_name = 'Ben from work' WHERE phone_e164 = ?", &[rusqlite::types::Value::Text(BEN.trim_start_matches('+').to_string())]).map(|_| ()).map_err(|e| e.to_string()) }) .unwrap(); let shown = p[0].safety(BEN); assert_eq!(shown["name"], "Ben from work", "{shown}"); assert!(shown["words"]["line"].as_str().unwrap().contains("Ben from work's phone"), "{shown}"); } // RULE: a scan of the other phone's code matches and marks them verified; another chat's code says so; a code that is none is refused. #[test] fn a_scan_of_the_other_phones_code_matches() { let (_relay, p) = chatting(); let thread = p[0].start(BEN); let bens = p[1].safety(ASHA)["code"].as_str().unwrap().to_string(); let chens = p[2].safety(ASHA)["code"].as_str().unwrap().to_string(); let other = p[0].call("chat.safety.scan", json!({ "thread": thread, "code": chens })); assert_eq!((other["result"].as_str(), other["verified"].as_bool()), (Some("notThisChat"), Some(false)), "{other}"); let scanned = p[0].call("chat.safety.scan", json!({ "thread": thread, "code": bens })); assert_eq!((scanned["result"].as_str(), scanned["verified"].as_bool()), (Some("matched"), Some(true)), "{scanned}"); assert!(scanned["said"].as_str().unwrap().contains("verified"), "{scanned}"); assert_eq!(p[0].safety(BEN)["verified"], true); assert_eq!(p[0].call("chat.contact", json!({ "thread": thread }))["verified"], true, "the person's page says so"); assert_eq!(p[0].refused("chat.safety.scan", json!({ "thread": thread, "code": "https://example.test/not-a-code" })), "bad_code"); // Taken back by hand. assert_eq!(p[0].call("chat.safety.verify", json!({ "thread": thread, "verified": false }))["verified"], false); assert_eq!(p[0].safety(BEN)["verified"], false); } // RULE: no line for the first keys a phone learns; once verified, a new key clears the mark and says so once, in that chat, quietly; a later sync says nothing more. #[test] fn a_new_key_clears_the_mark_and_says_so_once() { let (relay, p) = chatting(); assert!(p[0].safety_lines(BEN).is_empty() && p[1].safety_lines(ASHA).is_empty(), "nothing said of the first keys"); let thread = p[0].start(BEN); assert_eq!(p[0].call("chat.safety.verify", json!({ "thread": thread, "verified": true }))["verified"], true); // Asha has read Ben's words. p[0].call("chat.receipt", json!({ "thread": thread })); // Ben sets up Comms on a tablet. let tablet = "ctd_99999999-1111-4111-8111-111111111111_test-credential".to_string(); relay.0.lock().unwrap().devices.push((tablet, BEN.to_string(), format!("{:0>22}", "bentablet"), seal::key_text(&public_of(&scalar(77))))); p[0].later(); p[0].write(BEN, "after the tablet"); let lines = p[0].safety_lines(BEN); assert_eq!(lines.len(), 1, "{lines:?}"); assert!(lines[0].ends_with("safety number changed"), "{lines:?}"); let now = p[0].safety(BEN); assert_eq!((now["verified"].as_bool(), now["wasVerified"].as_bool()), (Some(false), Some(true)), "{now}"); assert!(now["changedAt"].is_string()); assert!(now["words"]["checkAgain"].is_string()); // Drawn as an event line, and the chat is not made unread by it. let page = p[0].call("chat.thread", json!({ "thread": thread })); assert!(page["items"].as_array().unwrap().iter().any(|i| i["item"] == "event" && i["opens"] == "safety" && i["text"].as_str().is_some_and(|t| t.ends_with("safety number changed"))), "{page}"); let list = p[0].call("chat.list", json!({})); let row = list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == json!(thread)).cloned().unwrap_or_else(|| panic!("{list}")); assert_eq!(row["unread"], 0, "{row}"); // A later sync of the same keys says nothing more; nor does Ben's own phone, whose own half changed. p[0].later(); p[0].write(BEN, "and again"); p[0].safety(BEN); assert_eq!(p[0].safety_lines(BEN).len(), 1); p[1].sync(); p[1].later(); p[1].write(ASHA, "from my phone"); assert!(p[1].safety_lines(ASHA).is_empty(), "a person's own new phone is no news to them"); } /// Comms Dev's safety screen (`write_chat_warm_fixture`, the iPhone's `-chat-warm-seed`): the core's own answers /// between invented phones. Kavi (the seed's phone) had verified Asha; Asha then set up Comms on a tablet, so her /// chat says so once and the screen asks to compare again. `scans` are what a scan of each code answers: Asha's /// phone now (`theirs`, a match that verifies her), her phone before the tablet (`old`, not matched) and Meera's /// chat (`other`, not this chat); `refused` a code that is none. pub(crate) fn warm_fixture() -> Value { const KAVI: &str = "+15550100100"; const ASHA_N: &str = "+15550100001"; const MEERA: &str = "+15550100003"; let (relay, p) = safety_world(&[KAVI, ASHA_N, MEERA], &[(KAVI, ASHA_N), (KAVI, MEERA)]); let client = p[0].handle.client(); let ns = crate::phone::cotton_chat::namespace(&client).unwrap(); for (number, name) in [(ASHA_N, "Asha Verma"), (MEERA, "Meera Iyer")] { crate::phone::cotton_chat::write(&client, "test.contact", |ctx| super::super::ensure_contact(ctx, &ns, number, Some(name), None).map(Value::from)).unwrap(); } p[1].register(true); p[0].write(ASHA_N, "hello"); p[1].sync(); p[1].write(KAVI, "hi"); p[0].write(MEERA, "hello"); p[2].sync(); p[2].write(KAVI, "hi"); p[0].sync(); let thread = p[0].start(ASHA_N); p[0].call("chat.safety", json!({ "thread": thread })); assert_eq!(p[0].call("chat.safety.verify", json!({ "thread": thread, "verified": true }))["verified"], true); let old = p[1].safety(KAVI)["code"].clone(); let tablet = "ctd_99999999-1111-4111-8111-111111111112_test-credential".to_string(); relay.0.lock().unwrap().devices.push((tablet, ASHA_N.to_string(), format!("{:0>22}", "ashatablet"), seal::key_text(&public_of(&scalar(78))))); p[0].later(); p[0].write(ASHA_N, "after the tablet"); let changed = p[0].call("chat.safety", json!({ "thread": thread })); assert_eq!((changed["verified"].as_bool(), changed["wasVerified"].as_bool()), (Some(false), Some(true)), "{changed}"); p[1].later(); let theirs = p[1].safety(KAVI)["code"].clone(); let other = p[2].safety(KAVI)["code"].clone(); let mut scans = Vec::new(); for (name, code) in [("old", &old), ("other", &other), ("theirs", &theirs)] { scans.push(json!({ "name": name, "code": code, "answer": p[0].call("chat.safety.scan", json!({ "thread": thread, "code": code })) })); } assert_eq!(scans[2]["answer"]["result"], "matched", "{scans:?}"); let verified = p[0].call("chat.safety", json!({ "thread": thread })); let ask = json!({ "thread": thread, "code": "https://example.test/not-a-code", "privateKey": p[0].secret }); let refusal = crate::phone::cotton_chat::over(&client, "chat.safety.scan", &ask).expect_err("not a code"); json!({ "safety": changed, "verified": verified, "scans": scans, "refused": { "code": refusal.code, "message": refusal.message } }) }