Skip to main content

weirdnet_contacts/
message.rs

1//! Signed direct messages, their delivery state, and conversations that merge.
2use crate::id::UserId;
3use serde::{Deserialize, Serialize};
4use weirdnet_net::{Keypair, PublicKey};
5
6/// The longest text body, in bytes.
7pub const MAX_TEXT: usize = 4000;
8/// The longest invite note, in bytes.
9pub const MAX_NOTE: usize = 200;
10
11const DOMAIN: &[u8] = b"weirdnet-contacts/msg/1\0";
12
13/// A message id: unique per sender (`<sender suffix>-<time>-<counter>`).
14#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[serde(transparent)]
16pub struct MessageId(pub String);
17
18/// An invitation to a collaboration, as a card in a conversation. The app decides what a
19/// project and a role are.
20#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
21pub struct DirectInvite {
22    /// The project's id.
23    pub project: String,
24    /// The offered role.
25    pub role: String,
26    /// A note from the sender.
27    pub note: String,
28    /// When the invite stops being valid, milliseconds since the epoch.
29    pub expires_ms: Option<i64>,
30}
31
32/// What a message says. Text and invite cards only: no voice, no attachments.
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34pub enum Body {
35    /// Text.
36    Text(String),
37    /// An invite card.
38    Invite(DirectInvite),
39}
40
41fn lp(out: &mut Vec<u8>, b: &[u8]) {
42    out.extend_from_slice(&(b.len() as u32).to_be_bytes());
43    out.extend_from_slice(b);
44}
45
46/// A signed message.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub struct Message {
49    /// Unique per sender.
50    pub id: MessageId,
51    /// The sender.
52    pub from: UserId,
53    /// The recipient.
54    pub to: UserId,
55    /// When it was written, milliseconds since the epoch.
56    pub sent_ms: i64,
57    /// The content.
58    pub body: Body,
59    /// The sender's public key, protobuf-encoded; `from` must be its identity.
60    pub key: Vec<u8>,
61    /// The sender's signature over [`Message::signing_bytes`].
62    pub sig: Vec<u8>,
63}
64
65impl Message {
66    /// The signed bytes: a domain tag, then the fields in a fixed order with 32-bit
67    /// big-endian lengths. The signature does not depend on the wire codec.
68    pub fn signing_bytes(&self) -> Vec<u8> {
69        let mut v = DOMAIN.to_vec();
70        lp(&mut v, self.id.0.as_bytes());
71        lp(&mut v, self.from.as_str().as_bytes());
72        lp(&mut v, self.to.as_str().as_bytes());
73        v.extend_from_slice(&self.sent_ms.to_be_bytes());
74        match &self.body {
75            Body::Text(t) => {
76                v.push(0);
77                lp(&mut v, t.as_bytes());
78            }
79            Body::Invite(i) => {
80                v.push(1);
81                lp(&mut v, i.project.as_bytes());
82                lp(&mut v, i.role.as_bytes());
83                lp(&mut v, i.note.as_bytes());
84                match i.expires_ms {
85                    Some(t) => {
86                        v.push(1);
87                        v.extend_from_slice(&t.to_be_bytes());
88                    }
89                    None => v.push(0),
90                }
91            }
92        }
93        lp(&mut v, &self.key);
94        v
95    }
96
97    /// A message from `kp` to `to`, signed.
98    pub fn sign(kp: &Keypair, to: &UserId, id: MessageId, body: Body, sent_ms: i64) -> Result<Message, String> {
99        let mut m = Message { id, from: UserId::of_keypair(kp), to: to.clone(), sent_ms, body, key: kp.public().encode_protobuf(), sig: Vec::new() };
100        m.sig = kp.sign(&m.signing_bytes()).map_err(|e| e.to_string())?;
101        Ok(m)
102    }
103
104    /// Whether the key is the sender's identity and the signature holds.
105    pub fn verify(&self) -> bool {
106        UserId::of_key_bytes(&self.key).as_ref() == Some(&self.from)
107            && PublicKey::try_decode_protobuf(&self.key).map(|pk| pk.verify(&self.signing_bytes(), &self.sig)).unwrap_or(false)
108    }
109
110    /// Whether the content is within the size limits.
111    pub fn within_limits(&self) -> bool {
112        match &self.body {
113            Body::Text(t) => !t.is_empty() && t.len() <= MAX_TEXT,
114            Body::Invite(i) => i.note.len() <= MAX_NOTE && !i.project.is_empty() && i.project.len() <= 128 && i.role.len() <= 64,
115        }
116    }
117}
118
119/// Where a message is. `Read` is the end of the line; `Failed` can be retried (back to
120/// `Queued`).
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
122pub enum Delivery {
123    /// Written, not yet handed to the other node.
124    Queued,
125    /// The other node was reached but has not confirmed.
126    Sent,
127    /// The other node has it.
128    Delivered,
129    /// The other person has read it.
130    Read,
131    /// The other node refused it or it could not be sent.
132    Failed,
133}
134
135impl Delivery {
136    fn rank(self) -> u8 {
137        match self {
138            Delivery::Queued | Delivery::Failed => 0,
139            Delivery::Sent => 1,
140            Delivery::Delivered => 2,
141            Delivery::Read => 3,
142        }
143    }
144
145    /// The state after moving to `to`: only forward, `Failed` only from `Queued` or `Sent`,
146    /// and out of `Failed` only back to `Queued`, `Sent`, `Delivered` or `Read`.
147    pub fn advance(self, to: Delivery) -> Delivery {
148        match (self, to) {
149            (Delivery::Failed, t) => t,
150            (Delivery::Queued | Delivery::Sent, Delivery::Failed) => Delivery::Failed,
151            (_, Delivery::Failed) => self,
152            (s, t) if t.rank() > s.rank() => t,
153            (s, _) => s,
154        }
155    }
156}
157
158/// A message and where it is.
159#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
160pub struct Entry {
161    /// The message.
162    pub msg: Message,
163    /// Its delivery state (for a received message, `Delivered`, then `Read`).
164    pub delivery: Delivery,
165}
166
167/// Everything said between you and one identity, in order, without repeats.
168#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
169pub struct Conversation {
170    /// The other identity.
171    pub with: UserId,
172    /// True while the other identity is unknown and wrote first: a message request.
173    pub request: bool,
174    entries: Vec<Entry>,
175}
176
177impl Conversation {
178    /// An empty conversation.
179    pub fn new(with: UserId) -> Self {
180        Conversation { with, request: false, entries: Vec::new() }
181    }
182
183    /// The messages, oldest first (ties by id).
184    pub fn entries(&self) -> &[Entry] {
185        &self.entries
186    }
187
188    /// The entry for `id`.
189    pub fn get(&self, id: &MessageId) -> Option<&Entry> {
190        self.entries.iter().find(|e| &e.msg.id == id)
191    }
192
193    /// Add a message; false if it was already there (the delivery state may still advance).
194    pub fn insert(&mut self, msg: Message, delivery: Delivery) -> bool {
195        if let Some(e) = self.entries.iter_mut().find(|e| e.msg.id == msg.id) {
196            e.delivery = e.delivery.advance(delivery);
197            return false;
198        }
199        let at = self.entries.partition_point(|e| (e.msg.sent_ms, &e.msg.id) < (msg.sent_ms, &msg.id));
200        self.entries.insert(at, Entry { msg, delivery });
201        true
202    }
203
204    /// Move a message's delivery state forward.
205    pub fn advance(&mut self, id: &MessageId, to: Delivery) -> bool {
206        match self.entries.iter_mut().find(|e| &e.msg.id == id) {
207            Some(e) => {
208                e.delivery = e.delivery.advance(to);
209                true
210            }
211            None => false,
212        }
213    }
214
215    /// Fold in another copy (your other device's, or the same conversation after a pull):
216    /// new messages are added after their signature is checked, delivery states move forward.
217    /// Returns how many messages were new.
218    pub fn merge(&mut self, other: &Conversation) -> usize {
219        let mut added = 0;
220        for e in &other.entries {
221            if e.msg.verify() && self.insert(e.msg.clone(), e.delivery) {
222                added += 1;
223            }
224        }
225        self.request &= other.request;
226        added
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    fn kp() -> Keypair {
235        Keypair::generate_ed25519()
236    }
237
238    fn text(from: &Keypair, to: &UserId, id: &str, t: i64, s: &str) -> Message {
239        Message::sign(from, to, MessageId(id.into()), Body::Text(s.into()), t).unwrap()
240    }
241
242    #[test]
243    fn signatures_hold_and_tampering_fails() {
244        let (a, b) = (kp(), kp());
245        let to = UserId::of_keypair(&b);
246        let m = text(&a, &to, "a-1", 10, "hello");
247        assert!(m.verify() && m.within_limits());
248        for tamper in [
249            |m: &mut Message| m.body = Body::Text("hullo".into()),
250            |m: &mut Message| m.sent_ms += 1,
251            |m: &mut Message| m.id = MessageId("a-2".into()),
252            |m: &mut Message| m.to = UserId::of_keypair(&Keypair::generate_ed25519()),
253        ] {
254            let mut t = m.clone();
255            tamper(&mut t);
256            assert!(!t.verify());
257        }
258        let mut forged = m.clone();
259        forged.from = UserId::of_keypair(&kp());
260        assert!(!forged.verify(), "the key must be the sender's identity");
261    }
262
263    #[test]
264    fn invites_sign_too_and_limits_apply() {
265        let (a, b) = (kp(), kp());
266        let to = UserId::of_keypair(&b);
267        let inv = DirectInvite { project: "p1".into(), role: "editor".into(), note: "join".into(), expires_ms: Some(99) };
268        let m = Message::sign(&a, &to, MessageId("a-1".into()), Body::Invite(inv.clone()), 5).unwrap();
269        assert!(m.verify() && m.within_limits());
270        let mut other = m.clone();
271        other.body = Body::Invite(DirectInvite { role: "owner".into(), ..inv });
272        assert!(!other.verify(), "the role is signed");
273        assert!(!text(&a, &to, "a-2", 1, "").within_limits());
274        assert!(!text(&a, &to, "a-3", 1, &"x".repeat(MAX_TEXT + 1)).within_limits());
275    }
276
277    #[test]
278    fn delivery_only_moves_forward_and_failed_can_retry() {
279        use Delivery::*;
280        assert_eq!(Queued.advance(Sent), Sent);
281        assert_eq!(Delivered.advance(Sent), Delivered);
282        assert_eq!(Read.advance(Delivered), Read);
283        assert_eq!(Sent.advance(Failed), Failed);
284        assert_eq!(Delivered.advance(Failed), Delivered);
285        assert_eq!(Failed.advance(Queued), Queued);
286        assert_eq!(Failed.advance(Delivered), Delivered);
287    }
288
289    #[test]
290    fn conversations_order_dedupe_and_merge() {
291        let (a, b) = (kp(), kp());
292        let (ua, ub) = (UserId::of_keypair(&a), UserId::of_keypair(&b));
293        let m1 = text(&a, &ub, "a-1", 10, "one");
294        let m2 = text(&b, &ua, "b-1", 20, "two");
295        let m3 = text(&a, &ub, "a-2", 30, "three");
296        let mut mine = Conversation::new(ub.clone());
297        assert!(mine.insert(m3.clone(), Delivery::Queued));
298        assert!(mine.insert(m1.clone(), Delivery::Sent));
299        assert!(!mine.insert(m1.clone(), Delivery::Delivered), "a repeat is not new, but delivery advances");
300        assert_eq!(mine.get(&m1.id).unwrap().delivery, Delivery::Delivered);
301        let mut theirs = Conversation::new(ua.clone());
302        theirs.insert(m1.clone(), Delivery::Read);
303        theirs.insert(m2.clone(), Delivery::Delivered);
304        let added = mine.merge(&theirs);
305        assert_eq!(added, 1);
306        let ids: Vec<_> = mine.entries().iter().map(|e| e.msg.id.0.as_str()).collect();
307        assert_eq!(ids, ["a-1", "b-1", "a-2"]);
308        assert_eq!(mine.get(&m1.id).unwrap().delivery, Delivery::Read);
309        assert_eq!(mine.merge(&theirs), 0, "merging twice adds nothing");
310        let mut bad = m2.clone();
311        bad.id = MessageId("b-9".into());
312        let mut evil = Conversation::new(ua);
313        evil.insert(bad, Delivery::Delivered);
314        assert_eq!(mine.merge(&evil), 0, "an unsigned-for message is not merged");
315    }
316}