weirdnet-contacts 0.1.0

A contact book for Weirdnet apps: trusted and blocked identities, presence with privacy rules (base to everyone, detail to trusted contacts), signed text direct messages with delivery state and an offline queue, and contact links, served over weirdnet-service.
Documentation
//! Signed direct messages, their delivery state, and conversations that merge.
use crate::id::UserId;
use serde::{Deserialize, Serialize};
use weirdnet_net::{Keypair, PublicKey};

/// The longest text body, in bytes.
pub const MAX_TEXT: usize = 4000;
/// The longest invite note, in bytes.
pub const MAX_NOTE: usize = 200;

const DOMAIN: &[u8] = b"weirdnet-contacts/msg/1\0";

/// A message id: unique per sender (`<sender suffix>-<time>-<counter>`).
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct MessageId(pub String);

/// An invitation to a collaboration, as a card in a conversation. The app decides what a
/// project and a role are.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectInvite {
    /// The project's id.
    pub project: String,
    /// The offered role.
    pub role: String,
    /// A note from the sender.
    pub note: String,
    /// When the invite stops being valid, milliseconds since the epoch.
    pub expires_ms: Option<i64>,
}

/// What a message says. Text and invite cards only: no voice, no attachments.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Body {
    /// Text.
    Text(String),
    /// An invite card.
    Invite(DirectInvite),
}

fn lp(out: &mut Vec<u8>, b: &[u8]) {
    out.extend_from_slice(&(b.len() as u32).to_be_bytes());
    out.extend_from_slice(b);
}

/// A signed message.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Message {
    /// Unique per sender.
    pub id: MessageId,
    /// The sender.
    pub from: UserId,
    /// The recipient.
    pub to: UserId,
    /// When it was written, milliseconds since the epoch.
    pub sent_ms: i64,
    /// The content.
    pub body: Body,
    /// The sender's public key, protobuf-encoded; `from` must be its identity.
    pub key: Vec<u8>,
    /// The sender's signature over [`Message::signing_bytes`].
    pub sig: Vec<u8>,
}

impl Message {
    /// The signed bytes: a domain tag, then the fields in a fixed order with 32-bit
    /// big-endian lengths. The signature does not depend on the wire codec.
    pub fn signing_bytes(&self) -> Vec<u8> {
        let mut v = DOMAIN.to_vec();
        lp(&mut v, self.id.0.as_bytes());
        lp(&mut v, self.from.as_str().as_bytes());
        lp(&mut v, self.to.as_str().as_bytes());
        v.extend_from_slice(&self.sent_ms.to_be_bytes());
        match &self.body {
            Body::Text(t) => {
                v.push(0);
                lp(&mut v, t.as_bytes());
            }
            Body::Invite(i) => {
                v.push(1);
                lp(&mut v, i.project.as_bytes());
                lp(&mut v, i.role.as_bytes());
                lp(&mut v, i.note.as_bytes());
                match i.expires_ms {
                    Some(t) => {
                        v.push(1);
                        v.extend_from_slice(&t.to_be_bytes());
                    }
                    None => v.push(0),
                }
            }
        }
        lp(&mut v, &self.key);
        v
    }

    /// A message from `kp` to `to`, signed.
    pub fn sign(kp: &Keypair, to: &UserId, id: MessageId, body: Body, sent_ms: i64) -> Result<Message, String> {
        let mut m = Message { id, from: UserId::of_keypair(kp), to: to.clone(), sent_ms, body, key: kp.public().encode_protobuf(), sig: Vec::new() };
        m.sig = kp.sign(&m.signing_bytes()).map_err(|e| e.to_string())?;
        Ok(m)
    }

    /// Whether the key is the sender's identity and the signature holds.
    pub fn verify(&self) -> bool {
        UserId::of_key_bytes(&self.key).as_ref() == Some(&self.from)
            && PublicKey::try_decode_protobuf(&self.key).map(|pk| pk.verify(&self.signing_bytes(), &self.sig)).unwrap_or(false)
    }

    /// Whether the content is within the size limits.
    pub fn within_limits(&self) -> bool {
        match &self.body {
            Body::Text(t) => !t.is_empty() && t.len() <= MAX_TEXT,
            Body::Invite(i) => i.note.len() <= MAX_NOTE && !i.project.is_empty() && i.project.len() <= 128 && i.role.len() <= 64,
        }
    }
}

/// Where a message is. `Read` is the end of the line; `Failed` can be retried (back to
/// `Queued`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Delivery {
    /// Written, not yet handed to the other node.
    Queued,
    /// The other node was reached but has not confirmed.
    Sent,
    /// The other node has it.
    Delivered,
    /// The other person has read it.
    Read,
    /// The other node refused it or it could not be sent.
    Failed,
}

impl Delivery {
    fn rank(self) -> u8 {
        match self {
            Delivery::Queued | Delivery::Failed => 0,
            Delivery::Sent => 1,
            Delivery::Delivered => 2,
            Delivery::Read => 3,
        }
    }

    /// The state after moving to `to`: only forward, `Failed` only from `Queued` or `Sent`,
    /// and out of `Failed` only back to `Queued`, `Sent`, `Delivered` or `Read`.
    pub fn advance(self, to: Delivery) -> Delivery {
        match (self, to) {
            (Delivery::Failed, t) => t,
            (Delivery::Queued | Delivery::Sent, Delivery::Failed) => Delivery::Failed,
            (_, Delivery::Failed) => self,
            (s, t) if t.rank() > s.rank() => t,
            (s, _) => s,
        }
    }
}

/// A message and where it is.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
    /// The message.
    pub msg: Message,
    /// Its delivery state (for a received message, `Delivered`, then `Read`).
    pub delivery: Delivery,
}

/// Everything said between you and one identity, in order, without repeats.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Conversation {
    /// The other identity.
    pub with: UserId,
    /// True while the other identity is unknown and wrote first: a message request.
    pub request: bool,
    entries: Vec<Entry>,
}

impl Conversation {
    /// An empty conversation.
    pub fn new(with: UserId) -> Self {
        Conversation { with, request: false, entries: Vec::new() }
    }

    /// The messages, oldest first (ties by id).
    pub fn entries(&self) -> &[Entry] {
        &self.entries
    }

    /// The entry for `id`.
    pub fn get(&self, id: &MessageId) -> Option<&Entry> {
        self.entries.iter().find(|e| &e.msg.id == id)
    }

    /// Add a message; false if it was already there (the delivery state may still advance).
    pub fn insert(&mut self, msg: Message, delivery: Delivery) -> bool {
        if let Some(e) = self.entries.iter_mut().find(|e| e.msg.id == msg.id) {
            e.delivery = e.delivery.advance(delivery);
            return false;
        }
        let at = self.entries.partition_point(|e| (e.msg.sent_ms, &e.msg.id) < (msg.sent_ms, &msg.id));
        self.entries.insert(at, Entry { msg, delivery });
        true
    }

    /// Move a message's delivery state forward.
    pub fn advance(&mut self, id: &MessageId, to: Delivery) -> bool {
        match self.entries.iter_mut().find(|e| &e.msg.id == id) {
            Some(e) => {
                e.delivery = e.delivery.advance(to);
                true
            }
            None => false,
        }
    }

    /// Fold in another copy (your other device's, or the same conversation after a pull):
    /// new messages are added after their signature is checked, delivery states move forward.
    /// Returns how many messages were new.
    pub fn merge(&mut self, other: &Conversation) -> usize {
        let mut added = 0;
        for e in &other.entries {
            if e.msg.verify() && self.insert(e.msg.clone(), e.delivery) {
                added += 1;
            }
        }
        self.request &= other.request;
        added
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn kp() -> Keypair {
        Keypair::generate_ed25519()
    }

    fn text(from: &Keypair, to: &UserId, id: &str, t: i64, s: &str) -> Message {
        Message::sign(from, to, MessageId(id.into()), Body::Text(s.into()), t).unwrap()
    }

    #[test]
    fn signatures_hold_and_tampering_fails() {
        let (a, b) = (kp(), kp());
        let to = UserId::of_keypair(&b);
        let m = text(&a, &to, "a-1", 10, "hello");
        assert!(m.verify() && m.within_limits());
        for tamper in [
            |m: &mut Message| m.body = Body::Text("hullo".into()),
            |m: &mut Message| m.sent_ms += 1,
            |m: &mut Message| m.id = MessageId("a-2".into()),
            |m: &mut Message| m.to = UserId::of_keypair(&Keypair::generate_ed25519()),
        ] {
            let mut t = m.clone();
            tamper(&mut t);
            assert!(!t.verify());
        }
        let mut forged = m.clone();
        forged.from = UserId::of_keypair(&kp());
        assert!(!forged.verify(), "the key must be the sender's identity");
    }

    #[test]
    fn invites_sign_too_and_limits_apply() {
        let (a, b) = (kp(), kp());
        let to = UserId::of_keypair(&b);
        let inv = DirectInvite { project: "p1".into(), role: "editor".into(), note: "join".into(), expires_ms: Some(99) };
        let m = Message::sign(&a, &to, MessageId("a-1".into()), Body::Invite(inv.clone()), 5).unwrap();
        assert!(m.verify() && m.within_limits());
        let mut other = m.clone();
        other.body = Body::Invite(DirectInvite { role: "owner".into(), ..inv });
        assert!(!other.verify(), "the role is signed");
        assert!(!text(&a, &to, "a-2", 1, "").within_limits());
        assert!(!text(&a, &to, "a-3", 1, &"x".repeat(MAX_TEXT + 1)).within_limits());
    }

    #[test]
    fn delivery_only_moves_forward_and_failed_can_retry() {
        use Delivery::*;
        assert_eq!(Queued.advance(Sent), Sent);
        assert_eq!(Delivered.advance(Sent), Delivered);
        assert_eq!(Read.advance(Delivered), Read);
        assert_eq!(Sent.advance(Failed), Failed);
        assert_eq!(Delivered.advance(Failed), Delivered);
        assert_eq!(Failed.advance(Queued), Queued);
        assert_eq!(Failed.advance(Delivered), Delivered);
    }

    #[test]
    fn conversations_order_dedupe_and_merge() {
        let (a, b) = (kp(), kp());
        let (ua, ub) = (UserId::of_keypair(&a), UserId::of_keypair(&b));
        let m1 = text(&a, &ub, "a-1", 10, "one");
        let m2 = text(&b, &ua, "b-1", 20, "two");
        let m3 = text(&a, &ub, "a-2", 30, "three");
        let mut mine = Conversation::new(ub.clone());
        assert!(mine.insert(m3.clone(), Delivery::Queued));
        assert!(mine.insert(m1.clone(), Delivery::Sent));
        assert!(!mine.insert(m1.clone(), Delivery::Delivered), "a repeat is not new, but delivery advances");
        assert_eq!(mine.get(&m1.id).unwrap().delivery, Delivery::Delivered);
        let mut theirs = Conversation::new(ua.clone());
        theirs.insert(m1.clone(), Delivery::Read);
        theirs.insert(m2.clone(), Delivery::Delivered);
        let added = mine.merge(&theirs);
        assert_eq!(added, 1);
        let ids: Vec<_> = mine.entries().iter().map(|e| e.msg.id.0.as_str()).collect();
        assert_eq!(ids, ["a-1", "b-1", "a-2"]);
        assert_eq!(mine.get(&m1.id).unwrap().delivery, Delivery::Read);
        assert_eq!(mine.merge(&theirs), 0, "merging twice adds nothing");
        let mut bad = m2.clone();
        bad.id = MessageId("b-9".into());
        let mut evil = Conversation::new(ua);
        evil.insert(bad, Delivery::Delivered);
        assert_eq!(mine.merge(&evil), 0, "an unsigned-for message is not merged");
    }
}