Cotton code
497 lines · 22.7 KB · RustRaw
//! What a box holds, and the checks an opened one must pass before it lands.//!//! The payload repeats the envelope's outside (its id, its kind, both numbers)//! INSIDE the seal, so the Worker cannot move a box to another envelope,//! another kind or another conversation: an opened payload that disagrees with//! the envelope it came in is dropped, as is one sealed by a device that is//! not among the keys the sender published.use serde::{Deserialize, Serialize};/// The payload's version.pub const VERSION: u32 = 1;/// A message's words at most (a box carries 64 KB in all).pub const BODY_MAX: usize = 16 * 1024;/// Pictures in one message at most.pub const PICTURES_MAX: usize = 10;/// A picture's preview at most, base64 characters (about 2 KB of JPEG):/// see [`Picture::preview`] and [`preview_of`].pub const PREVIEW_MAX: usize = 2_800;/// Message ids one receipt names at most.pub const RECEIPT_IDS_MAX: usize = 200;#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum Kind {    Message,    Receipt,    Typing,    /// A change to a message already sent: a reaction, an edit, a delete (Cotton Chat, 19 Nov 2026).    Change,    /// A change to a group's membership, name or picture: its ops (Cotton groups, 20 Nov 2026, [`super::group`]).    Group,    /// What the person's own agent asks of their phone (an agent in a chat, 23 Nov 2026): only their own    /// object makes it, sealed by the Worker for each of their devices; never a payload between people.    Agent,}impl Kind {    pub fn as_str(self) -> &'static str {        match self {            Kind::Message => "message",            Kind::Receipt => "receipt",            Kind::Typing => "typing",            Kind::Change => "change",            Kind::Group => "group",            Kind::Agent => "agent",        }    }}/// What a change does to the message it names.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum What {    /// The sender's reaction, replacing any earlier one of theirs.    React,    /// The sender's reaction taken back.    Unreact,    /// The message's words, written again by its writer.    Edit,    /// The message deleted for everyone by its writer.    Delete,    /// The chat's disappearing timer set (chat-search, 21 Nov 2026): `message` is the id of the line that says so,    /// `body` the seconds ("0" turns it off), one of [`crate::messages::app::timer::CHOICES`].    Timer,    /// A voice message's words, as its writer's phone heard them on the device    /// (never a service), in `body`, at most [`TRANSCRIPT_MAX`] bytes: sent    /// after the message, which never waits for them (FEEDBACK1 item 5,    /// 22 Nov 2026). A phone that knows nothing of it drops the change and    /// shows the voice message as before.    Transcript,    /// A group's call started (23 Nov 2026): `message` is the call's room id, `body` `voice`    /// or `video`. Every member's phone lands the call's line with Join while it goes on. A phone that knows    /// nothing of it drops the change; its person is still rung.    Call,}/// A change: what, to which message (its writer's id), and with what.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Change {    pub what: What,    pub message: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub emoji: Option<String>,}/// The most samples a voice message's waveform carries.pub const WAVEFORM_MAX: usize = 64;/// A voice message's transcript at most, bytes.pub const TRANSCRIPT_MAX: usize = 4 * 1024;/// The longest emoji a reaction carries, in bytes (the row's own check allows eight characters).pub const EMOJI_MAX: usize = 32;/// A receipt's news.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum Receipt {    Delivered,    Read,    /// The named envelopes' c2 boxes opened nothing here (`chat::ratchet`): sealed on a fresh session, so the    /// sealer's next words go on it. No tick moves.    Unreadable,}/// A picture a message carries: the file's place in the chat file store, the/// key that opens it, and what it is. The file is sealed on the phone/// ([`super::files`]); the store holds only its ciphertext.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct Picture {    /// The chat file store's id (`GET /v1/chat/files/<file>`).    pub file: String,    /// The file key, base64url (32 bytes).    pub key: String,    /// SHA-256 of the plain file, hex: what the opened file must hash to.    pub sha256: String,    pub mime: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub width: Option<u32>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub height: Option<u32>,    pub bytes: u64,    /// What the file is, when not a picture (Cotton Chat, 19 Nov 2026):    /// `voice`, `audio`, `video`, `file`, `contact`; absent, the mime decides.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub kind: Option<String>,    /// A file's own name, as its chip says it.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub name: Option<String>,    /// A voice message's, audio's or video's length.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub duration_ms: Option<u64>,    /// A voice message's waveform: at most [`WAVEFORM_MAX`] samples, 0..255.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub waveform: Vec<u8>,    /// The picture's preview ("Pictures at once", 23 Nov 2026): a tiny JPEG,    /// base64, made on the sender's phone and sealed in the box with the    /// words, so a picture is never a blank box while its file comes. At most    /// [`PREVIEW_MAX`] characters; an older phone leaves it out and ignores it.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub preview: Option<String>,}/// A preview as it may travel: a base64 JPEG (standard alphabet, padded or/// not) of at most [`PREVIEW_MAX`] characters whose bytes start as a JPEG/// does. Anything else is no preview, never a refusal: the picture still goes.pub fn preview_of(text: &str) -> Option<String> {    use base64::Engine as _;    let text = text.trim();    let text = text.strip_prefix("data:image/jpeg;base64,").unwrap_or(text);    if text.is_empty() || text.len() > PREVIEW_MAX {        return None;    }    let bytes = base64::engine::general_purpose::STANDARD.decode(text).or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(text)).ok()?;    bytes.starts_with(&[0xFF, 0xD8, 0xFF]).then(|| text.to_string())}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Payload {    pub v: u32,    pub id: String,    pub kind: Kind,    /// The sender's number, `+` and digits.    pub from: String,    pub to: String,    /// The sender's clock when it was written, ms.    pub at: i64,    /// A message's words.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub body: Option<String>,    /// The message this one answers (its id).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub reply_to: Option<String>,    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub pictures: Vec<Picture>,    /// A receipt's news, and the messages it is about.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub state: Option<Receipt>,    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub ids: Vec<String>,    /// Typing: started (true) or stopped.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub on: Option<bool>,    /// A change's what and target; an edit's new words ride in `body`.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub change: Option<Change>,    /// The group this is said in (its id), when it is: the envelope's outside says the same.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub group: Option<String>,    /// A group change's ops: the author's one, or the whole log to someone joining.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub ops: Vec<super::group::Op>,    /// The sender's name and picture as they show themselves (Cotton Chat, 20 Nov 2026), on a message.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub profile: Option<Profile>,    /// The sender's two switches (21 Nov 2026), on what a signalling app sends: a phone tells    /// read or typing only to someone whose last word said theirs is on too. Absent is off.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub signals: Option<Signals>,    /// A message's disappearing timer, seconds (chat-search, 21 Nov 2026): set, the message disappears from every    /// phone that holds it this long after `at`. Absent: it stays. An older app ignores it and keeps the message.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub timer: Option<u32>,    /// Said by the sender's agent, not the sender (an agent in a chat, 23 Nov 2026), on a group's message or    /// reaction. A message's `body` then reads "<name>: <words>" for a phone that knows no agents; this one's    /// `body` is the words.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub agent: Option<AgentMark>,    /// A message's link card, fetched by the sender's phone (FEEDBACK-4 B4, chat CONTRACT.md "Link previews"). An    /// older app ignores it; the receiver keeps it only after the same checks as the sender.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub preview: Option<LinkPreview>,    /// A group member asking for the group's whole log, their copy having lost it (owner's bug, 28 Nov 2026): a    /// member answers with the log, to them alone. An empty Group change an older build refuses, unsaid.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub ask: bool,}/// Whose agent said it: its id, its name, and a message's own words.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct AgentMark {    pub id: String,    pub name: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub body: Option<String>,}impl AgentMark {    /// What a phone that knows no agents reads: the agent's name before its words.    pub fn labelled(name: &str, words: &str) -> String {        format!("{}: {}", name.trim(), words.trim())    }}/// A link card as it travels: the words within `messages::app::preview`'s limits, `thumb` a JPEG under [`PREVIEW_MAX`].#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]pub struct LinkPreview {    pub url: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub title: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub description: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub site: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub thumb: Option<String>,}impl LinkPreview {    pub fn of(kept: &crate::messages::MessageLinkPreview) -> Self {        LinkPreview { url: kept.url.clone(), title: kept.title.clone(), description: kept.description.clone(), site: kept.site_name.clone(), thumb: kept.thumb.clone() }    }    /// As the receiver keeps it: the card checked again against the message's words, or nothing.    pub fn kept(&self, words: &str) -> Option<crate::messages::MessageLinkPreview> {        crate::messages::app::preview::checked(&serde_json::json!({ "url": self.url, "title": self.title, "description": self.description, "site": self.site, "thumb": self.thumb }), words)    }}/// A person's read-receipt and typing switches, as their own messages carry them.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct Signals {    #[serde(default)]    pub read: bool,    #[serde(default)]    pub typing: bool,}/// A person's own name and picture as they show themselves to the people they/// write to: carried sealed inside each message's box, so only those people/// (never the Worker, never someone who merely has the number) see it. The/// newest, by the sender's clock, stands.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]pub struct Profile {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub name: Option<String>,    /// The picture, a `cf1` file the Worker keeps unswept (`/v1/chat/profile-pictures/<file>`), its key here.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub picture: Option<Picture>,    /// When they last changed it, their clock, ms.    pub at: i64,}/// A name a person gives themselves, in characters at most.pub const PROFILE_NAME_MAX: usize = 80;impl Payload {    pub fn message(id: &str, from: &str, to: &str, at: i64, body: Option<String>, reply_to: Option<String>, pictures: Vec<Picture>) -> Self {        Payload { v: VERSION, id: id.into(), kind: Kind::Message, from: from.into(), to: to.into(), at, body, reply_to, pictures, state: None, ids: vec![], on: None, change: None, group: None, ops: vec![], profile: None, signals: None, timer: None, agent: None, preview: None, ask: false }    }    pub fn receipt(id: &str, from: &str, to: &str, at: i64, state: Receipt, ids: Vec<String>) -> Self {        Payload { v: VERSION, id: id.into(), kind: Kind::Receipt, from: from.into(), to: to.into(), at, body: None, reply_to: None, pictures: vec![], state: Some(state), ids, on: None, change: None, group: None, ops: vec![], profile: None, signals: None, timer: None, agent: None, preview: None, ask: false }    }    pub fn typing(id: &str, from: &str, to: &str, at: i64, on: bool) -> Self {        Payload { v: VERSION, id: id.into(), kind: Kind::Typing, from: from.into(), to: to.into(), at, body: None, reply_to: None, pictures: vec![], state: None, ids: vec![], on: Some(on), change: None, group: None, ops: vec![], profile: None, signals: None, timer: None, agent: None, preview: None, ask: false }    }    pub fn change(id: &str, from: &str, to: &str, at: i64, change: Change, body: Option<String>) -> Self {        Payload { v: VERSION, id: id.into(), kind: Kind::Change, from: from.into(), to: to.into(), at, body, reply_to: None, pictures: vec![], state: None, ids: vec![], on: None, change: Some(change), group: None, ops: vec![], profile: None, signals: None, timer: None, agent: None, preview: None, ask: false }    }    /// A group's ops, from `from` to `to`, in `group`.    pub fn group_ops(id: &str, from: &str, to: &str, at: i64, group: &str, ops: Vec<super::group::Op>) -> Self {        Payload { v: VERSION, id: id.into(), kind: Kind::Group, from: from.into(), to: to.into(), at, body: None, reply_to: None, pictures: vec![], state: None, ids: vec![], on: None, change: None, group: Some(group.into()), ops, profile: None, signals: None, timer: None, agent: None, preview: None, ask: false }    }    /// A member's ask for group `group`'s whole log.    pub fn group_ask(id: &str, from: &str, to: &str, at: i64, group: &str) -> Self {        Payload { ask: true, ..Payload::group_ops(id, from, to, at, group, vec![]) }    }    /// The same, said in a group.    pub fn in_group(mut self, group: &str) -> Self {        self.group = Some(group.into());        self    }    pub fn bytes(&self) -> Vec<u8> {        serde_json::to_vec(self).unwrap_or_default()    }}/// The outside of a held envelope, as the object hands it over.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Item {    pub id: String,    pub kind: Kind,    pub peer: String,    #[serde(default)]    pub out: bool,    #[serde(default)]    pub request: bool,    #[serde(rename = "box")]    pub sealed: String,    /// The sender's object's clock when it took the envelope, ms: the order a conversation is drawn in.    pub at: i64,    /// The group it was said in, when it was: the sender's own copies of a group's envelopes name this person's own number as `peer`.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub group: Option<String>,}/// Why an opened box is dropped. Never shown: a dropped box is as if never sent.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Dropped {    /// Not sealed for this device, or tampered with.    Unopened,    /// Sealed by a device that is not among the sender's published keys.    UnknownSender,    /// Not a payload this build reads.    Unreadable,    /// Its inside disagrees with its outside.    Mismatch(&'static str),    /// Over a size limit.    TooLarge,}/// Open and check one held item. `me` is this phone's number; `sender_keys`/// the keys the item's sender published: the other person's when it came/// from them, this person's own when it is a copy of their own message.pub fn accept(recipient_secret: &[u8; 32], item: &Item, me: &str, sender_keys: &[[u8; 32]]) -> Result<Payload, Dropped> {    let opened = super::seal::open(recipient_secret, &item.sealed).ok_or(Dropped::Unopened)?;    if !sender_keys.contains(&opened.sender) {        return Err(Dropped::UnknownSender);    }    let payload: Payload = serde_json::from_slice(&opened.payload).map_err(|_| Dropped::Unreadable)?;    check(&payload, item, me)?;    Ok(payload)}/// The inside against the outside.pub fn check(payload: &Payload, item: &Item, me: &str) -> Result<(), Dropped> {    if payload.v != VERSION {        return Err(Dropped::Unreadable);    }    if payload.id != item.id {        return Err(Dropped::Mismatch("id"));    }    if payload.kind != item.kind {        return Err(Dropped::Mismatch("kind"));    }    if payload.group != item.group {        return Err(Dropped::Mismatch("group"));    }    if payload.group.as_deref().is_some_and(|g| !super::group::is_group_id(g)) {        return Err(Dropped::Unreadable);    }    let (from, to) = if item.out { (me, item.peer.as_str()) } else { (item.peer.as_str(), me) };    if payload.from != from || payload.to != to {        return Err(Dropped::Mismatch("numbers"));    }    match payload.kind {        Kind::Message => {            if payload.body.as_deref().map_or(0, str::len) > BODY_MAX || payload.pictures.len() > PICTURES_MAX || payload.pictures.iter().any(|p| p.waveform.len() > WAVEFORM_MAX || p.name.as_deref().map_or(0, str::len) > 255 || p.preview.as_deref().map_or(0, str::len) > PREVIEW_MAX) {                return Err(Dropped::TooLarge);            }            if payload.body.as_deref().map_or(true, |b| b.trim().is_empty()) && payload.pictures.is_empty() {                return Err(Dropped::Unreadable);            }            if payload.timer.is_some_and(|t| !crate::messages::app::timer::CHOICES.contains(&t)) {                return Err(Dropped::Unreadable);            }            if payload.preview.as_ref().is_some_and(|p| p.url.len() > 2_048 || p.title.as_deref().map_or(0, str::len) > 1_024 || p.description.as_deref().map_or(0, str::len) > 2_048 || p.site.as_deref().map_or(0, str::len) > 512 || p.thumb.as_deref().map_or(0, str::len) > PREVIEW_MAX) {                return Err(Dropped::TooLarge);            }        }        Kind::Receipt => {            if payload.state.is_none() || payload.ids.is_empty() {                return Err(Dropped::Unreadable);            }            if payload.ids.len() > RECEIPT_IDS_MAX {                return Err(Dropped::TooLarge);            }        }        Kind::Typing => {            if payload.on.is_none() {                return Err(Dropped::Unreadable);            }        }        Kind::Agent => return Err(Dropped::Unreadable),        Kind::Group => {            // An ask for the whole log carries no ops (an older build drops it here, unsaid).            if payload.group.is_none() || (payload.ops.is_empty() && !payload.ask) {                return Err(Dropped::Unreadable);            }            if payload.ops.len() > super::group::LOG_MAX {                return Err(Dropped::TooLarge);            }        }        Kind::Change => {            let Some(change) = &payload.change else { return Err(Dropped::Unreadable) };            if change.message.is_empty() {                return Err(Dropped::Unreadable);            }            match change.what {                What::React => match change.emoji.as_deref().map(str::trim) {                    Some(e) if !e.is_empty() && e.len() <= EMOJI_MAX => {}                    Some(e) if !e.is_empty() => return Err(Dropped::TooLarge),                    _ => return Err(Dropped::Unreadable),                },                What::Edit => {                    if payload.body.as_deref().map_or(0, str::len) > BODY_MAX {                        return Err(Dropped::TooLarge);                    }                    if payload.body.as_deref().map_or(true, |b| b.trim().is_empty()) {                        return Err(Dropped::Unreadable);                    }                }                What::Transcript => {                    if payload.body.as_deref().map_or(0, str::len) > TRANSCRIPT_MAX {                        return Err(Dropped::TooLarge);                    }                    if payload.body.as_deref().map_or(true, |b| b.trim().is_empty()) {                        return Err(Dropped::Unreadable);                    }                }                What::Timer => {                    let seconds = payload.body.as_deref().and_then(|b| b.parse::<u32>().ok());                    if !seconds.is_some_and(|s| crate::messages::app::timer::CHOICES.contains(&s)) {                        return Err(Dropped::Unreadable);                    }                }                What::Call => {                    if !crate::calling::wire::is_room_id(&change.message) || !matches!(payload.body.as_deref(), Some("voice" | "video")) {                        return Err(Dropped::Unreadable);                    }                }                What::Unreact | What::Delete => {}            }        }    }    if let Some(agent) = &payload.agent {        // An agent speaks in a group, and only words or a reaction.        if payload.group.is_none() || !super::group::is_agent_id(&agent.id) || !super::group::agent_name_ok(&agent.name) {            return Err(Dropped::Unreadable);        }        match payload.kind {            Kind::Message => {                let words = agent.body.as_deref().map(str::trim).unwrap_or_default();                if words.is_empty() || !payload.pictures.is_empty() {                    return Err(Dropped::Unreadable);                }                if words.len() > BODY_MAX {                    return Err(Dropped::TooLarge);                }            }            Kind::Change if matches!(payload.change.as_ref().map(|c| c.what), Some(What::React | What::Unreact)) => {}            _ => return Err(Dropped::Unreadable),        }    }    Ok(())}#[cfg(test)]#[path = "payload_tests.rs"]mod tests;