[client] Reactions and replies: a message is named by its author and seq, a reply carries its reference, a reaction sets or removes, a newer kind is Unsupported

This commit is contained in:
2026-11-21 20:02:51 +01:00
parent 1d7f08927d
commit 9d9d63c02b
9 changed files with 875 additions and 31 deletions
+426 -18
View File
@@ -32,8 +32,8 @@ use sha2::Sha256;
use snapshot::Bytes;
use std::fmt;
use tabellarius_protocol::{
blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, PushEndpoint,
Sha256Hash, Token, MAX_BLOB_BYTES,
blob_hash, Author, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId,
PushEndpoint, Sha256Hash, Token, MAX_BLOB_BYTES,
};
pub use transport::{MemoryTransport, Transport, TransportError};
@@ -43,6 +43,10 @@ pub const CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_
pub const MAX_NAME_CHARS: usize = 64;
/// The longest text message, in bytes; well under a blob's limit once encrypted.
pub const MAX_TEXT_BYTES: usize = 64 * 1024;
/// The longest reaction, in bytes of UTF-8: the longest emoji ZWJ sequences are 28.
pub const MAX_EMOJI_BYTES: usize = 32;
/// The payload kinds this client knows; any other kind that carries a `seq` is `Unsupported`.
const KNOWN_KINDS: [&str; 5] = ["hello", "text", "receipt", "inbox", "reaction"];
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
const WELCOME_POST_LABEL: &[u8] = b"tabellarius v0 welcome mailbox post";
@@ -59,6 +63,9 @@ pub enum ClientError {
TooLong,
/// No such contact, or a contact whose mailbox is not known yet.
UnknownContact,
/// A reply or reaction to a message that does not exist in this conversation, or an emoji
/// that is empty or has a control character.
BadReference,
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
State,
}
@@ -102,16 +109,28 @@ pub enum Event {
name: String,
via: Option<InviteId>,
},
/// A text. `seq` is the author's own count; with the contact's [`Client::contact_author`] it
/// names the message, for replies and reactions. `reply_to` is a message this one answers,
/// checked to exist in this conversation (a reference that does not is left out).
Message {
contact: ContactId,
text: String,
seq: u64,
reply_to: Option<MessageRef>,
},
/// The contact's reaction to a message in this conversation: set (replacing their earlier one)
/// or, with `emoji` `None`, removed.
Reaction {
contact: ContactId,
to: MessageRef,
emoji: Option<String>,
},
/// A message of a kind this client does not know (a newer app's). Show that something arrived
/// that needs an update; its `seq` counts like a text's.
Unsupported { contact: ContactId, seq: u64 },
/// The other side's app has saved our texts up to `upto` (a `seq` from
/// [`Client::sent_seq`]). Only while receipts are on ([`Client::set_receipts`]).
Delivered {
contact: ContactId,
upto: u64,
},
Delivered { contact: ContactId, upto: u64 },
}
/// One operation for the relay, to deliver once the app has saved the snapshot: a blob to post,
@@ -184,6 +203,14 @@ impl fmt::Debug for Ack {
}
}
/// A message in a conversation, named by its author and the author's own `seq` (`PROTOCOL.md` §4).
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MessageRef {
pub author: Author,
pub seq: u64,
}
/// The JSON inside an MLS application message. The relay never sees it.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
@@ -194,8 +221,22 @@ enum Payload {
post_token: Token,
name: String,
},
/// `seq` counts this sender's texts to this contact, from 1.
Text { body: String, seq: u64 },
/// `seq` counts this sender's messages to this contact, from 1. `replyTo`, when there, names
/// the message this one answers; absent, the JSON is a text's from before replies.
#[serde(rename_all = "camelCase")]
Text {
body: String,
seq: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
reply_to: Option<MessageRef>,
},
/// The sender's reaction to a message: `emoji` sets it, absent removes it. No `seq`: not a
/// message, so it is not replied to, reacted to or covered by a receipt.
Reaction {
to: MessageRef,
#[serde(default, skip_serializing_if = "Option::is_none")]
emoji: Option<String>,
},
/// The receiver has saved our texts up to `upto`.
Receipt { upto: u64 },
/// A new post token for the mailbox the receiver already knows (unblock).
@@ -461,14 +502,27 @@ impl<T: Transport> Client<T> {
/// Encrypts text for a contact whose `hello` has arrived. No network: save the snapshot, then
/// [`Client::deliver`] the result.
pub fn compose(&mut self, contact: ContactId, text: &str) -> Result<Outgoing, ClientError> {
self.compose_text(contact, text, None)
}
/// [`Client::compose`], answering `reply_to`: a message in this conversation, ours or theirs,
/// that exists ([`ClientError::BadReference`] otherwise).
pub fn compose_text(
&mut self,
contact: ContactId,
text: &str,
reply_to: Option<MessageRef>,
) -> Result<Outgoing, ClientError> {
if text.len() > MAX_TEXT_BYTES {
return Err(ClientError::TooLong);
}
let c = self
.contacts
.iter_mut()
.find(|c| c.id == contact)
.ok_or(ClientError::UnknownContact)?;
let index = self.index_of(contact)?;
if let Some(r) = &reply_to {
if !self.names_a_message(index, r) {
return Err(ClientError::BadReference);
}
}
let c = &mut self.contacts[index];
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let seq = c.sent_seq + 1;
let blob = Self::seal(
@@ -478,12 +532,91 @@ impl<T: Transport> Client<T> {
&Payload::Text {
body: text.to_string(),
seq,
reply_to,
},
)?;
c.sent_seq = seq;
Ok(Outgoing::post(to, post, blob))
}
/// Our reaction to a message in this conversation: `Some(emoji)` sets it (replacing our
/// earlier one), `None` removes it. No network: save the snapshot, then deliver.
pub fn react(
&mut self,
contact: ContactId,
to: MessageRef,
emoji: Option<&str>,
) -> Result<Outgoing, ClientError> {
if let Some(e) = emoji {
if e.len() > MAX_EMOJI_BYTES {
return Err(ClientError::TooLong);
}
if !emoji_ok(e) {
return Err(ClientError::BadReference);
}
}
let index = self.index_of(contact)?;
if !self.names_a_message(index, &to) {
return Err(ClientError::BadReference);
}
let c = &mut self.contacts[index];
let (out_to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let blob = Self::seal(
&self.provider,
&self.signer,
&mut c.group,
&Payload::Reaction {
to,
emoji: emoji.map(str::to_string),
},
)?;
Ok(Outgoing::post(out_to, post, blob))
}
/// Our author name: the 16 bytes in our credential. With a `seq` it names our messages.
pub fn author(&self) -> Author {
author_of(&self.identity).unwrap_or_else(|| Author::from_bytes([0; 16]))
}
/// The contact's author name, read from the conversation's other MLS member.
pub fn contact_author(&self, contact: ContactId) -> Option<Author> {
let index = self.index_of(contact).ok()?;
self.peer_author(index)
}
fn index_of(&self, contact: ContactId) -> Result<usize, ClientError> {
self.contacts
.iter()
.position(|c| c.id == contact)
.ok_or(ClientError::UnknownContact)
}
fn peer_author(&self, index: usize) -> Option<Author> {
self.contacts[index]
.group
.members()
.filter_map(|m| BasicCredential::try_from(m.credential).ok())
.map(|c| c.identity().to_vec())
.find(|id| id != &self.identity)
.and_then(|id| author_of(&id))
}
/// Whether `r` names a message that exists in this conversation: ours up to our last `seq`,
/// theirs up to the highest `seq` received from them.
fn names_a_message(&self, index: usize, r: &MessageRef) -> bool {
let c = &self.contacts[index];
if r.seq == 0 {
return false;
}
if r.author.as_bytes()[..] == self.identity[..] {
r.seq <= c.sent_seq
} else if self.peer_author(index) == Some(r.author) {
r.seq <= c.received_seq
} else {
false
}
}
/// The `seq` of our last text to a contact: right after [`Client::compose`], the one it made.
pub fn sent_seq(&self, contact: ContactId) -> Option<u64> {
self.contacts
@@ -810,9 +943,10 @@ impl<T: Transport> Client<T> {
else {
return Ok(None);
};
let payload: Payload =
serde_json::from_slice(&app.into_bytes()).map_err(|_| ClientError::Mls)?;
self.receive_payload(index, payload)
match parse_payload(&app.into_bytes())? {
Parsed::Known(payload) => self.receive_payload(index, payload),
Parsed::Unknown { seq } => self.receive_unknown(index, seq),
}
}
_ => Err(ClientError::Mls),
}
@@ -841,8 +975,12 @@ impl<T: Transport> Client<T> {
via: c.via,
}))
}
Payload::Text { body, seq } => {
let c = &mut self.contacts[index];
Payload::Text {
body,
seq,
reply_to,
} => {
let c = &self.contacts[index];
if c.name.is_none() {
// Text before hello: not from a conversation that has been set up.
return Err(ClientError::Mls);
@@ -851,10 +989,33 @@ impl<T: Transport> Client<T> {
// Posted before the block, or fetched after it: dropped, never shown.
return Ok(None);
}
// Checked before this text counts, so a text cannot answer itself. The words are
// real even when the reference is not: the text stays, the reference goes.
let reply_to = reply_to.filter(|r| self.names_a_message(index, r));
let c = &mut self.contacts[index];
c.received_seq = c.received_seq.max(seq);
Ok(Some(Event::Message {
contact: c.id,
text: body,
seq,
reply_to,
}))
}
Payload::Reaction { to, emoji } => {
let c = &self.contacts[index];
if c.name.is_none() {
return Err(ClientError::Mls);
}
let emoji_bad = emoji
.as_deref()
.is_some_and(|e| e.len() > MAX_EMOJI_BYTES || !emoji_ok(e));
if c.blocked || emoji_bad || !self.names_a_message(index, &to) {
return Ok(None);
}
Ok(Some(Event::Reaction {
contact: c.id,
to,
emoji,
}))
}
Payload::Receipt { upto } => {
@@ -881,6 +1042,55 @@ impl<T: Transport> Client<T> {
}
}
impl<T: Transport> Client<T> {
/// A payload of a kind this client does not know, with a `seq`: a newer app's message.
fn receive_unknown(&mut self, index: usize, seq: u64) -> Result<Option<Event>, ClientError> {
let c = &mut self.contacts[index];
if c.name.is_none() {
return Err(ClientError::Mls);
}
if c.blocked {
return Ok(None);
}
c.received_seq = c.received_seq.max(seq);
Ok(Some(Event::Unsupported { contact: c.id, seq }))
}
}
enum Parsed {
Known(Payload),
Unknown { seq: u64 },
}
/// A payload of a known kind must parse exactly (`deny_unknown_fields`); one of an unknown kind is
/// `Unknown` when it carries a `seq` of at least 1, and refused otherwise.
fn parse_payload(bytes: &[u8]) -> Result<Parsed, ClientError> {
let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| ClientError::Mls)?;
let kind = value
.get("kind")
.and_then(serde_json::Value::as_str)
.ok_or(ClientError::Mls)?;
if KNOWN_KINDS.contains(&kind) {
return serde_json::from_value(value)
.map(Parsed::Known)
.map_err(|_| ClientError::Mls);
}
match value.get("seq").and_then(serde_json::Value::as_u64) {
Some(seq) if seq >= 1 => Ok(Parsed::Unknown { seq }),
_ => Err(ClientError::Mls),
}
}
/// An emoji as the wire allows it: not empty, no control characters (the length is checked apart,
/// as [`ClientError::TooLong`]).
fn emoji_ok(emoji: &str) -> bool {
!emoji.is_empty() && !emoji.chars().any(char::is_control)
}
fn author_of(identity: &[u8]) -> Option<Author> {
<[u8; 16]>::try_from(identity).ok().map(Author::from_bytes)
}
fn credential_with_key(identity: &[u8], signer: &SignatureKeyPair) -> CredentialWithKey {
CredentialWithKey {
credential: BasicCredential::new(identity.to_vec()).into(),
@@ -955,4 +1165,202 @@ mod tests {
}))
);
}
// Reactions and replies (`.agents/features/reactions-replies.md` §2.2).
fn paired() -> (Client<MemoryTransport>, Client<MemoryTransport>) {
let relay = MemoryTransport::default();
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
eva.set_receipts(false);
jan.set_receipts(false);
let invite = eva.create_invite().expect("invite");
jan.accept_invite(&invite).expect("accept");
eva.poll().expect("poll");
jan.poll().expect("poll");
(eva, jan)
}
/// Seals any JSON for the first contact, as a newer or misbehaving client could.
fn seal_raw(c: &mut Client<MemoryTransport>, json: &str) -> Outgoing {
let contact = &mut c.contacts[0];
let (to, post) = contact.outbox.expect("outbox");
let blob = contact
.group
.create_message(&c.provider, &c.signer, json.as_bytes())
.expect("seal")
.tls_serialize_detached()
.expect("bytes");
Outgoing::post(to, post, blob)
}
#[test]
fn a_text_without_a_reply_is_the_old_json_and_a_removal_has_no_emoji_key() {
let text = Payload::Text {
body: "x".into(),
seq: 1,
reply_to: None,
};
assert_eq!(
serde_json::to_string(&text).expect("json"),
r#"{"kind":"text","body":"x","seq":1}"#
);
let to = MessageRef {
author: Author::from_bytes([0; 16]),
seq: 3,
};
let removal = Payload::Reaction { to, emoji: None };
assert_eq!(
serde_json::to_string(&removal).expect("json"),
r#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":3}}"#
);
let reply = Payload::Text {
body: "y".into(),
seq: 2,
reply_to: Some(to),
};
assert!(serde_json::to_string(&reply)
.expect("json")
.contains(r#""replyTo":{"author":"#));
}
#[test]
fn an_unknown_kind_needs_a_seq_and_a_known_kind_must_parse_exactly() {
assert!(matches!(
parse_payload(br#"{"kind":"poll","seq":4,"question":"?"}"#),
Ok(Parsed::Unknown { seq: 4 })
));
for bad in [
&br#"{"kind":"poll","question":"?"}"#[..],
br#"{"kind":"poll","seq":0}"#,
br#"{"kind":"poll","seq":-1}"#,
br#"{"kind":"poll","seq":"4"}"#,
br#"{"seq":4}"#,
br#"{"kind":"text","body":"x","seq":1,"mentions":[]}"#,
br#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"emoji":"x","extra":1}"#,
br#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1,"x":1}}"#,
b"not json",
] {
assert!(
parse_payload(bad).is_err(),
"{}",
String::from_utf8_lossy(bad)
);
}
}
#[test]
fn a_reaction_that_names_no_message_here_or_carries_a_bad_emoji_is_dropped() {
let (mut eva, mut jan) = paired();
eva.send(eva.contacts[0].id, "jedna").expect("send");
jan.poll().expect("poll");
let first = MessageRef {
author: eva.author(),
seq: 1,
};
let stranger = Author::from_bytes([7; 16]);
let reaction = |to: MessageRef, emoji: Option<&str>| Payload::Reaction {
to,
emoji: emoji.map(str::to_string),
};
let long = "😀".repeat(9);
for payload in [
reaction(MessageRef { seq: 2, ..first }, Some("👍")),
reaction(MessageRef { seq: 0, ..first }, Some("👍")),
reaction(
MessageRef {
author: stranger,
seq: 1,
},
Some("👍"),
),
// Eva's view: a reaction from Jan to Jan's message 1, which never came.
reaction(
MessageRef {
author: jan.author(),
seq: 1,
},
Some("👍"),
),
reaction(first, Some("")),
reaction(first, Some("a\u{0}")),
reaction(first, Some(&long)),
] {
assert_eq!(eva.receive_payload(0, payload), Ok(None));
}
assert!(matches!(
eva.receive_payload(0, reaction(first, Some("👍"))),
Ok(Some(Event::Reaction { .. }))
));
}
#[test]
fn a_text_whose_reference_names_nothing_here_is_shown_without_it() {
let (mut eva, _jan) = paired();
let text = |seq, reply_to| Payload::Text {
body: "words".into(),
seq,
reply_to,
};
// Their first text answering their own first text: itself.
let itself = MessageRef {
author: eva.peer_author(0).expect("author"),
seq: 1,
};
let got = eva.receive_payload(0, text(1, Some(itself)));
assert!(
matches!(
&got,
Ok(Some(Event::Message {
reply_to: None,
seq: 1,
..
}))
),
"{got:?}"
);
// Now it exists: their second text may answer it.
let got = eva.receive_payload(0, text(2, Some(itself)));
assert!(
matches!(
&got,
Ok(Some(Event::Message {
reply_to: Some(_),
..
}))
),
"{got:?}"
);
let ours = MessageRef {
author: eva.author(),
seq: 1,
};
let got = eva.receive_payload(0, text(3, Some(ours)));
assert!(
matches!(&got, Ok(Some(Event::Message { reply_to: None, text, .. })) if text == "words"),
"we sent nothing yet: {got:?}"
);
}
#[test]
fn a_newer_apps_message_is_unsupported_and_counts_for_receipts() {
let (mut eva, mut jan) = paired();
eva.set_receipts(true);
let out = seal_raw(&mut jan, r#"{"kind":"poll","seq":1,"question":"Pivo?"}"#);
jan.deliver(&out).expect("deliver");
let out = seal_raw(&mut jan, r#"{"kind":"poll","question":"no seq"}"#);
jan.deliver(&out).expect("deliver");
let got = eva.receive().expect("receive");
assert_eq!(
got.events,
vec![Event::Unsupported {
contact: eva.contacts[0].id,
seq: 1
}]
);
assert_eq!(eva.contacts[0].received_seq, 1);
assert_eq!(got.outgoing.len(), 1, "a receipt for it");
// From a blocked contact: dropped.
eva.contacts[0].blocked = true;
assert_eq!(eva.receive_unknown(0, 2), Ok(None));
}
}