//! Send, sealed all the way (ruling R5, 15 Nov 2026): the //! phone's half of the one sharing key rule. //! //! The SENDER'S phone lays the payload from its own plain copy through the //! one rule (cotton-rules `send.contents`, the same code the Worker ran until //! now), seals it to the receiver's sharing key (cotton-core seal/share.rs, //! `p1:` bound to `send:`) and posts only the box and its outside. The //! RECEIVER'S phone opens the box with its own sharing key, plans the landing //! over its own copy (`send.held`, `send.keep`), asks its object to copy the //! bytes, and writes the rows itself: its sync seals them under its own data //! key like any write. Neither object ever holds a key that opens a send. //! //! The sharing key is derived from the data key ([`sharing`]): a phone that //! reads its sealed tables holds it, and posts its public half to its object //! once per launch ([`post_key`]). use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::{Mutex, OnceLock}; use serde_json::{json, Map, Value}; use zeroize::Zeroizing; use cotton_core::cotton_rules::send::{self as rule, Land, Landing, Make, Payload, Reads, Refused, Tables}; use cotton_core::definitions::TableDefinition; use cotton_core::seal::share::{key_from_text, key_text, open_from_person, seal_to_person, sharing_secret}; use cotton_core::vault::wrap::public_of; use super::cotton_chat::{ask, refused, words}; use crate::methods::MethodError; use crate::shell::client::ClientController; /// What a phone with no data key is told: it cannot seal or open a send. pub const KEY_MISSING: &str = "seal_key_missing"; /// The context a send's box is bound to. pub fn context(id: &str) -> String { format!("send:{id}") } /// This person's sharing key on this phone: the secret half and the public /// half's text. Refused by name when the phone holds no data key yet. pub fn sharing(client: &ClientController) -> Result<(Zeroizing<[u8; 32]>, String), MethodError> { use cotton_client::seal::DataKeyStore as _; let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?; let dk = client .data_keys() .data_key(&database) .map_err(|why| MethodError::new("could_not_read", why))? .ok_or_else(|| words(KEY_MISSING, "Unlock once on this phone: it holds no key yet to seal what it sends or open what it is sent."))?; let secret = sharing_secret(&dk, &database).map_err(|e| MethodError::new(e.code(), e.to_string()))?; let public = key_text(&public_of(&secret)); Ok((secret, public)) } /// This person's signing key's public half (cotton-core `seal::shared_album`), posted beside the sharing key so a /// shared album's members verify what they add. None while the phone holds no data key. pub fn sign_public(client: &ClientController) -> Option { use cotton_client::seal::DataKeyStore as _; let database = client.current_database().ok()?; let dk = client.data_keys().data_key(&database).ok()??; cotton_core::seal::shared_album::signing_public(&dk, &database).ok() } /// What a phone posts to `/v1/send/key`: the sharing key, and the signing key beside it. fn key_body(client: &ClientController, public: &str) -> Value { match sign_public(client) { Some(sign) => json!({ "key": public, "sign": sign }), None => json!({ "key": public }), } } /// The sharing key, its public half posted to this person's object once per /// launch (every phone of the person posts the same one), and the secret. pub fn post_key(client: &ClientController) -> Result, MethodError> { let (secret, public) = sharing(client)?; let mark = format!("{}:{public}", client.current_database().unwrap_or_default()); if !posted().lock().map(|p| p.contains(&mark)).unwrap_or(false) { ask(client, "POST", "/v1/send/key", Some(&key_body(client, &public))).map_err(refused)?; if let Ok(mut p) = posted().lock() { p.insert(mark); } } Ok(secret) } /// The keys posted this launch, by `:`. fn posted() -> &'static Mutex> { static POSTED: OnceLock>> = OnceLock::new(); POSTED.get_or_init(|| Mutex::new(HashSet::new())) } /// [`post_key`] for a caller that only wants it posted, never waited on (`seal.status`, OFFLINE START, 26 Nov 2026): /// the key is worked out here, from this phone alone, and the POST goes on a thread of its own, one at a time per /// key. A read that asked the object on its own thread waited out a phone with no network's lookup, and on Android /// the four threads every screen's call shares were filled by it; `shell.lines` waited 7 s behind it at a cold start. /// Offline, it fails on its thread and is posted again by the next status read, or by a send that needs it. pub fn post_key_beside(client: &ClientController) { static POSTING: OnceLock>> = OnceLock::new(); let posting = POSTING.get_or_init(|| Mutex::new(HashSet::new())); let Ok((_, public)) = sharing(client) else { return }; let mark = format!("{}:{public}", client.current_database().unwrap_or_default()); if posted().lock().map(|p| p.contains(&mark)).unwrap_or(true) { return; } let Some(door) = client.object_door() else { return }; let body = key_body(client, &public); if !posting.lock().map(|mut p| p.insert(mark.clone())).unwrap_or(false) { return; } let spawned = std::thread::Builder::new().name("cotton-send-key".into()).spawn({ let mark = mark.clone(); move || { let sent = door.address.send(door.exchange.as_ref(), "POST", "/v1/send/key", cotton_client::transport::object::bearer(&door.credential), Some(&body)); match sent { Ok(_) => { if let Ok(mut p) = posted().lock() { p.insert(mark.clone()); } } Err(refusal) => tracing::info!("send key: not posted yet ({}); the next status read posts it", refusal.message), } if let Ok(mut p) = POSTING.get_or_init(|| Mutex::new(HashSet::new())).lock() { p.remove(&mark); } } }); if spawned.is_err() { if let Ok(mut p) = posting.lock() { p.remove(&mark); } } } /// Every table definition of this database. pub fn definitions(client: &ClientController) -> Result, MethodError> { let mut tables = Vec::new(); client .read_rows("send.tables", &mut |ctx| { tables = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?.definitions; Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?; Ok(tables) } /// The tables as the rule reads them on this phone: its copy is plain, so a /// table sealed on the object reads as sendable; a table of secrets never. pub fn tables_of(defs: &[TableDefinition]) -> Tables { defs.iter().map(|t| (t.id.clone(), t.send_shape())).collect() } /// The rule's reads over this phone's own copy, through the generic record /// verbs; media weights from the object (`POST /v1/send/weigh`), asked once. pub struct PhoneReads<'a> { client: &'a ClientController, weights: Option>>, asked: Mutex>, } impl<'a> PhoneReads<'a> { pub fn new(client: &'a ClientController) -> PhoneReads<'a> { PhoneReads { client, weights: None, asked: Mutex::new(Vec::new()) } } fn list(&self, table: &str, equals: &Map) -> Result>, String> { let mut out = Vec::new(); for page in 0..50 { let listed = super::records::call(self.client, "records.list", &json!({ "table": table, "where": equals, "page": page, "limit": 200 })).map_err(|e| e.message)?; let records = listed["records"].as_array().cloned().unwrap_or_default(); let n = records.len(); for r in records { let mut data = r.get("data").and_then(Value::as_object).cloned().unwrap_or_default(); if let Some(id) = r.get("id") { data.insert("id".into(), id.clone()); } out.push(data); } if n < 200 { break; } } Ok(out) } } impl Reads for PhoneReads<'_> { fn row(&self, table: &str, id: &str) -> Result>, String> { match super::records::call(self.client, "records.get", &json!({ "table": table, "id": id })) { Ok(record) => { let mut data = record.get("data").unwrap_or(&record).as_object().cloned().unwrap_or_default(); data.remove("id"); Ok(Some(data)) } Err(e) if crate::phone::copy_standing::absent(&e.code) => Ok(None), Err(e) => Err(e.message), } } fn linked(&self, table: &str, column: &str, id: &str) -> Result>, String> { let mut equals = Map::new(); equals.insert(column.into(), json!(id)); self.list(table, &equals) } fn find(&self, table: &str, equals: &Map) -> Result, String> { Ok(self.list(table, equals)?.into_iter().filter_map(|r| r.get("id").and_then(Value::as_str).map(str::to_string)).collect()) } fn weigh(&self, key: &str, folder: bool) -> Result, String> { match &self.weights { Some(weights) => Ok(weights.get(&(key.to_string(), folder)).copied().flatten()), None => { if let Ok(mut asked) = self.asked.lock() { asked.push((key.to_string(), folder)); } Ok(Some(0)) } } } } fn rule_refusal(r: Refused) -> MethodError { words(r.code, &r.words) } /// What one record sends, laid on this phone from its plain copy: the rule /// run once to learn the media keys it names, the object asked their /// weights, and run again over them. pub fn compose(client: &ClientController, tables: &Tables, table: &str, record: &str, id: &str, from: rule::From) -> Result { let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?; let make = Make { id: id.into(), table: table.into(), record: record.into(), from, made_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), source_database: database, tables: tables.clone() }; let mut reads = PhoneReads::new(client); let first = rule::contents(&make, &reads).map_err(rule_refusal)?; let asked = reads.asked.lock().map(|a| a.clone()).unwrap_or_default(); if asked.is_empty() { return Ok(first); } let files: Vec = asked.iter().map(|(key, folder)| json!({ "key": key, "folder": folder })).collect(); let weighed = ask(client, "POST", "/v1/send/weigh", Some(&json!({ "files": files }))).map_err(refused)?; let mut weights = HashMap::new(); for f in weighed["files"].as_array().into_iter().flatten() { if let Some(key) = f["key"].as_str() { weights.insert((key.to_string(), f["folder"] == json!(true)), f["bytes"].as_u64()); } } reads.weights = Some(weights); rule::contents(&make, &reads).map_err(rule_refusal) } /// Each file the payload names that this person's phone sealed under its /// own per-file key (R6: FK from the data key and the object key), that key /// as text: it rides inside the box, so the receiver opens those bytes and /// nobody else does (e2e-files' seam: one file's key hands nothing else). pub fn file_keys(client: &ClientController, payload: &Payload) -> Result, MethodError> { use cotton_client::seal::DataKeyStore as _; let mut out = Map::new(); let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?; let Some(dk) = client.data_keys().data_key(&database).map_err(|why| MethodError::new("could_not_read", why))? else { return Ok(out) }; for file in payload.files.iter().filter(|f| !f.folder && cotton_client::media::sealed::is_person_file(&database, &f.key)) { let root = cotton_client::media::sealed::file_root_for(&dk, &database, &file.key).map_err(|e| MethodError::new(e.code(), e.to_string()))?; out.insert(file.key.clone(), json!(cotton_core::seal::file::person_file_key(&root, &file.key).text())); } Ok(out) } /// The payload and its files' keys sealed to the receiver's sharing key (text, as the object hands it), bound to the send. pub fn seal_payload(secret: &[u8; 32], receiver: &str, payload: &Payload, file_keys: &Map) -> Result { let key = key_from_text(receiver).ok_or_else(|| words("bad_key", "That person's sharing key does not read."))?; let bytes = serde_json::to_vec(&json!({ "send": payload, "file_keys": file_keys })).map_err(|e| MethodError::new("could_not_seal", e.to_string()))?; seal_to_person(secret, &key, &context(&payload.id), &bytes).map_err(|e| MethodError::new(e.code(), e.to_string())) } /// An arrival's box opened with this person's sharing key and read as a /// payload of tables this phone receives; refused unless it is the send the /// object says it is, from the number the object says it came from. pub fn open_payload(secret: &[u8; 32], item: &Value, tables: &Tables) -> Result { open_sent(secret, item, tables).map(|(payload, _)| payload) } /// [`open_payload`] with the files' keys the box carried (each sent media key to its FK as text). pub fn open_sent(secret: &[u8; 32], item: &Value, tables: &Tables) -> Result<(Payload, Map), MethodError> { let id = item["id"].as_str().unwrap_or_default(); let boxed = item["box"].as_str().ok_or_else(|| words("seal_does_not_open", "This send does not open here."))?; let opened = open_from_person(secret, boxed, &context(id)).map_err(|e| MethodError::new(e.code(), e.to_string()))?; let mut value: Value = serde_json::from_slice(&opened.payload).map_err(|_| words("seal_does_not_open", "This send does not open here."))?; let keys = value.get("file_keys").and_then(Value::as_object).cloned().unwrap_or_default(); if value.get("send").is_some() { value = value["send"].take(); } let payload = rule::read_payload(value, tables).map_err(rule_refusal)?; if payload.id != id || Some(payload.from.number.as_str()) != item["from"].as_str() || payload.root.table != item["table"].as_str().unwrap_or_default() { return Err(words("seal_does_not_open", "This send does not open here.")); } Ok((payload, keys)) } /// The most bytes a Keep reseals on the phone in one go; a larger file is copied by the object as it lies. pub const RESEAL_MAX: usize = 256 * 1024 * 1024; /// A file a Keep copies that the sender sealed under their own key: fetched /// through the send, opened with the key the box carried (bound to the /// sender's object key), sealed again under this person's own key for where /// it lands, and stored on this person's object. True when it was; false /// when it is not sealed (a clear file the object copies as it lies). pub fn reseal(client: &ClientController, send: &str, copy: &rule::Copy, fk: &str) -> Result { use cotton_client::seal::DataKeyStore as _; if copy.folder || copy.bytes as usize > RESEAL_MAX { return Ok(false); } let door = client.object_door().ok_or_else(super::cotton_chat::not_connected)?; let path = format!("/v1/send/{send}/media?key={}&whole=1", enc(©.from)); let (status, sealed) = door.address.send_bytes(door.exchange.as_ref(), "GET", &path, cotton_client::transport::object::bearer(&door.credential), None).map_err(refused)?; if status != 200 || !sealed.starts_with(cotton_core::seal::file::MAGIC) { return Ok(false); } let theirs = cotton_core::seal::file::FileKey::read(fk).map_err(|e| MethodError::new(e.code(), e.to_string()))?; let mut plain = Vec::new(); cotton_core::seal::file::open_file(&theirs, ©.from, &mut sealed.as_slice(), &mut plain).map_err(|e| MethodError::new(e.code(), e.to_string()))?; let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?; let dk = client.data_keys().data_key(&database).map_err(|why| MethodError::new("could_not_read", why))?.ok_or_else(|| words(KEY_MISSING, "Unlock once on this phone: it holds no key yet to keep what it is sent."))?; let root = cotton_client::media::sealed::file_root_for(&dk, &database, ©.to).map_err(|e| MethodError::new(e.code(), e.to_string()))?; let mine = cotton_core::seal::file::person_file_key(&root, ©.to); let mut resealed = Vec::with_capacity(sealed.len()); cotton_core::seal::file::seal_file(&mine, ©.to, &mut plain.as_slice(), &mut resealed).map_err(|e| MethodError::new(e.code(), e.to_string()))?; drop(plain); super::cotton_chat::put_typed(client, &format!("/v1/media/{}", copy.to), &resealed, cotton_client::media::sealed::SEALED_FILE_TYPE).map_err(refused)?; Ok(true) } /// The tables whose records enter only as their bytes, through the phone's own capture (a photo): a send of one /// lands by capturing the bytes it carries, never as a record written. pub const CAPTURED: [&str; 1] = ["photo"]; /// A sent photo kept: its bytes fetched through the send, opened with the key the box carried (or as they lie, a /// file sealed before R6), and brought in through the phone's own capture, which makes the photo row and seals /// its bytes under this person's key. Answers the new photo's id. pub fn capture_sent(client: &ClientController, send: &str, from_key: &str, fk: Option<&str>, data: &Map) -> Result { let door = client.object_door().ok_or_else(super::cotton_chat::not_connected)?; let path = format!("/v1/send/{send}/media?key={}&whole=1", enc(from_key)); let (status, bytes) = door.address.send_bytes(door.exchange.as_ref(), "GET", &path, cotton_client::transport::object::bearer(&door.credential), None).map_err(refused)?; if status != 200 { return Err(MethodError::new("unreachable", format!("the sent picture did not come ({status})"))); } let plain = match fk { Some(fk) if bytes.starts_with(cotton_core::seal::file::MAGIC) => { let theirs = cotton_core::seal::file::FileKey::read(fk).map_err(|e| MethodError::new(e.code(), e.to_string()))?; let mut plain = Vec::new(); cotton_core::seal::file::open_file(&theirs, from_key, &mut bytes.as_slice(), &mut plain).map_err(|e| MethodError::new(e.code(), e.to_string()))?; plain } _ => bytes, }; let filename = data.get("original_filename").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).unwrap_or("sent.jpg").to_string(); let mime = data.get("content_type").and_then(Value::as_str).filter(|m| m.starts_with("image/")).unwrap_or("image/jpeg").to_string(); let dir = client.layout().root().join("send-in"); std::fs::create_dir_all(&dir).map_err(|e| MethodError::new("could_not_write", e.to_string()))?; let file = dir.join(format!("{}-{}", fresh_id(), filename.replace(['/', '\\'], "_"))); // not a copy: a sealed file being sent. std::fs::write(&file, &plain).map_err(|e| MethodError::new("could_not_write", e.to_string()))?; drop(plain); let mut args = super::media::validate_capture(&json!({ "path": file.to_string_lossy(), "mime": mime, "filename": filename, "kind": "photo" })); let answer = args.as_mut().map_err(|e| e.clone()).and_then(|args| super::media::capture_args(client, args)); // not a copy: a sealed file being sent. let _ = std::fs::remove_file(&file); let answer = answer?; let id = answer["recordId"].as_str().or_else(|| answer["answer"]["recordId"].as_str()).ok_or_else(|| MethodError::new("capture_refused", "the sent picture's capture answered no record"))?.to_string(); // Its caption, the one column a person writes on a photo. if let Some(caption) = data.get("caption").and_then(Value::as_str).filter(|c| !c.trim().is_empty()) { let _ = super::records::call(client, "records.update", &json!({ "table": "photo", "id": id, "patch": { "caption": caption } })); } Ok(id) } fn enc(text: &str) -> String { text.bytes() .map(|b| match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), _ => format!("%{b:02X}"), }) .collect() } /// The landing's input on this phone. pub fn land_of(client: &ClientController, tables: &Tables, payload: &Payload, sent_by: Option) -> Result { let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?; Ok(Land { payload: serde_json::to_value(payload).unwrap_or(Value::Null), tables: tables.clone(), database, sent_by, sent_at: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) }) } /// What the receiver already holds of a send's root, as its card says it. pub fn held_root(client: &ClientController, land: &Land, payload: &Payload) -> Option { let held = rule::held(land, &PhoneReads::new(client)).ok()?; held.into_iter().find(|h| h.table == payload.root.table && h.sent == payload.root.id).map(|h| json!({ "table": h.table, "id": h.id })) } /// The Keep's plan over this phone's copy. pub fn plan(client: &ClientController, land: &Land) -> Result { rule::keep(land, &PhoneReads::new(client)).map_err(rule_refusal) } /// The rows a landing makes, written on this phone in order (each one's /// links to rows made before it named by the id that row was given), what /// it already holds never made again. Answers the landed root as it stands. pub fn write_rows(client: &ClientController, landing: &Landing) -> Result { write_rows_after(client, landing, BTreeMap::new()) } /// [`write_rows`], with the records already made another way (a captured photo): sent id to the id here. pub fn write_rows_after(client: &ClientController, landing: &Landing, mut made: BTreeMap) -> Result { for create in &landing.creates { if made.contains_key(&create.id) { continue; } if let Some(existing) = PhoneReads::new(client).row(&create.table, &create.id).ok().flatten() { let _ = existing; made.insert(create.id.clone(), create.id.clone()); continue; } let mut data = create.data.clone(); // A table this build stores in its own shape (a todo, a note, a photo) keeps no column for the provenance // the rule stamps, and its write refuses what Cotton sets itself: the row lands with its own columns, and // which send brought it stays on this phone's send item (its landed root), as Undo reads it. if cotton_client::transport::object::ObjectTables::personal().object(&create.table).is_some() { for key in rule::PROVENANCE { data.remove(key); } // So is every column it marks readonly (a note's kind, words, journal date): Cotton sets those here. for key in readonly_columns(&create.table) { data.remove(&key); } } for value in data.values_mut() { if let Some(id) = value.as_str().and_then(|s| made.get(s)) { *value = json!(id); } } let written = super::records::call(client, "records.create", &json!({ "table": create.table, "data": data }))?; let id = written["record"]["id"].as_str().or_else(|| written["id"].as_str()).unwrap_or(&create.id).to_string(); made.insert(create.id.clone(), id); } let root = made.get(&landing.root.id).cloned().unwrap_or_else(|| landing.root.id.clone()); Ok(json!({ "table": landing.root.table, "id": root })) } /// The columns table `id`'s definition marks readonly: the generic write refuses them, and Cotton sets them itself. fn readonly_columns(id: &str) -> Vec { let file = cotton_core::kit::table_file(id).or_else(|| cotton_core::kit::table_file(&format!("personal/{id}"))); let Some(definition) = file.and_then(|f| serde_json::from_slice::(f).ok()) else { return Vec::new() }; definition["columns"] .as_array() .into_iter() .flatten() .filter(|c| c["readonly"] == json!(true)) .filter_map(|c| c["key"].as_str().map(str::to_string)) .collect() } /// How many records of each table a payload carries. pub fn counts(payload: &Payload) -> Value { let mut out = Map::new(); for r in &payload.records { let n = out.get(&r.table).and_then(Value::as_u64).unwrap_or(0) + 1; out.insert(r.table.clone(), json!(n)); } Value::Object(out) } /// The card a thread row draws for a send: the root table's card face and /// its fields, read off the payload (a column the root carries, or a lookup /// through a link to a record that travelled with it). pub fn card_of(def: Option<&TableDefinition>, payload: &Payload) -> Value { let Some(def) = def.and_then(|d| serde_json::to_value(d).ok()) else { return Value::Null }; let Some(face) = def["card"]["face"].as_str().map(str::to_string) else { return Value::Null }; let Some(root) = payload.records.iter().find(|r| matches!(r.role, rule::Role::Root)) else { return Value::Null }; let columns: HashMap = def["columns"].as_array().into_iter().flatten().filter_map(|c| Some((c["key"].as_str()?.to_string(), c.clone()))).collect(); let mut fields = Map::new(); for field in def["card"]["fields"].as_array().into_iter().flatten() { let (Some(slot), Some(column)) = (field["slot"].as_str(), field["column"].as_str()) else { continue }; let mut value = root.data.get(column).cloned(); if value.is_none() { if let Some(lookup) = columns.get(column).map(|c| &c["computed"]["lookup"]) { if let (Some(through), Some(col)) = (lookup["through"].as_str(), lookup["column"].as_str()) { let target = root.data.get(through).and_then(Value::as_str); value = payload.records.iter().find(|r| Some(r.id.as_str()) == target && !matches!(r.role, rule::Role::Root)).and_then(|r| r.data.get(col).cloned()); } } } if let Some(v) = value.filter(|v| !v.is_null()) { fields.insert(slot.into(), v); } } json!({ "face": face, "fields": fields }) } /// A fresh send id: 32 hex digits. pub fn fresh_id() -> String { use rand::RngCore; let mut bytes = [0u8; 16]; rand::rngs::OsRng.fill_bytes(&mut bytes); bytes.iter().map(|b| format!("{b:02x}")).collect() }