//! The kept chat pictures the object still holds plain, sealed from this//! phone and put back under their own keys (owner's decision, 22 Nov 2026://! kept chat pictures never sit unencrypted on the server).//!//! Since 22 Nov 2026 a device seals the kind `messages` as it seals a photo//! (`media::sealed::SEALED_KINDS`), under the message table's own files root,//! which a window over messages hands the Worker (`seal::keys::table_file_root`),//! so an assistant reads one inside a window and nowhere else. Before that, a//! Comms picture kept in the person's own media and every WhatsApp picture the//! Mac imported went up plain under `<database>/messages/…`.//!//! Each run (the end of `chat.keep`, which every Comms app runs on its own//! timer): ask the object for a page of this database's plain `messages`//! files (`GET /v1/media-plain?kind=messages`), fetch each, seal it on this//! device and put it back under its own key. A sealed file is never the same//! size as its plain bytes, so the put replaces it; the object never lets a//! plain upload replace a sealed one, so an older app cannot undo it. Bounded://! [`EACH_UNMETERED`] files on Wi-Fi, [`EACH_METERED`] small ones otherwise.//! Where it stands is kept beside the copy (`seal-kept.json`); at the end it//! looks again a day later, for what an app from before this one sent since.//! Needs this device's data key; with none yet it waits, sealing nothing.//! And the object holds it back (`waiting`, the devices named) while any of//! the person's devices that pulls messages runs a core from before this one,//! which reads a kept picture plain and would find the sealed one unreadable.use std::path::PathBuf;use serde_json::{json, Value};usecrate::shell::client::ClientController;/// Files sealed in one run on an unmetered network.const EACH_UNMETERED: usize = 50;/// Files sealed in one run otherwise, each at most [`METERED_MOST`].const EACH_METERED: usize = 10;const METERED_MOST: u64 = 1024 * 1024;/// How long after a listing that came to its end the object is asked again.const LOOK_AGAIN_MS: i64 = 24 * 3_600_000;/// What one run did.#[derive(Debug, Default, PartialEq, Eq)]pubstructSealed {pub sealed: usize,pub bytes: u64,/// Left for an unmetered network (too big for this one).pub left: usize,/// The listing came to its end.pub done: bool,/// The devices the object holds the reseal back for: they pull messages on a core from before 22 Nov 2026,/// which would read a resealed picture as garbage. Nothing is sealed meanwhile; asked again next run.pub waiting: Vec<String>,}fn state_path(client: &ClientController) -> PathBuf { client.layout().root().join("seal-kept.json")}fn state(client: &ClientController) -> Value { std::fs::read(state_path(client)).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_else(|| json!({}))}fn keep_state(client: &ClientController, value: &Value) {// not a copy: the seal state's file.let _ = std::fs::write(state_path(client), value.to_string());}/// THE SWITCH (coordinator, 22 Nov 2026): the reseal of the plain kept pictures already on the object is OFF in/// phone builds until it is proven on dev at size; turned on by this one line. New kept pictures are sealed on the/// phone before they leave it either way (`media::sealed::SEALED_KINDS`), and the object never lets a plain upload/// replace a sealed one.pubconst RESEAL: bool = false;/// One run, when [`RESEAL`] is on: at most a page of plain files sealed and put back. Off, it asks nothing.pub(crate) fn carry(client: &ClientController, unmetered: bool) -> Result<Sealed, String> {if !RESEAL {returnOk(Sealed::default()); } carry_now(client, unmetered)}/// The run itself, whatever the switch says (its tests, and the dev proof).pub(crate) fn carry_now(client: &ClientController, unmetered: bool) -> Result<Sealed, String> {use cotton_client::seal::DataKeyStoreas _;letmut said = state(client);let now = client.now().timestamp_millis();if said["doneAt"].as_i64().is_some_and(|at| now - at < LOOK_AGAIN_MS) {returnOk(Sealed { done: true, ..Sealed::default() }); }letSome(door) = client.object_door() else { returnOk(Sealed::default()) };let database = client.current_database()?;if client.data_keys().data_key(&database)?.is_none() {returnOk(Sealed::default()); }let files = super::personal_object::person_files_of(client, &database);let each = if unmetered { EACH_UNMETERED } else { EACH_METERED };let after = said["after"].as_str().map(|a| format!("&after={}", cotton_chat_enc(a))).unwrap_or_default();let path = format!("/v1/media-plain?kind=messages&limit={each}{after}");let (status, body) = door.address.send_bytes(door.exchange.as_ref(), "GET", &path, cotton_client::transport::object::bearer(&door.credential), None).map_err(|refusal| refusal.message)?;if status != 200 {returnErr(format!("the object did not list its plain files ({status})")); }let page: Value = serde_json::from_slice(&body).map_err(|e| e.to_string())?;let waiting: Vec<String> = page["waiting"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(str::to_string)).collect();if !waiting.is_empty() {returnOk(Sealed { waiting, ..Sealed::default() }); }letmut out = Sealed::default();for file in page["files"].as_array().into_iter().flatten() {letSome(media_path) = file["key"].as_str() else { continue };let bytes = file["bytes"].as_u64().unwrap_or(0);if !unmetered && bytes > METERED_MOST { out.left += 1;continue; }let (status, plain) = door.address.send_bytes(door.exchange.as_ref(), "GET", &format!("/v1/media/{media_path}"), cotton_client::transport::object::bearer(&door.credential), None).map_err(|refusal| refusal.message)?;if status != 200 || plain.starts_with(cotton_core::seal::file::MAGIC) {// Gone since it was listed, or sealed by another device meanwhile.continue; }let fk = files.file_key(media_path).map_err(|refusal| refusal.to_string())?;letmut sealed = Vec::with_capacity(plain.len() + 4096); cotton_core::seal::file::seal_file(&fk, media_path, &mut plain.as_slice(), &mut sealed).map_err(|e| e.to_string())?;super::cotton_chat::put_typed(client, &format!("/v1/media/{media_path}"), &sealed, cotton_client::media::sealed::SEALED_FILE_TYPE).map_err(|refusal| refusal.message)?; out.sealed += 1; out.bytes += plain.len() as u64; }match page["next"].as_str() {// Past what this run left for Wi-Fi only when it sealed it: a metered run keeps its place.Some(next) if out.left == 0 => said["after"] = json!(next),Some(_) => {}Noneif out.left == 0 => { said = json!({ "doneAt": now }); out.done = true; }None => {} } keep_state(client, &said);Ok(out)}fn cotton_chat_enc(text: &str) -> String { text.bytes() .map(|b| if b.is_ascii_alphanumeric() || b"-_.~/".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }) .collect()}#[cfg(test)]mod tests {use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};usesuper::*;usecrate::phone::passwords::tests::phone;usecrate::phone::personal_object::ObjectDoor;fn door(client: &ClientController, replies: Vec<Reply>) -> Arc<ScriptedExchange> {let exchange = ScriptedExchange::new(replies); client.set_object_door(Some(Arc::new(ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: exchange.clone(), credential: "invented-credential".into() }))); exchange }/// RULE (owner's decision, 22 Nov 2026): the kept chat pictures the object holds plain are sealed on the phone under the message table's own files root and put back under their own keys, a page a run; a metered run leaves a big one for Wi-Fi and keeps its place; once the listing ends it rests a day. Nothing is lost: each sealed file opens to the bytes it replaced. #[test]fn the_plain_kept_pictures_are_sealed_and_put_back_under_their_own_keys() {let (_dir, handle) = phone();let client = handle.client();let database = client.current_database().unwrap();let dk = cotton_core::seal::DataKey::from_bytes([31; 32]); client.data_keys().hold(&database, &dk);let (one, two, big) = (format!("{database}/messages/t-1/a.png"), format!("{database}/messages/t-1/b.jpg"), format!("{database}/messages/t-2/c.png"));let (plain_one, plain_two) = (b"an invented picture".to_vec(), vec![7u8; 70 * 1024]);// Metered: the small one sealed, the big one left for Wi-Fi, the place kept.let listing = json!({ "files": [{ "key": one, "bytes": plain_one.len() }, { "key": big, "bytes": 3 * 1024 * 1024 }], "next": null }).to_string();let exchange = door(&client, vec![Reply::ok(&listing), Reply::new(200, plain_one.clone()), Reply::ok(r#"{"stored":true}"#)]);let ran = carry_now(&client, false).unwrap(); assert_eq!(ran, Sealed { sealed: 1, bytes: plain_one.len() as u64, left: 1, done: false, waiting: vec![] }); assert!(exchange.nth(0).path.starts_with("/v1/media-plain?kind=messages&limit=10"), "{}", exchange.nth(0).path);let put = exchange.nth(2); assert_eq!((put.method.as_str(), put.path.as_str()), ("PUT", format!("/v1/media/{one}").as_str())); assert_eq!(put.header("content-type"), Some(cotton_client::media::sealed::SEALED_FILE_TYPE));let root = cotton_core::seal::keys::table_file_root(&dk, &database, "message").unwrap();letmut opened = Vec::new(); cotton_core::seal::file::open_file(&cotton_core::seal::file::person_file_key(&root, &one), &one, &mut put.body.as_slice(), &mut opened).expect("sealed under the message table's root"); assert_eq!(opened, plain_one, "nothing lost");// On Wi-Fi: the rest, then the end; a file another device sealed meanwhile is left as it is.let listing = json!({ "files": [{ "key": two, "bytes": plain_two.len() }, { "key": big, "bytes": 30 }], "next": null }).to_string();letmut already = cotton_core::seal::file::MAGIC.to_vec(); already.extend_from_slice(b"sealed by another phone");let exchange = door(&client, vec![Reply::ok(&listing), Reply::new(200, plain_two.clone()), Reply::ok(r#"{"stored":true}"#), Reply::new(200, already)]);let ran = carry_now(&client, true).unwrap(); assert_eq!(ran, Sealed { sealed: 1, bytes: plain_two.len() as u64, left: 0, done: true, waiting: vec![] }); assert_eq!(exchange.calls(), 4, "the sealed one is not put again");letmut opened = Vec::new(); cotton_core::seal::file::open_file(&cotton_core::seal::file::person_file_key(&root, &two), &two, &mut exchange.nth(2).body.as_slice(), &mut opened).unwrap(); assert_eq!(opened, plain_two, "across a part's edge, nothing lost");// Done: it rests a day, asking nothing.let exchange = door(&client, vec![]); assert!(carry_now(&client, true).unwrap().done); assert_eq!(exchange.calls(), 0); }/// RULE: while the object names a device on an older core that pulls messages, nothing is sealed, nothing fetched, and it is not done: asked again next run. #[test]fn while_an_older_app_reads_messages_nothing_is_resealed() {let (_dir, handle) = phone();let client = handle.client(); client.data_keys().hold(&client.current_database().unwrap(), &cotton_core::seal::DataKey::from_bytes([31; 32]));let exchange = door(&client, vec![Reply::ok(r#"{"files":[],"next":null,"waiting":["Old Comms"]}"#), Reply::ok(r#"{"files":[],"next":null}"#)]); assert_eq!(carry_now(&client, true).unwrap(), Sealed { waiting: vec!["Old Comms".into()], ..Sealed::default() }); assert_eq!(exchange.calls(), 1);// Once it has updated, the run goes on (here to the end of an empty list). assert!(carry_now(&client, true).unwrap().done); assert_eq!(exchange.calls(), 2); }/// RULE (coordinator, 22 Nov 2026): the switch is off in this build: chat.keep's run of the reseal asks the object nothing and seals nothing, even with a data key and plain pictures waiting. #[test]fn the_reseal_is_switched_off_in_this_build() { assert!(!RESEAL, "turned on only once the reseal is proven on dev at size");let (_dir, handle) = phone();let client = handle.client(); client.data_keys().hold(&client.current_database().unwrap(), &cotton_core::seal::DataKey::from_bytes([31; 32]));let exchange = door(&client, vec![Reply::ok(r#"{"files":[{"key":"x","bytes":1}],"next":null}"#)]); assert_eq!(carry(&client, true).unwrap(), Sealed::default()); assert_eq!(exchange.calls(), 0, "nothing asked"); }/// RULE: with no data key on this phone yet it seals nothing and asks nothing. #[test]fn with_no_data_key_it_waits() {let (_dir, handle) = phone();let client = handle.client();let exchange = door(&client, vec![]); assert_eq!(carry_now(&client, true).unwrap(), Sealed::default()); assert_eq!(exchange.calls(), 0); }}