weirdnet-collab 0.3.0

Collaboration control for Weirdnet apps: project members and roles, signed allow and deny rules, owner consent grants, a decision with a reason chain, invites and a signed, mergeable audit log. App-agnostic: the app defines what a project, role and permission are.
Documentation
//! A project's text chat: signed messages, reactions and mentions, kept by the host.
//!
//! The app names the three permissions ([`ChatPerms`]): read, write, and manage (delete anyone's
//! message). Every call checks them against the [`Project`] at that moment, so a role change, an
//! override or a ban applies to the next message. Muting someone is a member rule that denies
//! `write`. The log keeps all history; a deleted message keeps its place with its text removed.
//! Each change gets a new sequence number, so a client asks for what changed since the last one
//! it saw.
use crate::enc::{Enc, signed_by};
use crate::ids::{Permission, ProjectId, RecordId};
use crate::project::{Ctx, Project};
use crate::records::SignError;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;

/// The longest message, in bytes.
pub const MAX_TEXT: usize = 4000;
/// The longest reaction, in bytes (one emoji or a short word).
pub const MAX_REACTION: usize = 16;
/// Most different reactions on one message.
pub const MAX_REACTIONS: usize = 24;

/// Which permissions govern chat.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChatPerms {
    /// Read the chat.
    pub read: Permission,
    /// Post and react.
    pub write: Permission,
    /// Delete anyone's message.
    pub manage: Permission,
}

/// Why a chat call was refused.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum ChatError {
    /// The caller lacks the permission.
    #[error("not allowed")]
    NotAllowed,
    /// The signature does not hold.
    #[error("bad signature")]
    BadSignature,
    /// The message is for another project.
    #[error("wrong project")]
    WrongProject,
    /// The message was signed by someone other than the caller.
    #[error("not your message")]
    NotYours,
    /// Empty, or too long.
    #[error("the text is empty or too long")]
    BadText,
    /// A message with that id is already there.
    #[error("duplicate message")]
    Duplicate,
    /// No such message.
    #[error("no such message")]
    NoSuchMessage,
    /// It mentions someone who is not a member.
    #[error("mentions someone who is not in the project")]
    UnknownMention,
}

/// One signed chat message.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatMessage {
    /// Unique id, chosen by the author.
    pub id: RecordId,
    /// The project.
    pub project: ProjectId,
    /// Who wrote it.
    pub author: UserId,
    /// The text.
    pub text: String,
    /// Who it mentions.
    pub mentions: Vec<UserId>,
    /// When it was written, by the author's clock.
    pub at_ms: i64,
    /// The author's public key, protobuf-encoded.
    pub key: Vec<u8>,
    /// The author's signature.
    pub sig: Vec<u8>,
}

impl ChatMessage {
    fn bytes(&self) -> Vec<u8> {
        let e = Enc::new("chat").s(self.id.as_str()).s(self.project.as_str()).s(self.author.as_str()).s(&self.text);
        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()
    }

    /// Write and sign a message as `author`, with a 128-bit random id.
    pub fn sign(author: &Keypair, project: &ProjectId, text: &str, mentions: Vec<UserId>, now: i64) -> Result<ChatMessage, SignError> {
        let mut b = [0u8; 16];
        getrandom::fill(&mut b).map_err(|e| SignError(e.to_string()))?;
        let id: String = std::iter::once('m').chain(b.iter().flat_map(|x| format!("{x:02x}").chars().collect::<Vec<_>>())).collect();
        let mut m = ChatMessage {
            id: RecordId::new(&id),
            project: project.clone(),
            author: UserId::of_keypair(author),
            text: text.to_string(),
            mentions,
            at_ms: now,
            key: author.public().encode_protobuf(),
            sig: Vec::new(),
        };
        m.sig = author.sign(&m.bytes()).map_err(|e| SignError(e.to_string()))?;
        Ok(m)
    }

    /// Whether the author signed it.
    pub fn verify(&self) -> bool {
        signed_by(&self.author, &self.key, &self.bytes(), &self.sig)
    }
}

/// A message as the log keeps it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatItem {
    /// The message. After a deletion its text and mentions are empty and it no longer verifies.
    pub message: ChatMessage,
    /// Reactions: each reaction and who gave it.
    pub reactions: BTreeMap<String, BTreeSet<UserId>>,
    /// Who deleted it, and when.
    pub deleted: Option<(UserId, i64)>,
    /// When the host took it in, by the host's clock.
    pub posted_ms: i64,
    /// The sequence number of its last change.
    pub seq: u64,
}

impl ChatItem {
    /// Whether it mentions `user` (and is not deleted).
    pub fn mentions(&self, user: &UserId) -> bool {
        self.deleted.is_none() && self.message.mentions.contains(user)
    }
}

/// A project's chat, kept by the host.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatLog {
    items: Vec<ChatItem>,
    seq: u64,
}

impl ChatLog {
    fn may(p: &Project, who: &UserId, perm: &Permission, now: i64) -> Result<(), ChatError> {
        if p.can(who, perm.as_str(), &Ctx::at(now)) { Ok(()) } else { Err(ChatError::NotAllowed) }
    }

    fn bump(&mut self) -> u64 {
        self.seq += 1;
        self.seq
    }

    /// The latest sequence number.
    pub fn seq(&self) -> u64 {
        self.seq
    }

    /// Take in a message `from` posted. It must be theirs, signed, for this project, and they
    /// must have `write` now, and everyone it mentions must be a member. Returns its
    /// sequence number.
    pub fn post(&mut self, p: &Project, perms: &ChatPerms, from: &UserId, m: ChatMessage, now: i64) -> Result<u64, ChatError> {
        if &m.author != from {
            return Err(ChatError::NotYours);
        }
        if &m.project != p.id() {
            return Err(ChatError::WrongProject);
        }
        if !m.verify() {
            return Err(ChatError::BadSignature);
        }
        Self::may(p, from, &perms.write, now)?;
        if m.text.trim().is_empty() || m.text.len() > MAX_TEXT {
            return Err(ChatError::BadText);
        }
        if self.items.iter().any(|i| i.message.id == m.id) {
            return Err(ChatError::Duplicate);
        }
        if m.mentions.iter().any(|u| p.member(u).is_none()) {
            return Err(ChatError::UnknownMention);
        }
        let seq = self.bump();
        self.items.push(ChatItem { message: m, reactions: BTreeMap::new(), deleted: None, posted_ms: now, seq });
        Ok(seq)
    }

    fn item_mut(&mut self, id: &RecordId) -> Result<&mut ChatItem, ChatError> {
        self.items.iter_mut().find(|i| &i.message.id == id && i.deleted.is_none()).ok_or(ChatError::NoSuchMessage)
    }

    /// `who` adds (`on`) or takes back a reaction. Needs `write`.
    #[allow(clippy::too_many_arguments)]
    pub fn react(
        &mut self,
        p: &Project,
        perms: &ChatPerms,
        who: &UserId,
        id: &RecordId,
        reaction: &str,
        on: bool,
        now: i64,
    ) -> Result<u64, ChatError> {
        Self::may(p, who, &perms.write, now)?;
        if reaction.is_empty() || reaction.len() > MAX_REACTION || reaction.chars().any(char::is_whitespace) {
            return Err(ChatError::BadText);
        }
        let item = self.item_mut(id)?;
        if on && !item.reactions.contains_key(reaction) && item.reactions.len() >= MAX_REACTIONS {
            return Err(ChatError::BadText);
        }
        let changed = if on {
            item.reactions.entry(reaction.to_string()).or_default().insert(who.clone())
        } else {
            let r = item.reactions.get_mut(reaction).is_some_and(|s| s.remove(who));
            item.reactions.retain(|_, s| !s.is_empty());
            r
        };
        if !changed {
            return Ok(self.seq);
        }
        let seq = self.bump();
        self.item_mut(id)?.seq = seq;
        Ok(seq)
    }

    /// Delete a message: its author may (with `write`), and so may anyone with `manage`.
    pub fn delete(&mut self, p: &Project, perms: &ChatPerms, who: &UserId, id: &RecordId, now: i64) -> Result<u64, ChatError> {
        let author = self.item_mut(id)?.message.author.clone();
        if &author == who {
            Self::may(p, who, &perms.write, now).or_else(|_| Self::may(p, who, &perms.manage, now))?;
        } else {
            Self::may(p, who, &perms.manage, now)?;
        }
        let seq = self.bump();
        let item = self.item_mut(id)?;
        item.message.text.clear();
        item.message.mentions.clear();
        item.reactions.clear();
        item.deleted = Some((who.clone(), now));
        item.seq = seq;
        Ok(seq)
    }

    /// What changed after `since`, oldest first, if `who` may read. Pass 0 for all history.
    pub fn since(&self, p: &Project, perms: &ChatPerms, who: &UserId, since: u64, now: i64) -> Result<Vec<ChatItem>, ChatError> {
        Self::may(p, who, &perms.read, now)?;
        let mut v: Vec<ChatItem> = self.items.iter().filter(|i| i.seq > since).cloned().collect();
        v.sort_by_key(|i| i.seq);
        Ok(v)
    }

    /// All messages, in the order they were posted.
    pub fn items(&self) -> &[ChatItem] {
        &self.items
    }
}

/// Merge changed items into a client's copy, keyed by message id, kept in posting order.
pub fn merge(into: &mut Vec<ChatItem>, changed: Vec<ChatItem>) {
    for c in changed {
        match into.iter_mut().find(|i| i.message.id == c.message.id) {
            Some(i) => *i = c,
            None => into.push(c),
        }
    }
    into.sort_by(|a, b| a.posted_ms.cmp(&b.posted_ms).then(a.message.id.cmp(&b.message.id)));
}