Cotton code
165 lines · 9.3 KB · RustRaw
//! `chat.notices` over a phone's own copy and a scripted object: a message//! landed is noticed, read here or on another of the person's phones it is//! not, and a read here tells the person's other phones alone. Every number,//! key and name is invented.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_core::chat::payload::{Kind, Payload, Receipt};use cotton_core::chat::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";const MINE: u8 = 2;const THEIRS: u8 = 1;const TABLET: u8 = 4;fn scalar(seed: u8) -> [u8; 32] {    let mut bytes = [seed; 32];    bytes[0] = seed.wrapping_mul(7).wrapping_add(1);    bytes}fn key(seed: u8) -> String {    seal::key_text(&public_of(&scalar(seed)))}fn private(seed: u8) -> String {    seal::key_text(&scalar(seed))}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 keys_reply() -> Reply {    Reply::ok(&json!({ "me": ME, "devices": [{ "device": "theirhandle00000000000", "key": key(THEIRS) }], "own": [{ "device": "tablethandle0000000000", "key": key(TABLET) }] }).to_string())}fn hold_definitions(handle: &CottonHandle) {    let thread: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tables/thread.json")).expect("the thread definition");    handle.client().with_writer(|replica| cotton_client::transport::object::hold_defined_columns(&replica.driver, [&thread]).map(|_| ())).unwrap();}fn from_them(payload: &Payload, request: bool, at: i64) -> Value {    json!({ "id": payload.id, "kind": payload.kind.as_str(), "peer": THEM, "out": false, "request": request, "box": seal::seal(&scalar(THEIRS), &public_of(&scalar(MINE)), &payload.bytes()).unwrap(), "at": at })}/// Their words landed through the inbox: the thread.fn land(handle: &CottonHandle, items: Vec<Value>) -> String {    with_door(handle, [Reply::ok(&json!({ "me": ME, "items": items }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    got["landed"][0]["thread"].as_str().unwrap_or_else(|| panic!("nothing landed: {got}")).to_string()}fn notices(handle: &CottonHandle) -> Value {    answer(handle, "chat.notices", json!({}))}// RULE: their message landed here is one notice, titled by who they are to this phone, its line their words, with Reply and Mark as read and the words to draw them.#[test]fn a_landed_message_is_noticed() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let a = Payload::message("aaaaaaaaaaaaaaaa", THEM, ME, 10, Some("are you up?".into()), None, vec![]);    let b = Payload::message("bbbbbbbbbbbbbbbb", THEM, ME, 20, Some("the train is late".into()), None, vec![]);    let thread = land(&handle, vec![from_them(&a, false, 100), from_them(&b, false, 200)]);    let got = notices(&handle);    let list = got["notices"].as_array().unwrap();    assert_eq!(list.len(), 1, "{got}");    let n = &list[0];    assert_eq!((n["thread"].as_str(), n["unread"].as_u64(), n["actions"].as_bool(), n["at"].as_i64()), (Some(thread.as_str()), Some(2), Some(true), Some(200)));    assert!(n["title"].as_str().unwrap().contains("555"), "named by the number: {n}");    assert_eq!(n["lines"].as_array().unwrap().iter().map(|l| l["text"].as_str().unwrap()).collect::<Vec<_>>(), ["are you up?", "the train is late"]);    assert_eq!((got["words"]["reply"].as_str(), got["words"]["markRead"].as_str()), (Some("Reply"), Some("Mark as read")));}// RULE: read here (`chat.act read`), the notice goes, and the next flush tells this person's other phones (their tablet) that it was read, sealed for those alone: the other person is never told.#[test]fn read_here_the_notice_goes_and_only_my_other_phones_are_told() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let a = Payload::message("cccccccccccccccc", THEM, ME, 10, Some("hello".into()), None, vec![]);    let thread = land(&handle, vec![from_them(&a, false, 100)]);    let read = answer(&handle, "chat.act", json!({ "act": "read", "thread": thread }));    assert_eq!(read["flush"], true, "a flush tells the other phones");    assert_eq!(notices(&handle)["notices"], json!([]));    let exchange = with_door(&handle, [keys_reply(), Reply::ok(r#"{"ok":true,"at":1}"#)]);    answer(&handle, "chat.flush", json!({ "privateKey": private(MINE) }));    let sent = exchange.seen().into_iter().find(|s| s.path == "/v1/chat/send").expect("the read told");    let envelope: Value = serde_json::from_slice(&sent.body).unwrap();    assert_eq!(envelope["kind"], "receipt");    let boxes = envelope["boxes"].as_object().unwrap();    assert_eq!(boxes.keys().collect::<Vec<_>>(), ["tablethandle0000000000"], "the tablet alone, never theirs");    let opened: Payload = serde_json::from_slice(&seal::open(&scalar(TABLET), boxes["tablethandle0000000000"].as_str().unwrap()).unwrap().payload).unwrap();    assert_eq!((opened.kind, opened.state, opened.ids.clone()), (Kind::Receipt, Some(Receipt::Read), vec!["cccccccccccccccc".to_string()]));    // Told once: the next flush says nothing more.    let exchange = with_door(&handle, []);    answer(&handle, "chat.flush", json!({ "privateKey": private(MINE) }));    assert_eq!(exchange.calls(), 0);}// RULE: read on another of this person's phones (their own read receipt arriving), the notice goes here too, the chat is read in the list, and the landing says which chat was read.#[test]fn read_on_my_other_phone_the_notice_goes_here() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let a = Payload::message("dddddddddddddddd", THEM, ME, 10, Some("hello".into()), None, vec![]);    let thread = land(&handle, vec![from_them(&a, false, 100)]);    assert_eq!(notices(&handle)["notices"].as_array().unwrap().len(), 1);    let seen = Payload::receipt("eeeeeeeeeeeeeeee", ME, THEM, 300, Receipt::Read, vec!["dddddddddddddddd".into()]);    let item = json!({ "id": seen.id, "kind": "receipt", "peer": THEM, "out": true, "request": false, "box": seal::seal(&scalar(TABLET), &public_of(&scalar(MINE)), &seen.bytes()).unwrap(), "at": 300 });    with_door(&handle, [Reply::ok(&json!({ "me": ME, "items": [item] }).to_string()), keys_reply(), Reply::ok(r#"{"ok":true}"#)]);    let got = answer(&handle, "chat.incoming", json!({ "privateKey": private(MINE) }));    assert_eq!(got["read"], json!([thread]));    assert_eq!(notices(&handle)["notices"], json!([]));    let row = answer(&handle, "chat.list", json!({}))["rows"].as_array().unwrap().iter().find(|r| r["thread"] == json!(thread)).cloned().expect("the row");    assert_eq!(row["unread"], json!(0), "{row}");}// RULE: a stranger's request is noticed as "New message" alone, and a muted chat is not noticed at all.#[test]fn a_request_says_new_message_and_a_muted_chat_nothing() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let ask = Payload::message("ffffffffffffffff", THEM, ME, 10, Some("we met at the station".into()), None, vec![]);    let thread = land(&handle, vec![from_them(&ask, true, 100)]);    let got = notices(&handle);    assert_eq!((got["notices"][0]["title"].as_str(), got["notices"][0]["lines"].as_array().map(Vec::len)), (Some("New message"), Some(0)));    assert!(!got.to_string().contains("station"), "a stranger's words never reach the lock screen");    answer(&handle, "chat.act", json!({ "act": "mute", "thread": thread }));    assert_eq!(notices(&handle)["notices"], json!([]));}// RULE (owner, 24 Nov 2026; chat DECISIONS.md): a muted chat makes no notice, but a message that mentions him does.#[test]fn a_mention_of_him_rings_through_mute() {    let (_dir, handle) = phone();    hold_definitions(&handle);    let first = Payload::message("1111111111111111", THEM, ME, 10, Some("dinner at eight".into()), None, vec![]);    let thread = land(&handle, vec![from_them(&first, false, 100)]);    answer(&handle, "chat.act", json!({ "act": "mute", "thread": thread }));    assert_eq!(notices(&handle)["notices"], json!([]), "muted, nothing");    let mention = Payload::message("2222222222222222", THEM, ME, 20, Some(format!("@{ME} are you coming?")), None, vec![]);    land(&handle, vec![from_them(&mention, false, 200)]);    let got = notices(&handle);    assert_eq!(got["notices"].as_array().map(Vec::len), Some(1), "{got}");    assert!(got["notices"][0]["lines"].as_array().unwrap().iter().any(|l| l["text"].as_str().unwrap().contains("are you coming")));}