//! The `c2` box on this phone (`assets/design/chat/SEALING.md`): the ratchet //! file, what each device's keys answer says of `c2`, claiming one-time keys, //! and the one place every box is sealed and opened. The ratchet itself is the //! core's ([`cotton_core::chat::ratchet`]). //! //! **Which box.** This phone seals `c2` for a device whose record verifies //! when this phone itself speaks `c2` (a shell that said `ratchet: true` at //! `chat.register`, so a ratchet file is here), and `c1` for every other one, //! unless that device is pinned: one that spoke `c2` with this phone is never //! sealed `c1` for again, and its `c1` boxes are dropped. //! //! **The file.** `client//chat-ratchet-.c2`, sealed under the chat //! key, written whole (to a sibling, then renamed) after every change and //! before any envelope it sealed leaves the phone, so a crash never reuses a //! message key. One lock for every phone in this process: each change is //! work on the CPU alone, never a network call. use std::collections::HashMap; use std::path::PathBuf; use std::sync::Mutex; use serde_json::{json, Map, Value}; use cotton_client::transport::object::ObjectRefusal; use cotton_core::chat::payload::{Item, Payload}; use cotton_core::chat::ratchet::{self, OpenError, Prekey, Record, SealError, Store, Verified}; use cotton_core::chat::seal; use crate::methods::MethodError; use crate::shell::client::ClientController; /// The ratchets this process holds, by file: the lock every seal and open takes. static STORES: Mutex>> = Mutex::new(None); /// The refusal of a message to a device that spoke `c2` and no longer offers it. pub const DOWNGRADE: &str = "downgrade"; fn path(client: &ClientController, secret: &[u8; 32]) -> PathBuf { client.layout().client_dir().join(ratchet::store_name(&cotton_core::vault::wrap::public_of(secret))) } /// Work on this phone's ratchet: `None` when it has none and `create` is false. The work answers whether it changed it. fn with_store(client: &ClientController, secret: &[u8; 32], create: bool, work: impl FnOnce(&mut Store) -> (R, bool)) -> Result, String> { let file = path(client, secret); let mut held = STORES.lock().unwrap_or_else(|p| p.into_inner()); let stores = held.get_or_insert_with(HashMap::new); if !stores.contains_key(&file) { let read = std::fs::read(&file).ok().and_then(|bytes| Store::from_bytes(secret, &bytes)); match read { Some(store) => { stores.insert(file.clone(), store); } None if create => { if file.exists() { // A file this chat key cannot open is not this key's: it is set aside, never read again. // not a copy: the ratchet's own file. let _ = std::fs::rename(&file, file.with_extension("c2.unreadable")); } stores.insert(file.clone(), Store::new(chrono::Utc::now().timestamp_millis())); save(&file, secret, &stores[&file])?; } None => return Ok(None), } } let store = stores.get_mut(&file).expect("held"); let (answer, changed) = work(store); if changed { save(&file, secret, store)?; } Ok(Some(answer)) } fn save(file: &std::path::Path, secret: &[u8; 32], store: &Store) -> Result<(), String> { let bytes = store.to_bytes(secret).ok_or("the ratchet could not be sealed")?; if let Some(parent) = file.parent() { std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; } let next = file.with_extension("c2.next"); // not a copy: the ratchet's own file. std::fs::write(&next, bytes).map_err(|e| format!("{}: {e}", next.display()))?; // not a copy: the ratchet's own file. std::fs::rename(&next, file).map_err(|e| format!("{}: {e}", file.display())) } /// Tests: every ratchet read again from its file. #[cfg(test)] pub(crate) fn forget_cached() { *STORES.lock().unwrap_or_else(|p| p.into_inner()) = None; } /// Whether this phone speaks `c2` (its shell said so once, and its ratchet file is here). pub(crate) fn speaks(client: &ClientController, secret: &[u8; 32]) -> bool { with_store(client, secret, false, |_| ((), false)).ok().flatten().is_some() } /// `chat.ratchet { privateKey }`: whether this phone speaks c2 and what its ratchet holds (a walk's evidence; no key, no word). pub(crate) fn status(client: &ClientController, secret: &[u8; 32]) -> Result { let held = with_store(client, secret, false, |store| (store.summary(), false)).map_err(|e| MethodError::new("unreadable", e))?; Ok(match held { Some((devices, sessions, pinned, opened)) => json!({ "speaks": true, "devices": devices, "sessions": sessions, "pinned": pinned, "opened": opened }), None => json!({ "speaks": false }), }) } /// This phone's own `c2` identity and signing keys, as its record publishes them beside its chat key; none /// where it speaks only `c1` (`chat.safety`: this device's part of the person's half). pub(crate) fn own_c2(client: &ClientController, secret: &[u8; 32]) -> Option<([u8; 32], [u8; 32])> { let chat_pub = cotton_core::vault::wrap::public_of(secret); let record = with_store(client, secret, false, |store| (store.record(&chat_pub), false)).ok().flatten()?; ratchet::verify_record(&chat_pub, &record).map(|v| (v.identity, v.signing)) } /// What `chat.register` publishes for a shell that said `ratchet: true`: the record, the fallback key and the /// one-time keys not yet published. [`published`] once the object took them. pub(crate) fn register_body(client: &ClientController, secret: &[u8; 32]) -> Result { let chat_pub = cotton_core::vault::wrap::public_of(secret); let now = super::cotton_chat::now_ms(client); with_store(client, secret, true, |store| { let record = store.record(&chat_pub); let fallback = store.fallback(now); let prekeys = store.prekeys(0); let mut body = json!({ "identity": record.identity, "signing": record.signing, "sig": record.sig, "prekeys": prekeys }); if let Some(fallback) = fallback { body["fallback"] = json!({ "key": fallback.key, "sig": fallback.sig }); } (body, true) }) .map_err(|e| MethodError::new("unwritable", e))? .ok_or_else(|| MethodError::new("unwritable", "no ratchet")) } /// The keys handed to the object are there now. pub(crate) fn published(client: &ClientController, secret: &[u8; 32]) { let _ = with_store(client, secret, false, |store| { store.published(); ((), true) }); } /// The object says this device has `left` one-time keys: below the mark, more go up. pub(crate) fn top_up(client: &ClientController, secret: &[u8; 32], left: u64) { if left as usize >= ratchet::PREKEYS_LOW { return; } let keys = with_store(client, secret, false, |store| (store.prekeys(left as usize), true)).ok().flatten().unwrap_or_default(); if keys.is_empty() { return; } if super::cotton_chat::ask(client, "POST", "/v1/chat/prekeys", Some(&json!({ "prekeys": keys }))).is_ok() { published(client, secret); } } /// The `c2` records a keys answer carries, by device handle (a device without one is answered as none). pub(crate) fn records_of(list: &Value) -> Vec<(String, Option)> { list.as_array() .into_iter() .flatten() .filter_map(|k| Some((k["device"].as_str()?.to_string(), k.get("c2").and_then(|c| serde_json::from_value(c.clone()).ok())))) .collect() } /// One device to seal for: the number it belongs to, its handle and its chat key. pub(crate) struct Target<'a> { pub number: &'a str, pub handle: &'a str, pub key: &'a [u8; 32], } /// The record of a device, as this phone last heard it and checked against its chat key. fn verified(client: &ClientController, handle: &str, key: &[u8; 32]) -> Option { let record = super::cotton_chat::record_of(client, handle)?; ratchet::verify_record(key, &record) } /// One payload sealed for each of these devices: `c2` where both sides speak it, `c1` otherwise; a device that /// spoke `c2` and offers it no longer refuses the whole envelope (`downgrade`), never falling back. pub(crate) fn seal_boxes(client: &ClientController, secret: &[u8; 32], targets: &[Target<'_>], payload: &Payload) -> Result, ObjectRefusal> { let bytes = payload.bytes(); let speaks = speaks(client, secret); let devices: Vec<(&Target<'_>, Option)> = targets.iter().map(|t| (t, if speaks { verified(client, t.handle, t.key) } else { None })).collect(); // The devices this phone has no session with yet: one key claimed for each, by number, before the lock. let mut claimed: HashMap = HashMap::new(); if speaks { let needing: Vec<(&str, &str)> = with_store(client, secret, false, |store| (devices.iter().filter_map(|(t, v)| v.filter(|v| store.needs_prekey(v)).map(|_| (t.number, t.handle))).collect::>(), false)) .map_err(local)? .unwrap_or_default(); let mut by_number: HashMap<&str, Vec<&str>> = HashMap::new(); for (number, handle) in needing { by_number.entry(number).or_default().push(handle); } for (number, handles) in by_number { for chunk in handles.chunks(16) { let answer = super::cotton_chat::ask(client, "POST", "/v1/chat/prekeys/claim", Some(&json!({ "number": number, "devices": chunk })))?; for (handle, prekey) in answer["prekeys"].as_object().into_iter().flatten() { if let Ok(prekey) = serde_json::from_value::(prekey.clone()) { claimed.insert(handle.clone(), prekey); } } } } } let sealed = with_store(client, secret, false, |store| { let mut out = Map::new(); for (target, record) in &devices { if let Some(device) = record { match store.seal(target.handle, device, claimed.get(target.handle), &bytes) { Ok(b) => { out.insert(target.handle.to_string(), json!(b)); continue; } // No key could be had for it (none left, not even its fallback): never c1 for a pinned device. Err(SealError::NeedPrekey | SealError::BadPrekey) if store.pinned(target.handle) => return (Err(downgrade()), true), Err(_) => {} } } else if store.pinned(target.handle) { return (Err(downgrade()), true); } if let Some(b) = seal::seal(secret, target.key, &bytes) { out.insert(target.handle.to_string(), json!(b)); } } (Ok(out), true) }) .map_err(local)?; match sealed { Some(result) => result, // This phone speaks c1 alone. None => Ok(targets.iter().filter_map(|t| seal::seal(secret, t.key, &bytes).map(|b| (t.handle.to_string(), json!(b)))).collect()), } } fn downgrade() -> ObjectRefusal { ObjectRefusal { status: 409, code: DOWNGRADE.into(), message: "This message wasn't sent: one of their phones stopped using the stronger lock it used with you.".into() } } fn local(message: String) -> ObjectRefusal { ObjectRefusal { status: 0, code: "local".into(), message } } /// What opening a box came to. pub(crate) enum Opened { /// The payload, checked inside against outside. Payload(Payload), /// Dropped (not for this device, a replay, an unknown sealer, a refused downgrade). Dropped, /// A `c2` box no session opens: the pair is due a fresh session, told to the sealer. Unreadable, } /// The name an envelope's opened words are kept under until it is taken. pub(crate) fn item_key(item: &Item) -> String { format!("{}:{}:{}:{}:{}", item.kind.as_str(), item.id, item.peer, item.out, item.group.as_deref().unwrap_or("")) } /// Open one item from devices `senders` (the sealer's number's handles and chat keys): checked inside against outside. pub(crate) fn open(client: &ClientController, secret: &[u8; 32], item: &Item, me: &str, senders: &[(String, [u8; 32])]) -> Opened { if ratchet::is_c2(&item.sealed) { let verified: Vec<(String, Verified)> = senders.iter().filter_map(|(h, k)| verified(client, h, k).map(|v| (h.clone(), v))).collect(); let now = super::cotton_chat::now_ms(client); let key = item_key(item); let opened = with_store(client, secret, false, |store| { let result = store.open(&key, &item.sealed, &verified, now); let changed = !matches!(result, Err(OpenError::Unreadable | OpenError::UnknownSender)); (result, changed) }); return match opened { Ok(Some(Ok(o))) => match serde_json::from_slice::(&o.payload) { Ok(payload) if cotton_core::chat::payload::check(&payload, item, me).is_ok() => Opened::Payload(payload), _ => Opened::Dropped, }, Ok(Some(Err(OpenError::Undecryptable { .. }))) => Opened::Unreadable, _ => Opened::Dropped, }; } let Some(opened) = seal::open(secret, &item.sealed) else { return Opened::Dropped }; let mine = cotton_core::vault::wrap::public_of(secret); let handle = senders.iter().find(|(_, k)| k == &opened.sender).map(|(h, _)| h.clone()); let Some(handle) = handle.or_else(|| (item.out && opened.sender == mine).then(String::new)) else { return Opened::Dropped }; // A device that spoke c2 with this phone is never read in c1 again. let pinned = with_store(client, secret, false, |store| (store.pinned(&handle), false)).ok().flatten().unwrap_or(false); if pinned { return Opened::Dropped; } match cotton_core::chat::payload::accept(secret, item, me, &[opened.sender]) { Ok(payload) => Opened::Payload(payload), Err(_) => Opened::Dropped, } } /// These envelopes were taken: the words kept for them go. pub(crate) fn taken(client: &ClientController, secret: &[u8; 32], keys: &[String]) { if keys.is_empty() { return; } let _ = with_store(client, secret, false, |store| { let changed = store.taken(keys.iter().map(String::as_str)); ((), changed) }); } /// The sealer identity a c2 box names, for a sender lookup. pub(crate) fn sealer_of(item: &Item) -> Option<[u8; 32]> { ratchet::sender_of(&item.sealed) } /// Whether a device's record (as last heard) names this identity. pub(crate) fn names(client: &ClientController, handle: &str, key: &[u8; 32], identity: &[u8; 32]) -> bool { verified(client, handle, key).is_some_and(|v| &v.identity == identity) } /// The method an iPhone's notification extension calls, through `cotton_call` with a null handle. pub const PEEK: &str = "chat.peek"; /// `chat.peek { privateKey, dir, item, me? }` → `{ opened: false }` or `{ opened: true, from, kind, body?, group?, /// pictures, out }`: one held envelope's c2 box opened **read-only** from the ratchet file in `dir` (the app's /// `client/` folder, in the app group), to draw an alert on the lock screen. Nothing is written: the message keys /// stay for the app, which opens the box for real at its next inbox pass (the envelope is held until then). Opens only /// on a session the ratchet already holds, or a box the app opened and has not had taken; a c1 box is the extension's /// own Swift opener's (`ChatBox`). `me` (this phone's number), when given, checks the box's inside fully. pub fn peek(request: &Value) -> Result { let secret = request .get("privateKey") .and_then(Value::as_str) .and_then(seal::key_from_text) .map(zeroize::Zeroizing::new) .ok_or_else(|| MethodError::new("bad_request", "privateKey: 32 bytes as base64url"))?; let dir = request.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| MethodError::new("bad_request", "dir: the folder the ratchet file is in"))?; let item: Item = serde_json::from_value(request.get("item").cloned().unwrap_or(Value::Null)).map_err(|_| MethodError::new("bad_request", "item: the held envelope { id, kind, peer, out, box, at, group? }"))?; let closed = || Ok(json!({ "opened": false })); if !ratchet::is_c2(&item.sealed) { return closed(); } let file = std::path::Path::new(dir).join(ratchet::store_name(&cotton_core::vault::wrap::public_of(&secret))); let Some(store) = std::fs::read(&file).ok().and_then(|bytes| Store::from_bytes(&secret, &bytes)) else { return closed() }; let Some((_, plain)) = store.peek(&item_key(&item), &item.sealed) else { return closed() }; let Ok(payload) = serde_json::from_slice::(&plain) else { return closed() }; let fits = match request.get("me").and_then(Value::as_str) { Some(me) => cotton_core::chat::payload::check(&payload, &item, me).is_ok(), None => payload.id == item.id && payload.kind == item.kind && payload.group == item.group && (item.out || payload.from == item.peer), }; if !fits { return closed(); } let mut answer = json!({ "opened": true, "from": payload.from, "kind": item.kind.as_str(), "out": item.out, "pictures": payload.pictures.len() }); if let Some(body) = &payload.body { answer["body"] = json!(body); } if let Some(group) = &payload.group { answer["group"] = json!(group); } Ok(answer) }