Skip to main content

weirdnet_collab/
chat.rs

1//! A project's text chat: signed messages, reactions and mentions, kept by the host.
2//!
3//! The app names the three permissions ([`ChatPerms`]): read, write, and manage (delete anyone's
4//! message). Every call checks them against the [`Project`] at that moment, so a role change, an
5//! override or a ban applies to the next message. Muting someone is a member rule that denies
6//! `write`. The log keeps all history; a deleted message keeps its place with its text removed.
7//! Each change gets a new sequence number, so a client asks for what changed since the last one
8//! it saw.
9use crate::enc::{Enc, signed_by};
10use crate::ids::{Permission, ProjectId, RecordId};
11use crate::project::{Ctx, Project};
12use crate::records::SignError;
13use serde::{Deserialize, Serialize};
14use std::collections::{BTreeMap, BTreeSet};
15use weirdnet_contacts::UserId;
16use weirdnet_net::Keypair;
17
18/// The longest message, in bytes.
19pub const MAX_TEXT: usize = 4000;
20/// The longest reaction, in bytes (one emoji or a short word).
21pub const MAX_REACTION: usize = 16;
22/// Most different reactions on one message.
23pub const MAX_REACTIONS: usize = 24;
24
25/// Which permissions govern chat.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct ChatPerms {
28    /// Read the chat.
29    pub read: Permission,
30    /// Post and react.
31    pub write: Permission,
32    /// Delete anyone's message.
33    pub manage: Permission,
34}
35
36/// Why a chat call was refused.
37#[derive(Debug, PartialEq, Eq, thiserror::Error)]
38pub enum ChatError {
39    /// The caller lacks the permission.
40    #[error("not allowed")]
41    NotAllowed,
42    /// The signature does not hold.
43    #[error("bad signature")]
44    BadSignature,
45    /// The message is for another project.
46    #[error("wrong project")]
47    WrongProject,
48    /// The message was signed by someone other than the caller.
49    #[error("not your message")]
50    NotYours,
51    /// Empty, or too long.
52    #[error("the text is empty or too long")]
53    BadText,
54    /// A message with that id is already there.
55    #[error("duplicate message")]
56    Duplicate,
57    /// No such message.
58    #[error("no such message")]
59    NoSuchMessage,
60    /// It mentions someone who is not a member.
61    #[error("mentions someone who is not in the project")]
62    UnknownMention,
63}
64
65/// One signed chat message.
66#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
67pub struct ChatMessage {
68    /// Unique id, chosen by the author.
69    pub id: RecordId,
70    /// The project.
71    pub project: ProjectId,
72    /// Who wrote it.
73    pub author: UserId,
74    /// The text.
75    pub text: String,
76    /// Who it mentions.
77    pub mentions: Vec<UserId>,
78    /// When it was written, by the author's clock.
79    pub at_ms: i64,
80    /// The author's public key, protobuf-encoded.
81    pub key: Vec<u8>,
82    /// The author's signature.
83    pub sig: Vec<u8>,
84}
85
86impl ChatMessage {
87    fn bytes(&self) -> Vec<u8> {
88        let e = Enc::new("chat").s(self.id.as_str()).s(self.project.as_str()).s(self.author.as_str()).s(&self.text);
89        self.mentions.iter().fold(e.u32(self.mentions.len() as u32), |e, u| e.s(u.as_str())).i64(self.at_ms).b(&self.key).done()
90    }
91
92    /// Write and sign a message as `author`, with a 128-bit random id.
93    pub fn sign(author: &Keypair, project: &ProjectId, text: &str, mentions: Vec<UserId>, now: i64) -> Result<ChatMessage, SignError> {
94        let mut b = [0u8; 16];
95        getrandom::fill(&mut b).map_err(|e| SignError(e.to_string()))?;
96        let id: String = std::iter::once('m').chain(b.iter().flat_map(|x| format!("{x:02x}").chars().collect::<Vec<_>>())).collect();
97        let mut m = ChatMessage {
98            id: RecordId::new(&id),
99            project: project.clone(),
100            author: UserId::of_keypair(author),
101            text: text.to_string(),
102            mentions,
103            at_ms: now,
104            key: author.public().encode_protobuf(),
105            sig: Vec::new(),
106        };
107        m.sig = author.sign(&m.bytes()).map_err(|e| SignError(e.to_string()))?;
108        Ok(m)
109    }
110
111    /// Whether the author signed it.
112    pub fn verify(&self) -> bool {
113        signed_by(&self.author, &self.key, &self.bytes(), &self.sig)
114    }
115}
116
117/// A message as the log keeps it.
118#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
119pub struct ChatItem {
120    /// The message. After a deletion its text and mentions are empty and it no longer verifies.
121    pub message: ChatMessage,
122    /// Reactions: each reaction and who gave it.
123    pub reactions: BTreeMap<String, BTreeSet<UserId>>,
124    /// Who deleted it, and when.
125    pub deleted: Option<(UserId, i64)>,
126    /// When the host took it in, by the host's clock.
127    pub posted_ms: i64,
128    /// The sequence number of its last change.
129    pub seq: u64,
130}
131
132impl ChatItem {
133    /// Whether it mentions `user` (and is not deleted).
134    pub fn mentions(&self, user: &UserId) -> bool {
135        self.deleted.is_none() && self.message.mentions.contains(user)
136    }
137}
138
139/// A project's chat, kept by the host.
140#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
141pub struct ChatLog {
142    items: Vec<ChatItem>,
143    seq: u64,
144}
145
146impl ChatLog {
147    fn may(p: &Project, who: &UserId, perm: &Permission, now: i64) -> Result<(), ChatError> {
148        if p.can(who, perm.as_str(), &Ctx::at(now)) { Ok(()) } else { Err(ChatError::NotAllowed) }
149    }
150
151    fn bump(&mut self) -> u64 {
152        self.seq += 1;
153        self.seq
154    }
155
156    /// The latest sequence number.
157    pub fn seq(&self) -> u64 {
158        self.seq
159    }
160
161    /// Take in a message `from` posted. It must be theirs, signed, for this project, and they
162    /// must have `write` now, and everyone it mentions must be a member. Returns its
163    /// sequence number.
164    pub fn post(&mut self, p: &Project, perms: &ChatPerms, from: &UserId, m: ChatMessage, now: i64) -> Result<u64, ChatError> {
165        if &m.author != from {
166            return Err(ChatError::NotYours);
167        }
168        if &m.project != p.id() {
169            return Err(ChatError::WrongProject);
170        }
171        if !m.verify() {
172            return Err(ChatError::BadSignature);
173        }
174        Self::may(p, from, &perms.write, now)?;
175        if m.text.trim().is_empty() || m.text.len() > MAX_TEXT {
176            return Err(ChatError::BadText);
177        }
178        if self.items.iter().any(|i| i.message.id == m.id) {
179            return Err(ChatError::Duplicate);
180        }
181        if m.mentions.iter().any(|u| p.member(u).is_none()) {
182            return Err(ChatError::UnknownMention);
183        }
184        let seq = self.bump();
185        self.items.push(ChatItem { message: m, reactions: BTreeMap::new(), deleted: None, posted_ms: now, seq });
186        Ok(seq)
187    }
188
189    fn item_mut(&mut self, id: &RecordId) -> Result<&mut ChatItem, ChatError> {
190        self.items.iter_mut().find(|i| &i.message.id == id && i.deleted.is_none()).ok_or(ChatError::NoSuchMessage)
191    }
192
193    /// `who` adds (`on`) or takes back a reaction. Needs `write`.
194    #[allow(clippy::too_many_arguments)]
195    pub fn react(
196        &mut self,
197        p: &Project,
198        perms: &ChatPerms,
199        who: &UserId,
200        id: &RecordId,
201        reaction: &str,
202        on: bool,
203        now: i64,
204    ) -> Result<u64, ChatError> {
205        Self::may(p, who, &perms.write, now)?;
206        if reaction.is_empty() || reaction.len() > MAX_REACTION || reaction.chars().any(char::is_whitespace) {
207            return Err(ChatError::BadText);
208        }
209        let item = self.item_mut(id)?;
210        if on && !item.reactions.contains_key(reaction) && item.reactions.len() >= MAX_REACTIONS {
211            return Err(ChatError::BadText);
212        }
213        let changed = if on {
214            item.reactions.entry(reaction.to_string()).or_default().insert(who.clone())
215        } else {
216            let r = item.reactions.get_mut(reaction).is_some_and(|s| s.remove(who));
217            item.reactions.retain(|_, s| !s.is_empty());
218            r
219        };
220        if !changed {
221            return Ok(self.seq);
222        }
223        let seq = self.bump();
224        self.item_mut(id)?.seq = seq;
225        Ok(seq)
226    }
227
228    /// Delete a message: its author may (with `write`), and so may anyone with `manage`.
229    pub fn delete(&mut self, p: &Project, perms: &ChatPerms, who: &UserId, id: &RecordId, now: i64) -> Result<u64, ChatError> {
230        let author = self.item_mut(id)?.message.author.clone();
231        if &author == who {
232            Self::may(p, who, &perms.write, now).or_else(|_| Self::may(p, who, &perms.manage, now))?;
233        } else {
234            Self::may(p, who, &perms.manage, now)?;
235        }
236        let seq = self.bump();
237        let item = self.item_mut(id)?;
238        item.message.text.clear();
239        item.message.mentions.clear();
240        item.reactions.clear();
241        item.deleted = Some((who.clone(), now));
242        item.seq = seq;
243        Ok(seq)
244    }
245
246    /// What changed after `since`, oldest first, if `who` may read. Pass 0 for all history.
247    pub fn since(&self, p: &Project, perms: &ChatPerms, who: &UserId, since: u64, now: i64) -> Result<Vec<ChatItem>, ChatError> {
248        Self::may(p, who, &perms.read, now)?;
249        let mut v: Vec<ChatItem> = self.items.iter().filter(|i| i.seq > since).cloned().collect();
250        v.sort_by_key(|i| i.seq);
251        Ok(v)
252    }
253
254    /// All messages, in the order they were posted.
255    pub fn items(&self) -> &[ChatItem] {
256        &self.items
257    }
258}
259
260/// Merge changed items into a client's copy, keyed by message id, kept in posting order.
261pub fn merge(into: &mut Vec<ChatItem>, changed: Vec<ChatItem>) {
262    for c in changed {
263        match into.iter_mut().find(|i| i.message.id == c.message.id) {
264            Some(i) => *i = c,
265            None => into.push(c),
266        }
267    }
268    into.sort_by(|a, b| a.posted_ms.cmp(&b.posted_ms).then(a.message.id.cmp(&b.message.id)));
269}