//! Safety numbers on this phone (22 Nov 2026). The //! number, the code and what a scan says are `cotton_core::chat::safety`; //! SEALING.md "Safety numbers" says what they are over, CONTRACT.md "Safety //! number" what the screen draws. //! //! ```text //! chat.safety { thread | number, privateKey } → { thread, name, number: [12 × "12345"], code, verified, changedAt?, wasVerified?, words } //! chat.safety.scan { thread | number, code, privateKey } → { result: matched | notMatched | notThisChat, verified, said } //! chat.safety.verify { thread | number, verified } → { verified } //! ``` //! //! **Kept in the person's own data, so every phone of theirs agrees.** A //! contact's half as this person's phones last saw it is `message_contact. //! safety`; the half they verified is `safety_verified`, a column of its own //! so a phone that saw a change late never writes over a mark made since. //! Verified means the two are the same half: a change clears it by itself. //! //! **A change is said once.** Every time the keys are asked afresh //! ([`observe`], from `cotton_chat::keys_for` and `keys_many`), the half is //! compared with the one kept. The first ever is kept and nothing is said; //! a different one is kept, and their one-to-one chat gets a quiet line under //! an id made of the two halves, so this person's other phones, seeing the //! same change, land the same row once. A person's own devices are no news to //! them: only the other person's half is watched. use rusqlite::types::Value as SqlValue; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use cotton_core::chat::safety::{self, CodeError, Device, Half, Scan}; use cotton_core::chat::{ids, CHANNEL}; use cotton_core::messages::app::list; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::{insert_row, update_row}; use super::cotton_chat::{bad, e164, exists, holds, iso, namespace, not_connected, now_ms, one, person_of, read, refused, text, thread_number, words, write, ws, CONTACTS, MESSAGES, THREADS}; use crate::methods::MethodError; use crate::shell::client::ClientController; /// The methods this module answers (each also in `cotton_chat::METHODS`). pub const METHODS: [&str; 3] = ["chat.safety", "chat.safety.scan", "chat.safety.verify"]; /// The contact's half as last seen. const SEEN: &str = "safety"; /// The half the person verified. const MARK: &str = "safety_verified"; /// A contact's half as this person's phones last saw it. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Seen { v: u8, keys: String, at: i64, #[serde(default, skip_serializing_if = "Option::is_none")] changed_at: Option, /// The half before this one was the one verified. #[serde(default, skip_serializing_if = "std::ops::Not::not")] was_verified: bool, } /// The half the person verified, and when. #[derive(Debug, Clone, Serialize, Deserialize)] struct Mark { v: u8, keys: String, at: i64, } /// What this copy keeps of one contact's safety number. struct Held { contact: String, on_cotton: bool, seen: Option, mark: Option, } impl Held { fn verified(&self) -> bool { matches!((&self.seen, &self.mark), (Some(s), Some(m)) if s.keys == m.keys) } } fn parsed Deserialize<'de>>(raw: Option<&Value>) -> Option { match raw? { Value::String(text) => serde_json::from_str(text).ok(), other @ Value::Object(_) => serde_json::from_value(other.clone()).ok(), _ => None, } } /// The contact's row; none where the copy does not hold the columns yet or there is no contact. fn held(ctx: &mut Ctx<'_>, number: &str) -> Result, String> { if !holds(ctx, CONTACTS, SEEN)? || !holds(ctx, CONTACTS, MARK)? { return Ok(None); } let digits = number.trim_start_matches('+').to_string(); let row = one(ctx, &format!("SELECT id, on_cotton_at, {SEEN}, {MARK} FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits)])?; Ok(row.map(|r| Held { contact: r.get("id").and_then(Value::as_str).unwrap_or_default().to_string(), on_cotton: r.get("on_cotton_at").is_some_and(|v| !v.is_null()), seen: parsed(r.get(SEEN)), mark: parsed(r.get(MARK)), })) } /// Whether the person verified this contact's safety number as it stands (the person's page says it). pub(crate) fn verified_here(ctx: &mut Ctx<'_>, number: &str) -> Result { Ok(held(ctx, number)?.is_some_and(|h| h.verified())) } /// The devices of a keys answer as a sender seals for them: a `c2` record counts where it verifies. fn devices_of(client: &ClientController, keys: &[(String, [u8; 32])]) -> Vec { keys.iter() .map(|(handle, chat)| Device { chat: *chat, c2: super::cotton_chat::record_of(client, handle).and_then(|r| cotton_core::chat::ratchet::verify_record(chat, &r)).map(|v| (v.identity, v.signing)), }) .collect() } /// The keys asked afresh for `number`: their half is compared with the one kept, and a change is said once. pub(crate) fn observe(client: &ClientController, number: &str, devices: &[(String, [u8; 32])]) { if super::cotton_chat::me(client).as_deref() == Some(number) { return; } let keys = safety::half_text(&safety::half(number, &devices_of(client, devices))); let (n, k) = (number.to_string(), keys.clone()); // Most askings find what is kept: read, and write only for news. let news = read(client, "chat.safety.seen", move |ctx| Ok(json!(held(ctx, &n)?.is_some_and(|h| h.on_cotton && h.seen.as_ref().is_none_or(|s| s.keys != k))))); if news.ok().and_then(|v| v.as_bool()) != Some(true) { return; } let Ok(ns) = namespace(client) else { return }; let name = person_of(client, number).1.unwrap_or_else(|| number.to_string()); let (n, now) = (number.to_string(), now_ms(client)); // A copy that cannot keep it now asks again at the next asking; the send or open that asked goes on regardless. let _ = write(client, "chat.safety.seen", move |ctx| note(ctx, &ns, &n, &keys, &name, now)); } fn note(ctx: &mut Ctx<'_>, ns: &str, number: &str, keys: &str, name: &str, now: i64) -> Result { let Some(held) = held(ctx, number)? else { return Ok(Value::Null) }; if !held.on_cotton { return Ok(Value::Null); } let seen = match &held.seen { // The first keys this person's phones learn of them: kept, nothing said. None => Seen { v: safety::VERSION, keys: keys.to_string(), at: now, changed_at: None, was_verified: false }, Some(s) if s.keys == keys => return Ok(Value::Null), Some(before) => { let was_verified = held.verified(); let thread = super::cotton_chat::chat_with(ctx, ns, number)?; if exists(ctx, THREADS, &thread)? { line(ctx, ns, &thread, number, &before.keys, keys, name, was_verified, now)?; } Seen { v: safety::VERSION, keys: keys.to_string(), at: now, changed_at: Some(now), was_verified } } }; let mut patch = Map::new(); patch.insert(SEEN.into(), json!(serde_json::to_string(&seen).unwrap_or_default())); update_row(ctx, CONTACTS, &held.contact, patch).map_err(|f| f.to_string())?; Ok(Value::Null) } /// The chat's one line for this change, under the id every phone of this person makes for it. #[allow(clippy::too_many_arguments)] fn line(ctx: &mut Ctx<'_>, ns: &str, thread: &str, number: &str, before: &str, after: &str, name: &str, was_verified: bool, now: i64) -> Result<(), String> { let external = format!("safety-{}-{}", &before[..16.min(before.len())], &after[..16.min(after.len())]); let id = ids::message_id(ns, number, &external); if exists(ctx, MESSAGES, &id)? { return Ok(()); } let at = iso(now); let mut columns = Map::new(); columns.insert("thread_id".into(), json!(thread)); columns.insert("direction".into(), json!("in")); columns.insert("channel".into(), json!(CHANNEL)); columns.insert("origin".into(), json!("live")); columns.insert("body".into(), json!(list::say(&list::lines(), "app.safety.changed", &[("name", name)]))); columns.insert("external_id".into(), json!(external)); columns.insert("sent_at".into(), json!(at)); // Quiet: an event line, never unread, never the list's last line (`chat_app` leaves `cotton.safety` out of both). columns.insert("meta".into(), json!({ "system": true, "cotton": { "safety": { "wasVerified": was_verified }, "from": number, "written_at": at } })); insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string()) } pub fn over(client: &ClientController, method: &str, request: &Value) -> Result { match method { "chat.safety" => show(client, request), "chat.safety.scan" => scan(client, request), "chat.safety.verify" => verify(client, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a safety number method"))), } } /// The chat and the number it is with: `thread`, or `number`. fn target(client: &ClientController, request: &Value) -> Result<(String, String), MethodError> { match request.get("thread").and_then(Value::as_str) { Some(thread) => Ok((thread.to_string(), thread_number(client, thread)?)), None => { let number = e164(text(request, "number")?).ok_or_else(|| words("bad_number", "That isn't a phone number Cotton can use. Start it with + and the country code."))?; Ok((super::cotton_chat::chat_with_number(client, &namespace(client)?, &number), number)) } } } fn kept(client: &ClientController, number: &str) -> Result, MethodError> { let n = number.to_string(); let found = read(client, "chat.safety", move |ctx| { Ok(match held(ctx, &n)? { Some(h) => json!({ "contact": h.contact, "onCotton": h.on_cotton, "seen": h.seen.map(|s| serde_json::to_value(s).unwrap_or_default()), "mark": h.mark.map(|m| serde_json::to_value(m).unwrap_or_default()) }), None => Value::Null, }) })?; if found.is_null() { return Ok(None); } Ok(Some(Held { contact: found["contact"].as_str().unwrap_or_default().to_string(), on_cotton: found["onCotton"] == json!(true), seen: parsed(found.get("seen")), mark: parsed(found.get("mark")) })) } /// Both halves as this phone holds them now, the contact's asked afresh (which notes a change). struct Pair { me: String, mine: Half, them: String, theirs: Half, } fn pair(client: &ClientController, request: &Value, number: &str) -> Result { let secret = super::cotton_chat::private_key_of(request)?; let me = super::cotton_chat::my_number(client).ok_or_else(not_connected)?; if me == number { return Err(words("own_number", "That's your own number.")); } // Someone not on Cotton has no keys to compare: a lookup would answer made-up ones. if !kept(client, number)?.is_some_and(|h| h.on_cotton) { return Err(words("not_on_cotton", &list::say(&list::lines(), "state.waiting", &[]))); } let (theirs, own) = super::cotton_chat::keys_now(client, number).map_err(refused)?; let chat = cotton_core::vault::wrap::public_of(&secret); let mut mine = devices_of(client, &own); mine.push(Device { chat, c2: super::chat_ratchet::own_c2(client, &secret) }); Ok(Pair { mine: safety::half(&me, &mine), theirs: safety::half(number, &devices_of(client, &theirs)), me, them: number.to_string() }) } /// The name this phone knows them by, as their chat says it: their person in People, else the contact's own name. fn name_of(client: &ClientController, number: &str) -> String { if let Some(name) = person_of(client, number).1 { return name; } let digits = number.trim_start_matches('+').to_string(); let found = read(client, "chat.safety.name", move |ctx| { Ok(one(ctx, &format!("SELECT display_name FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.clone())])? .and_then(|r| r.get("display_name").and_then(Value::as_str).map(str::to_string)) .map_or(Value::Null, Value::from)) }); found.ok().and_then(|v| v.as_str().map(str::to_string)).filter(|n| !n.trim().is_empty() && e164(n).as_deref() != Some(number)).unwrap_or_else(|| number.to_string()) } fn show(client: &ClientController, request: &Value) -> Result { let (thread, number) = target(client, request)?; let p = pair(client, request, &number)?; let held = kept(client, &number)?; let verified = held.as_ref().is_some_and(Held::verified); let seen = held.as_ref().and_then(|h| h.seen.clone()); let name = name_of(client, &number); let lines = list::lines(); let say = |key: &str| list::say(&lines, key, &[("name", &name)]); let mut words = json!({ "title": say("app.safety.title"), "line": say("app.safety.line"), "changes": say("app.safety.changes"), "scan": say("app.safety.scan"), "verify": say("app.safety.verify"), "unverify": say("app.safety.unverify"), "verified": say("app.safety.verified"), }); let was_verified = seen.as_ref().is_some_and(|s| s.was_verified); if was_verified && !verified { words["checkAgain"] = json!(say("app.safety.check_again")); } let mut answer = json!({ "thread": thread, "name": name, "number": safety::number(&p.me, &p.mine, &p.them, &p.theirs), "code": safety::code(&p.me, &p.mine, &p.them, &p.theirs), "verified": verified, "words": words, }); if let Some(at) = seen.as_ref().and_then(|s| s.changed_at) { answer["changedAt"] = json!(iso(at)); answer["wasVerified"] = json!(was_verified); } Ok(answer) } fn scan(client: &ClientController, request: &Value) -> Result { let (_, number) = target(client, request)?; let code = text(request, "code")?.to_string(); let p = pair(client, request, &number)?; let lines = list::lines(); let name = name_of(client, &number); let say = |key: &str| list::say(&lines, key, &[("name", &name)]); let result = match safety::scan(&p.me, &p.mine, &p.them, &p.theirs, &code) { Ok(result) => result, Err(CodeError::Malformed) => return Err(words("bad_code", &say("app.safety.unreadable"))), Err(CodeError::OtherVersion(_)) => return Err(words("other_version", &say("app.safety.other_version"))), }; if result == Scan::Matched { mark(client, &number, true)?; } let verified = kept(client, &number)?.is_some_and(|h| h.verified()); let (result, said) = match result { Scan::Matched => ("matched", say("app.safety.matched")), Scan::NotMatched => ("notMatched", say("app.safety.not_matched")), Scan::NotThisChat => ("notThisChat", say("app.safety.not_this_chat")), }; Ok(json!({ "result": result, "verified": verified, "said": said })) } fn verify(client: &ClientController, request: &Value) -> Result { let (_, number) = target(client, request)?; let on = request.get("verified").and_then(Value::as_bool).ok_or_else(|| bad("verified", "true or false"))?; mark(client, &number, on)?; Ok(json!({ "verified": kept(client, &number)?.is_some_and(|h| h.verified()) })) } /// The person's mark: the half last seen (what `chat.safety` just showed), or none. fn mark(client: &ClientController, number: &str, on: bool) -> Result<(), MethodError> { let held = kept(client, number)?.ok_or_else(|| MethodError::new("not_ready", "this copy keeps no safety number for them yet"))?; let value = match (on, &held.seen) { (true, Some(seen)) => json!(serde_json::to_string(&Mark { v: safety::VERSION, keys: seen.keys.clone(), at: now_ms(client) }).unwrap_or_default()), (true, None) => return Err(MethodError::new("not_ready", "chat.safety first: no safety number is kept for them yet")), (false, _) => Value::Null, }; let contact = held.contact; write(client, "chat.safety.verify", move |ctx| { let mut patch = Map::new(); patch.insert(MARK.into(), value.clone()); update_row(ctx, CONTACTS, &contact, patch).map_err(|f| f.to_string())?; Ok(Value::Null) })?; Ok(()) }