Cotton code
693 lines · 26.6 KB · RustRaw
//! COTTON GROUPS (20 Nov 2026): a conversation between//! several Cotton people, sealed end to end, with no group the Worker can read.//!//! **Sealing: one box per member device, never a group key.** A group message//! is the one-to-one `c1:` box ([`super::seal`]) made once for each device of//! each current member (and the sender's own other devices), and the Worker//! routes each member's boxes to that member's object exactly as it routes a//! one-to-one message. Chosen over sender keys because://! - removal is immediate and complete: the moment a sender's phone knows a//!   member is out, no box is made for them; there is no shared key to rotate,//!   so no window in which a removed member still holds a key that opens what//!   is sent next, and no rotation message that can be lost;//! - a new member reads nothing from before they joined: nothing earlier was//!   ever sealed for them, and there is no chain key to hand over or withhold;//! - nothing new to trust: the box, its sender binding and its checks are the//!   ones one-to-one chat already relies on and tests;//! - the cost is a box per device: a message's words are small (16 KB at most,//!   pictures travel by key), so a family group of 20 people with two phones//!   each is forty small boxes in one request. [`MEMBERS_MAX`] keeps it there.//!   Sender keys pay off at hundreds of members, which these groups are not.//!//! **Membership is an op log every member folds the same way.** The Worker//! keeps no roster it could be asked about or could change. Each change//! (create, add, remove, leave, make or unmake an admin, rename, picture) is//! an [`Op`] its author seals to every member like a message. Every phone keeps//! the log it has seen and [`fold`]s it, sorted by (`rev`, author, id): a//! Lamport stamp, so the same set of ops gives the same group on every phone//! whatever order they arrived in, and two admins' concurrent changes to//! different people both stand. An op counts only when its author was allowed//! to make it at its place in that order (admins add, remove, rename and//! change the picture; anyone leaves), so a phone that receives a change from//! someone it does not yet know is an admin leaves it waiting//! ([`Accept::Wait`]) rather than refusing it.//!//! **Who vouches for an op.** An op that arrives directly is authenticated by//! its box: [`merge`] takes from a sender only the ops that sender wrote. The//! one exception is the welcome: a phone joining (or rejoining) a group has no//! history of its own and takes the whole log from the member who added it,//! trusting the person who invited it, as every messenger does.//!//! **What this does not give.** No forward secrecy (the box has none). And no//! signature on an op beyond its box: a member who was an admin can still//! write a change stamped before they lost it, which the fold will honour.//! Members are trusted not to forge history against their own group; the//! Worker, which never holds a key, cannot.use std::collections::{BTreeMap, BTreeSet};use serde::{Deserialize, Serialize};use super::payload::Picture;/// People in a group at most, the creator included: the fan-out's bound.pub const MEMBERS_MAX: usize = 64;/// Ops a group's log keeps at most; past it the group takes no more changes.pub const LOG_MAX: usize = 2000;/// A group's name at most, in characters.pub const TITLE_MAX: usize = 100;/// Agents in a group at most (an agent in a chat, 23 Nov 2026).pub const AGENTS_MAX: usize = 4;/// An agent's name at most, in characters.pub const AGENT_NAME_MAX: usize = 60;/// The highest stamp an op may carry: far beyond any real group, and far from overflow.pub const REV_MAX: u64 = 1 << 40;/// A group's id: 16 random bytes as hex, made by its creator.pub fn is_group_id(id: &str) -> bool {    id.len() == 32 && id.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))}/// What one op does.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(tag = "op", rename_all = "lowercase")]pub enum What {    /// The group made: its name and its first members besides the creator.    Create { title: String, members: Vec<String> },    Add { members: Vec<String> },    Remove { members: Vec<String> },    /// The author leaves.    Leave,    /// Made admins.    Admin { members: Vec<String> },    /// No longer admins (one admin always stays).    Unadmin { members: Vec<String> },    Rename { title: String },    /// The group's picture, sealed like a message's (its key rides in the op); `None` takes it away.    Picture {        #[serde(default, skip_serializing_if = "Option::is_none")]        picture: Option<Picture>,    },    /// The author's own agent joins (`on`) or goes (an agent in a chat, 23 Nov 2026). Its person or an admin    /// takes it out; only its person brings it in.    Agent { agent: AgentId, on: bool },}/// An agent as a group knows it: its id (the person's connection's member id) and the name it speaks under.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct AgentId {    pub id: String,    pub name: String,}/// An agent a group has held.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct AgentSeat {    pub name: String,    /// Its person's number: whose agent it is.    pub of: String,    /// In the group now.    pub on: bool,    /// The stamp it was last brought in or taken out at.    pub rev: u64,    /// Who took it out, when someone did.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub out_by: Option<String>,}/// Whether an agent's id is one an op may name: 1 to 64 letters, digits and dashes.pub fn is_agent_id(id: &str) -> bool {    !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')}/// Whether an agent's name may be carried: some words, at most [`AGENT_NAME_MAX`] characters, one line.pub fn agent_name_ok(name: &str) -> bool {    !name.trim().is_empty() && name.chars().count() <= AGENT_NAME_MAX && !name.chars().any(char::is_control)}/// One change to a group, by its author.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Op {    /// The op's own id (fresh random hex).    pub id: String,    /// Its Lamport stamp: one more than the highest its author had seen.    pub rev: u64,    /// Its author's number.    pub by: String,    /// Its author's clock, ms (drawn, never ordered by).    pub at: i64,    #[serde(flatten)]    pub what: What,}impl Op {    fn order(&self) -> (u64, &str, &str) {        (self.rev, self.by.as_str(), self.id.as_str())    }    /// The numbers this op names, besides its author.    pub fn subjects(&self) -> &[String] {        match &self.what {            What::Create { members, .. } | What::Add { members } | What::Remove { members } | What::Admin { members } | What::Unadmin { members } => members,            _ => &[],        }    }}/// How a member left, when they did.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum Out {    Left,    Removed { by: String },}/// One person a group has ever held.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Seat {    pub admin: bool,    /// In the group now.    pub member: bool,    /// Who added them (the creator for the first members; themselves for the creator).    pub added_by: String,    /// The stamp they were last added at: their seniority when an admin must be chosen.    pub added_rev: u64,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub out: Option<Out>,}/// A group as its log folds.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct State {    /// Whether a creating op stands at the log's head: without one there is no group yet.    pub made: bool,    pub creator: Option<String>,    pub title: String,    pub picture: Option<Picture>,    pub seats: BTreeMap<String, Seat>,    /// The highest stamp in the log: a new op's is one more.    pub rev: u64,    /// The ops that counted, in the order they were applied.    pub applied: Vec<String>,    /// The agents it has held, by id (an agent in a chat, 23 Nov 2026).    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]    pub agents: BTreeMap<String, AgentSeat>,}impl State {    pub fn is_member(&self, number: &str) -> bool {        self.seats.get(number).is_some_and(|s| s.member)    }    pub fn is_admin(&self, number: &str) -> bool {        self.seats.get(number).is_some_and(|s| s.member && s.admin)    }    /// Current members, in number order.    pub fn members(&self) -> Vec<String> {        self.seats.iter().filter(|(_, s)| s.member).map(|(n, _)| n.clone()).collect()    }    /// Current members other than `me`: whom a message is sealed for.    pub fn audience(&self, me: &str) -> Vec<String> {        self.members().into_iter().filter(|n| n != me).collect()    }    /// Whether this agent is in the group now.    pub fn has_agent(&self, id: &str) -> bool {        self.agents.get(id).is_some_and(|a| a.on)    }    /// Whether `id` is an agent of `number` in the group now: what a message marked as an agent's must be.    pub fn is_agent_of(&self, id: &str, number: &str) -> bool {        self.agents.get(id).is_some_and(|a| a.on && a.of == number)    }    /// The agents in the group now, by id.    pub fn agents_on(&self) -> Vec<(&String, &AgentSeat)> {        self.agents.iter().filter(|(_, a)| a.on).collect()    }    fn agent_count(&self) -> usize {        self.agents.values().filter(|a| a.on).count()    }    /// A person out of the group takes their agents out with them.    fn agents_follow(&mut self, rev: u64) {        let gone: Vec<String> = self.agents.iter().filter(|(_, a)| a.on && !self.is_member(&a.of)).map(|(id, _)| id.clone()).collect();        for id in gone {            if let Some(a) = self.agents.get_mut(&id) {                a.on = false;                a.rev = rev;                a.out_by = None;            }        }    }    fn count(&self) -> usize {        self.seats.values().filter(|s| s.member).count()    }    fn admins(&self) -> usize {        self.seats.values().filter(|s| s.member && s.admin).count()    }    /// One admin always stands while anyone is in: the longest-standing member, when the last admin goes.    fn keep_an_admin(&mut self) {        if self.admins() > 0 {            return;        }        let eldest = self.seats.iter().filter(|(_, s)| s.member).min_by(|a, b| (a.1.added_rev, a.0).cmp(&(b.1.added_rev, b.0))).map(|(n, _)| n.clone());        if let Some(number) = eldest {            if let Some(seat) = self.seats.get_mut(&number) {                seat.admin = true;            }        }    }}/// Whether a number is one an op may name: `+` and 6 to 15 digits.pub fn is_number(number: &str) -> bool {    number.strip_prefix('+').is_some_and(|d| (6..=15).contains(&d.len()) && d.bytes().all(|b| b.is_ascii_digit()))}/// Whether an op is well made, whatever the group: its shape, never its permission.pub fn well_made(op: &Op) -> bool {    if op.id.is_empty() || op.id.len() > 64 || !op.id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {        return false;    }    if op.rev == 0 || op.rev > REV_MAX || !is_number(&op.by) {        return false;    }    let names_ok = |members: &[String]| !members.is_empty() && members.len() <= MEMBERS_MAX && members.iter().all(|m| is_number(m));    match &op.what {        What::Create { title, members } => title_ok(title) && members.len() < MEMBERS_MAX && members.iter().all(|m| is_number(m) && m != &op.by),        What::Add { members } | What::Remove { members } | What::Admin { members } | What::Unadmin { members } => names_ok(members),        What::Leave => true,        What::Rename { title } => title_ok(title),        What::Picture { picture } => picture.as_ref().is_none_or(|p| !p.file.is_empty() && p.file.len() <= 64 && !p.key.is_empty()),        What::Agent { agent, .. } => is_agent_id(&agent.id) && agent_name_ok(&agent.name),    }}/// A name a group may carry: some words, at most [`TITLE_MAX`] characters.pub fn title_ok(title: &str) -> bool {    !title.trim().is_empty() && title.chars().count() <= TITLE_MAX}/// The log, ordered by stamp, each op once (by id; the first copy stands).pub fn ordered(log: &[Op]) -> Vec<&Op> {    let mut seen = BTreeSet::new();    let mut ops: Vec<&Op> = log.iter().filter(|op| seen.insert(op.id.as_str())).collect();    ops.sort_by(|a, b| a.order().cmp(&b.order()));    ops}/// The group a log makes: every op in stamp order, each counted only when its/// author could make it there. The same ops give the same group, whatever/// order they arrived in.pub fn fold(log: &[Op]) -> State {    let mut state = State::default();    for op in ordered(log) {        state.rev = state.rev.max(op.rev);        if !well_made(op) {            continue;        }        if apply(&mut state, op) {            state.applied.push(op.id.clone());        }        state.agents_follow(op.rev);    }    state}/// One op on the group so far; whether it counted.fn apply(state: &mut State, op: &Op) -> bool {    let by = op.by.as_str();    match &op.what {        What::Create { title, members } => {            if state.made {                return false;            }            state.made = true;            state.creator = Some(op.by.clone());            state.title = title.trim().to_string();            state.seats.insert(op.by.clone(), Seat { admin: true, member: true, added_by: op.by.clone(), added_rev: op.rev, out: None });            for number in members {                if state.count() >= MEMBERS_MAX {                    break;                }                state.seats.entry(number.clone()).or_insert(Seat { admin: false, member: true, added_by: op.by.clone(), added_rev: op.rev, out: None });            }            true        }        _ if !state.made => false,        What::Add { members } => {            if !state.is_admin(by) {                return false;            }            let mut any = false;            for number in members {                if state.is_member(number) || state.count() >= MEMBERS_MAX {                    continue;                }                state.seats.insert(number.clone(), Seat { admin: false, member: true, added_by: op.by.clone(), added_rev: op.rev, out: None });                any = true;            }            any        }        What::Remove { members } => {            if !state.is_admin(by) {                return false;            }            let mut any = false;            for number in members {                if number == by {                    continue;                }                if let Some(seat) = state.seats.get_mut(number).filter(|s| s.member) {                    seat.member = false;                    seat.admin = false;                    seat.out = Some(Out::Removed { by: op.by.clone() });                    any = true;                }            }            state.keep_an_admin();            any        }        What::Leave => {            let Some(seat) = state.seats.get_mut(by).filter(|s| s.member) else { return false };            seat.member = false;            seat.admin = false;            seat.out = Some(Out::Left);            state.keep_an_admin();            true        }        What::Admin { members } => {            if !state.is_admin(by) {                return false;            }            let mut any = false;            for number in members {                if let Some(seat) = state.seats.get_mut(number).filter(|s| s.member && !s.admin) {                    seat.admin = true;                    any = true;                }            }            any        }        What::Unadmin { members } => {            if !state.is_admin(by) {                return false;            }            let mut any = false;            for number in members {                if state.admins() <= 1 {                    break;                }                if let Some(seat) = state.seats.get_mut(number).filter(|s| s.member && s.admin) {                    seat.admin = false;                    any = true;                }            }            any        }        What::Rename { title } => {            if !state.is_admin(by) || state.title == title.trim() {                return false;            }            state.title = title.trim().to_string();            true        }        What::Picture { picture } => {            if !state.is_admin(by) {                return false;            }            state.picture = picture.clone();            true        }        What::Agent { agent, on: true } => {            if !state.is_member(by) || state.has_agent(&agent.id) || state.agent_count() >= AGENTS_MAX {                return false;            }            // An agent is its person's for good: another member cannot bring in someone else's.            if state.agents.get(&agent.id).is_some_and(|a| a.of != by) {                return false;            }            state.agents.insert(agent.id.clone(), AgentSeat { name: agent.name.trim().to_string(), of: op.by.clone(), on: true, rev: op.rev, out_by: None });            true        }        What::Agent { agent, on: false } => {            let Some(seat) = state.agents.get(&agent.id).filter(|a| a.on) else { return false };            if seat.of != by && !state.is_admin(by) {                return false;            }            let seat = state.agents.get_mut(&agent.id).expect("held");            seat.on = false;            seat.rev = op.rev;            seat.out_by = Some(op.by.clone());            true        }    }}/// What a phone does with ops that arrived from one sender.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Accept {    /// Taken into the log: the new log, and the ids of ops that are new to it.    Merged { log: Vec<Op>, new: Vec<String> },    /// Not yet: they name a group this phone has no head for, or an author it    /// does not yet know may make them. Kept waiting (the box stays held) and    /// tried again on the next pass.    Wait,    /// Never: not well made, or written by someone other than the sender    /// outside a welcome.    Refuse,}/// Ops from `sender` merged into `log`, `me` being this phone's number.////// Directly, a sender vouches only for their own ops. A welcome (a log taken/// while this phone is not in the group: it never was, or was taken out and is/// being added back) is taken whole: the inviter vouches for the history, and/// the welcome must leave both the sender and `me` in the group.pub fn merge(log: &[Op], incoming: &[Op], sender: &str, me: &str) -> Accept {    if incoming.is_empty() || incoming.len() > LOG_MAX || incoming.iter().any(|op| !well_made(op)) {        return Accept::Refuse;    }    let before = fold(log);    let welcome = !before.is_member(me);    if !welcome && incoming.iter().any(|op| op.by != sender) {        return Accept::Refuse;    }    let known: BTreeSet<&str> = log.iter().map(|op| op.id.as_str()).collect();    let fresh: Vec<&Op> = incoming.iter().filter(|op| !known.contains(op.id.as_str())).collect();    if fresh.is_empty() {        return Accept::Merged { log: log.to_vec(), new: vec![] };    }    if log.len() + fresh.len() > LOG_MAX {        return Accept::Refuse;    }    let mut merged = log.to_vec();    merged.extend(fresh.iter().map(|op| (*op).clone()));    let after = fold(&merged);    if welcome {        // A welcome must make a group holding both its sender and this phone.        if !after.made || !after.is_member(sender) || !after.is_member(me) {            return if after.made { Accept::Refuse } else { Accept::Wait };        }    } else if !after.made {        return Accept::Wait;    }    // A direct op that did not count may yet: its author's admin may be on its way.    let counted: BTreeSet<&str> = after.applied.iter().map(String::as_str).collect();    if !welcome && fresh.iter().any(|op| !counted.contains(op.id.as_str()) && !matches!(op.what, What::Create { .. })) && !before.is_admin(sender) && !after.is_admin(sender) {        return Accept::Wait;    }    Accept::Merged { new: fresh.iter().map(|op| op.id.clone()).collect(), log: merged }}/// Why a change cannot be made, in the person's words (the screens say them as they are).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Refusal {    NotMember,    NotAdmin,    Full,    BadName,    NoOne,    LastAdmin,    Own,    /// The agent is in the group already.    AgentIn,    /// Only an agent's person (or an admin, to take it out) can do that.    NotYours,    AgentsFull,}impl Refusal {    pub fn code(self) -> &'static str {        match self {            Refusal::NotMember => "not_member",            Refusal::NotAdmin => "not_admin",            Refusal::Full => "group_full",            Refusal::BadName => "bad_name",            Refusal::NoOne => "no_one",            Refusal::LastAdmin => "last_admin",            Refusal::Own => "own_number",            Refusal::AgentIn => "already_in",            Refusal::NotYours => "not_yours",            Refusal::AgentsFull => "agents_full",        }    }    pub fn words(self) -> &'static str {        match self {            Refusal::NotMember => "You're no longer in this group.",            Refusal::NotAdmin => "Only the group's admins can do that.",            Refusal::Full => "A group holds 64 people at most.",            Refusal::BadName => "Give the group a name of 100 characters or fewer.",            Refusal::NoOne => "There's nobody new to add.",            Refusal::LastAdmin => "Make someone else an admin first.",            Refusal::Own => "That's you.",            Refusal::AgentIn => "That agent is in this chat already.",            Refusal::NotYours => "Only its person or an admin can do that.",            Refusal::AgentsFull => "A group holds 4 agents at most.",        }    }}/// What a group lets `me` do now: the screens draw only these.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]pub struct Can {    pub send: bool,    pub add: bool,    pub remove: bool,    pub rename: bool,    pub picture: bool,    pub admins: bool,    pub leave: bool,}pub fn can(state: &State, me: &str) -> Can {    let member = state.is_member(me);    let admin = state.is_admin(me);    Can { send: member, add: admin && state.count() < MEMBERS_MAX, remove: admin, rename: admin, picture: admin, admins: admin, leave: member }}/// The op `me` would write, checked against the group as it stands, its stamp/// one past the log's. `id` and `at` are the caller's (fresh, and its clock).pub fn make(state: &State, me: &str, id: &str, at: i64, what: What) -> Result<Op, Refusal> {    if !state.is_member(me) {        return Err(Refusal::NotMember);    }    match &what {        What::Create { .. } => return Err(Refusal::NotMember),        What::Leave => {}        What::Agent { agent, on: true } => {            if state.has_agent(&agent.id) {                return Err(Refusal::AgentIn);            }            if state.agents.get(&agent.id).is_some_and(|a| a.of != me) {                return Err(Refusal::NotYours);            }            if state.agent_count() >= AGENTS_MAX {                return Err(Refusal::AgentsFull);            }        }        What::Agent { agent, on: false } => match state.agents.get(&agent.id).filter(|a| a.on) {            None => return Err(Refusal::NoOne),            Some(seat) if seat.of != me && !state.is_admin(me) => return Err(Refusal::NotYours),            Some(_) => {}        },        _ if !state.is_admin(me) => return Err(Refusal::NotAdmin),        What::Add { members } => {            let new: Vec<&String> = members.iter().filter(|m| !state.is_member(m)).collect();            if members.iter().any(|m| m == me) {                return Err(Refusal::Own);            }            if new.is_empty() {                return Err(Refusal::NoOne);            }            if state.count() + new.len() > MEMBERS_MAX {                return Err(Refusal::Full);            }        }        What::Remove { members } => {            if members.iter().any(|m| m == me) {                return Err(Refusal::Own);            }            if !members.iter().any(|m| state.is_member(m)) {                return Err(Refusal::NoOne);            }        }        What::Admin { members } => {            if !members.iter().any(|m| state.is_member(m) && !state.is_admin(m)) {                return Err(Refusal::NoOne);            }        }        What::Unadmin { members } => {            if !members.iter().any(|m| state.is_admin(m)) {                return Err(Refusal::NoOne);            }            if state.admins() <= members.iter().filter(|m| state.is_admin(m)).count() {                return Err(Refusal::LastAdmin);            }        }        What::Rename { title } => {            if !title_ok(title) {                return Err(Refusal::BadName);            }        }        What::Picture { .. } => {}    }    let op = Op { id: id.to_string(), rev: state.rev.saturating_add(1).min(REV_MAX), by: me.to_string(), at, what };    if !well_made(&op) {        return Err(Refusal::BadName);    }    Ok(op)}/// A new group's first op: `me` creates it with `title` and `members`.pub fn create(me: &str, id: &str, at: i64, title: &str, members: &[String]) -> Result<Op, Refusal> {    if !title_ok(title) {        return Err(Refusal::BadName);    }    let mut others: Vec<String> = members.iter().filter(|m| m.as_str() != me).cloned().collect();    others.sort();    others.dedup();    if others.is_empty() {        return Err(Refusal::NoOne);    }    if others.len() + 1 > MEMBERS_MAX {        return Err(Refusal::Full);    }    let op = Op { id: id.to_string(), rev: 1, by: me.to_string(), at, what: What::Create { title: title.trim().to_string(), members: others } };    if !well_made(&op) {        return Err(Refusal::BadName);    }    Ok(op)}/// Whom an op goes to: everyone in the group after it, and, for a removal or/// a leave, those it took out too (so they know). The newly added get the/// whole log ([`welcomed`]) instead.pub fn told(before: &State, after: &State, op: &Op, me: &str) -> Vec<String> {    let mut to: BTreeSet<String> = after.audience(me).into_iter().collect();    if matches!(op.what, What::Remove { .. } | What::Leave) {        to.extend(before.audience(me));    }    for number in welcomed(before, after) {        to.remove(&number);    }    to.remove(me);    to.into_iter().collect()}/// Who an op brought in: members after it who were not before.pub fn welcomed(before: &State, after: &State) -> Vec<String> {    after.members().into_iter().filter(|n| !before.is_member(n)).collect()}#[cfg(test)]#[path = "group_tests.rs"]mod tests;