Cotton code
236 lines · 15.8 KB · RustRaw
//! A Cotton chat's files on a phone over a scripted object: a received file//! opens under its own extension and is kept in the person's own media, a//! kept file opens again with no chat store, the keep pass keeps what is//! light and leaves what waits for Wi-Fi, and a file the store swept says//! so. Every number, key and byte is invented.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_core::chat::payload::{Payload, Picture};use cotton_core::chat::{files, seal};use cotton_core::vault::wrap::public_of;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::phone::cotton_chat::over;use crate::phone::passwords::tests::phone;use crate::phone::personal_object::ObjectDoor;const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";const ME: &str = "+15550100002";const THEM: &str = "+15550100001";fn scalar(seed: u8) -> [u8; 32] {    let mut bytes = [seed; 32];    bytes[0] = seed.wrapping_mul(7).wrapping_add(1);    bytes}fn with_door(handle: &CottonHandle, replies: impl IntoIterator<Item = Reply>) -> Arc<ScriptedExchange> {    let exchange = ScriptedExchange::new(replies);    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: CREDENTIAL.to_string() };    handle.client().set_object_door(Some(Arc::new(door)));    exchange}fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value {    over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn refused(handle: &CottonHandle, method: &str, request: Value) -> (String, String) {    over(&handle.client(), method, &request).err().map(|e| (e.code, e.message)).unwrap_or_else(|| panic!("{method} answered"))}fn keys_reply() -> Reply {    Reply::ok(&json!({ "me": ME, "devices": [{ "device": "theirhandle00000000000", "key": seal::key_text(&public_of(&scalar(1))) }], "own": [] }).to_string())}/// A file their phone sealed: its picture entry and the sealed bytes the store holds.fn sealed(plain: &[u8], file: &str, mime: &str, kind: Option<&str>, name: Option<&str>) -> (Picture, Vec<u8>) {    let s = files::seal_file(plain).expect("sealed");    let picture = Picture { file: file.into(), key: seal::key_text(&s.key), sha256: s.sha256.clone(), mime: mime.into(), width: None, height: None, bytes: plain.len() as u64, kind: kind.map(str::to_string), name: name.map(str::to_string), duration_ms: None, waveform: vec![], preview: None };    (picture, s.bytes)}/// Their message carrying `pictures`, landed: its row id.fn landed(handle: &CottonHandle, id: &str, pictures: Vec<Picture>) -> String {    let message = Payload::message(id, THEM, ME, chrono::Utc::now().timestamp_millis(), None, None, pictures);    let item = json!({ "id": message.id, "kind": "message", "peer": THEM, "out": false, "request": false, "box": seal::seal(&scalar(1), &public_of(&scalar(2)), &message.bytes()).unwrap(), "at": chrono::Utc::now().timestamp_millis() });    with_door(handle, [Reply::ok(&json!({ "me": ME, "items": [item] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(handle, "chat.incoming", json!({ "privateKey": seal::key_text(&scalar(2)) }));    got["landed"][0]["message"].as_str().unwrap_or_else(|| panic!("nothing landed: {got}")).to_string()}fn row(handle: &CottonHandle, id: &str) -> serde_json::Map<String, Value> {    handle        .client()        .with_writer(|replica| Ok(replica.driver.get("SELECT media, meta FROM cotton_msg_messages WHERE id = ?", &[rusqlite::types::Value::Text(id.to_string())]).map_err(|e| e.to_string())?.map(|row| crate::phone::passwords::json_row(&row))))        .unwrap()        .expect("the message")}fn meta(handle: &CottonHandle, id: &str) -> Value {    crate::phone::cotton_chat::meta_value(row(handle, id).get("meta").unwrap_or(&Value::Null))}// RULE: a received file opens under its own name's extension (a PDF is a .pdf), and is kept in the person's own media at once: the message names it (`media`), its picture says `kept`, and the next open needs no chat store.#[test]fn a_received_file_opens_and_is_kept() {    let (dir, handle) = phone();    let plain = b"%PDF-1.4 an invented boarding pass".to_vec();    let (picture, bytes) = sealed(&plain, "f".repeat(32).as_str(), "application/pdf", Some("file"), Some("Boarding pass.pdf"));    let id = landed(&handle, "aaaaaaaaaaaaaaaa", vec![picture]);    let out = dir.path().join("open");    with_door(&handle, [Reply::new(200, bytes)]);    let opened = answer(&handle, "chat.file", json!({ "message": id, "dir": out.to_string_lossy() }));    let path = opened["path"].as_str().unwrap();    // Under the name it was sent with, so the phone's viewer titles it so (not "0c99….pdf").    assert_eq!(std::path::Path::new(path).file_name().and_then(|n| n.to_str()), Some("Boarding pass.pdf"), "{path}");    assert!(std::path::Path::new(path).starts_with(&out), "{path}");    assert_eq!(std::fs::read(path).unwrap(), plain);    assert_eq!((opened["mime"].as_str(), opened["name"].as_str(), opened["kept"].as_bool()), (Some("application/pdf"), Some("Boarding pass.pdf"), Some(true)));    // Comms' own viewer draws it, whatever else is on the phone (owner, 24 Nov 2026).    assert_eq!(opened["view"], "pdf");    let kept = meta(&handle, &id)["cotton"]["pictures"][0]["kept"].as_str().expect("kept").to_string();    assert!(kept.contains("/messages/"), "{kept}");    let media: Value = serde_json::from_str(row(&handle, &id)["media"].as_str().unwrap()).unwrap();    assert_eq!((media[0]["key"].as_str(), media[0]["cottonKept"].as_bool()), (Some(kept.as_str()), Some(true)));    // Drawn once: the thread's bubble carries one file, not two.    let thread = answer(&handle, "chat.list", json!({}))["rows"][0]["thread"].as_str().unwrap().to_string();    let page = answer(&handle, "chat.thread", json!({ "thread": thread }));    let bubble = page["items"].as_array().unwrap().iter().find(|i| i["message"] == json!(id)).cloned().expect("the bubble");    assert_eq!(bubble["media"].as_array().map(Vec::len), Some(1), "{bubble}");    // Opened again: from the person's own copy, the chat store not asked.    let exchange = with_door(&handle, []);    std::fs::remove_dir_all(&out).unwrap();    let again = answer(&handle, "chat.file", json!({ "message": id, "dir": out.to_string_lossy() }));    assert_eq!(std::fs::read(again["path"].as_str().unwrap()).unwrap(), plain);    assert_eq!(exchange.calls(), 0);}// RULE: a file the chat store swept, that no phone kept, refuses `file_gone` in the kit's words; the keep pass marks it gone and never asks again.// Never within minutes of the message landing (FEEDBACK1 item 1): then the store's miss is only "not yet".#[test]fn a_swept_file_says_it_has_gone() {    let (dir, handle) = phone();    let (picture, _) = sealed(b"an invented photo", "e".repeat(32).as_str(), "image/jpeg", None, None);    let id = landed(&handle, "bbbbbbbbbbbbbbbb", vec![picture]);    with_door(&handle, [Reply::new(404, r#"{"code":"not_found"}"#)]);    let (code, _) = refused(&handle, "chat.file", json!({ "message": id, "dir": dir.path().join("o").to_string_lossy() }));    assert_eq!(code, "file_offline", "just landed: not gone");    with_door(&handle, [Reply::new(404, r#"{"code":"not_found"}"#)]);    assert_eq!(answer(&handle, "chat.keep", json!({})), json!({ "kept": 0, "left": 1, "gone": 0 }), "just landed: left, never marked gone");    assert!(meta(&handle, &id)["cotton"]["pictures"][0].get("gone").is_none());    // An hour on, the store's miss is the sweep's.    let hour_ago = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    handle        .client()        .with_writer(|replica| replica.driver.run("UPDATE cotton_msg_messages SET sent_at = ?, created_at = ?, meta = json_set(meta, '$.cotton.written_at', ?) WHERE id = ?", &[rusqlite::types::Value::Text(hour_ago.clone()), rusqlite::types::Value::Text(hour_ago.clone()), rusqlite::types::Value::Text(hour_ago.clone()), rusqlite::types::Value::Text(id.clone())]).map(|_| ()).map_err(|e| e.to_string()))        .unwrap();    with_door(&handle, [Reply::new(404, r#"{"code":"not_found"}"#)]);    let (code, words) = refused(&handle, "chat.file", json!({ "message": id, "dir": dir.path().join("o").to_string_lossy() }));    assert_eq!(code, "file_gone");    assert!(words.contains("30 days"), "{words}");    with_door(&handle, [Reply::new(404, r#"{"code":"not_found"}"#)]);    assert_eq!(answer(&handle, "chat.keep", json!({}))["gone"], 1);    assert_eq!(meta(&handle, &id)["cotton"]["pictures"][0]["gone"], true);    let exchange = with_door(&handle, []);    assert_eq!(answer(&handle, "chat.keep", json!({})), json!({ "kept": 0, "left": 0, "gone": 0 }));    assert_eq!(exchange.calls(), 0);}// RULE: the keep pass keeps what no phone kept, a voice message on any network; a video waits for an unmetered network, then is kept.#[test]fn the_keep_pass_keeps_light_files_and_videos_on_wifi() {    let (_dir, handle) = phone();    let (voice, voice_bytes) = sealed(b"invented voice", "a".repeat(32).as_str(), "audio/mp4", Some("voice"), None);    let (video, video_bytes) = sealed(b"invented film", "b".repeat(32).as_str(), "video/mp4", Some("video"), Some("clip.mp4"));    let id = landed(&handle, "cccccccccccccccc", vec![voice, video]);    with_door(&handle, [Reply::new(200, voice_bytes)]);    assert_eq!(answer(&handle, "chat.keep", json!({})), json!({ "kept": 1, "left": 1, "gone": 0 }));    with_door(&handle, [Reply::new(200, video_bytes)]);    assert_eq!(answer(&handle, "chat.keep", json!({ "unmetered": true })), json!({ "kept": 1, "left": 0, "gone": 0 }));    let pictures = meta(&handle, &id)["cotton"]["pictures"].clone();    assert!(pictures[0]["kept"].is_string() && pictures[1]["kept"].as_str().unwrap().ends_with(".mp4"), "{pictures}");}// RULE: the sender keeps their own copy of what they send, in their own media, as it goes up: their other phones and a new phone open it past the chat store's thirty days.#[test]fn the_sender_keeps_their_own_copy() {    let (dir, handle) = phone();    let path = dir.path().join("photo.jpg");    std::fs::write(&path, b"an invented jpeg").unwrap();    // Known on Cotton here (they wrote, or accepted): chat.start asks the server nothing.    crate::phone::chat_people::hold_on_cotton(&handle.client(), THEM);    with_door(&handle, []);    let thread = answer(&handle, "chat.start", json!({ "number": THEM }))["thread"].as_str().unwrap().to_string();    with_door(&handle, [Reply::ok(r#"{"file":"0123456789abcdef0123456789abcdef"}"#), keys_reply(), Reply::ok(r#"{"ok":true,"at":1}"#)]);    let sent = answer(&handle, "chat.send", json!({ "thread": thread, "pictures": [{ "path": path.to_string_lossy(), "mime": "image/jpeg" }], "privateKey": seal::key_text(&scalar(2)) }));    assert_eq!(sent["state"], "sent");    let kept = meta(&handle, sent["message"].as_str().unwrap())["cotton"]["pictures"][0]["kept"].clone();    assert!(kept.as_str().is_some_and(|k| k.ends_with(".jpg")), "{kept}");}// RULE: a file opens under the name it was sent with, made safe: no folder of the sender's, no leading dot, its type's extension kept; none, and it is its hash's start (21 Nov 2026).#[test]fn a_file_opens_under_its_own_name_made_safe() {    let picture = |name: Option<&str>, mime: &str| sealed(b"x", "f".repeat(32).as_str(), mime, Some("file"), name).0;    let dir = std::path::Path::new("/d");    let name = |p: &Picture| super::opened_path(dir, p);    let pdf = picture(Some("Boarding pass.pdf"), "application/pdf");    let hash = pdf.sha256[..16].to_string();    assert_eq!(name(&pdf), dir.join(&hash).join("Boarding pass.pdf"));    assert_eq!(name(&picture(Some("../../etc/passwd"), "text/plain")).file_name().unwrap(), "passwd.txt");    assert_eq!(name(&picture(Some("..\\..\\x\\Report.PDF"), "application/pdf")).file_name().unwrap(), "Report.PDF");    assert_eq!(name(&picture(Some(".hidden"), "application/pdf")).file_name().unwrap(), "hidden.pdf");    assert_eq!(name(&picture(Some("  "), "video/mp4")), dir.join(&hash).join(format!("{hash}.mp4")));    assert_eq!(name(&picture(None, "video/mp4")), dir.join(&hash).join(format!("{hash}.mp4")));    for p in [name(&picture(Some("../../etc/passwd"), "text/plain")), name(&picture(Some("a/b\u{0}c.pdf"), "application/pdf"))] {        assert_eq!(p.parent(), Some(dir.join(&hash).as_path()), "{p:?}");    }}/// Storage's Photos and files, as You's Storage says it (`shell.settings`): its bytes and how much Free up may take.fn photos_and_files(handle: &CottonHandle) -> (u64, u64) {    let settings = crate::methods::dispatch(handle, "shell.settings", &json!({ "commit": "abc1234" })).expect("shell.settings");    let files = settings["storage"]["parts"].as_array().unwrap().iter().find(|p| p["id"] == "files").cloned().expect("Photos and files");    (files["bytes"].as_u64().unwrap(), settings["storage"]["free_up"]["bytes"].as_u64().unwrap())}// RULE (owner's iPhone, Comms build 19: Storage said "Photos and files 0 MB" after he had sent and seen pictures): a picture the person sends, and one they see in a chat, is kept in their own media and counted under Photos and files; once it is in their account it may be freed and comes back when seen again.#[test]fn what_is_sent_and_seen_counts_under_photos_and_files() {    let (dir, handle) = phone();    assert_eq!(photos_and_files(&handle).0, 0, "nothing yet");    let sent_bytes = b"an invented jpeg the person sent".to_vec();    let path = dir.path().join("photo.jpg");    std::fs::write(&path, &sent_bytes).unwrap();    crate::phone::chat_people::hold_on_cotton(&handle.client(), THEM);    with_door(&handle, []);    let thread = answer(&handle, "chat.start", json!({ "number": THEM }))["thread"].as_str().unwrap().to_string();    with_door(&handle, [Reply::ok(r#"{"file":"0123456789abcdef0123456789abcdef"}"#), keys_reply(), Reply::ok(r#"{"ok":true,"at":1}"#)]);    let sent = answer(&handle, "chat.send", json!({ "thread": thread, "pictures": [{ "path": path.to_string_lossy(), "mime": "image/jpeg" }], "privateKey": seal::key_text(&scalar(2)) }));    assert_eq!(sent["state"], "sent");    assert_eq!(photos_and_files(&handle).0, sent_bytes.len() as u64, "the sent picture counts");    // Their picture, drawn in the conversation (`chat.picture`, as a bubble asks it).    let seen_bytes = b"an invented photo they sent, a little longer".to_vec();    let (picture, bytes) = sealed(&seen_bytes, "d".repeat(32).as_str(), "image/jpeg", None, None);    let id = landed(&handle, "dddddddddddddddd", vec![picture]);    with_door(&handle, [Reply::new(200, bytes)]);    let shown = answer(&handle, "chat.picture", json!({ "message": id, "dir": dir.path().join("shown").to_string_lossy() }));    assert_eq!(std::fs::read(shown["path"].as_str().unwrap()).unwrap(), seen_bytes);    assert!(meta(&handle, &id)["cotton"]["pictures"][0]["kept"].is_string(), "kept in their own media");    assert_eq!(photos_and_files(&handle).0, (sent_bytes.len() + seen_bytes.len()) as u64, "the seen picture counts too");    // Seen again: from their own media, the chat store not asked.    let exchange = with_door(&handle, []);    let again = answer(&handle, "chat.picture", json!({ "message": id, "dir": dir.path().join("again").to_string_lossy() }));    assert_eq!(std::fs::read(again["path"].as_str().unwrap()).unwrap(), seen_bytes);    assert_eq!(exchange.calls(), 0);    // In their account (synced up), both may be freed: neither was made on this phone's camera.    handle.client().with_writer(|replica| replica.driver.run("UPDATE _media SET state = 'synced'", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap();    assert_eq!(photos_and_files(&handle).1, (sent_bytes.len() + seen_bytes.len()) as u64, "Free up may take them");}