Compare commits

...

3 Commits

9 changed files with 911 additions and 31 deletions
+122
View File
@@ -0,0 +1,122 @@
# Reactions and replies — two payloads, and messages that can be named (`PROTOCOL.md` §4)
Amicitia F27, step 2 of its full-chat plan (`Amicitia/.agents/features/full-chat.md` §2). Everything
here is **inside MLS**: the relay's view (§5, §8) does not change. No new route, no new column.
## 1. Why and what
A chat people move to needs the two smallest things every messenger has: a **reaction** on a message
(👍, ❤️, 😂 …) and a **reply** that quotes the message it answers. Both need a message to have a name
both sides agree on. Today a `text` carries a `seq`, but the receiving app is never told it, and
nothing says *whose* `seq`.
So this change:
1. names every message by **(author, seq)**: the author's 16-byte MLS credential identity (random,
made on the device, already in every credential, never a name) and the author's own `seq`;
2. adds `replyTo` to `text`, and a new payload `reaction`;
3. tells the app a received message's `seq`, and both identities, so it can store and name messages;
4. turns a payload of a **kind this client does not know** that carries a `seq` into an event
*Unsupported*, so a later kind (polls, files, stickers) shows *Update the app to see this message*
instead of vanishing. Today such a payload fails to parse and is dropped without a trace.
## 2. Design
```mermaid
sequenceDiagram
participant A as Anna's app
participant C as Client (Anna)
participant R as Relay
participant D as Client (Ben)
participant B as Ben's app
A->>C: compose_text(ben, "lunch?", None) → seq 7
C->>R: MLS blob {"kind":"text","body":"lunch?","seq":7}
R->>D: fetch
D->>B: Message{seq 7, reply_to: None}; B names it (Anna, 7)
B->>D: react(anna, (Anna, 7), Some("👍"))
D->>R: MLS blob {"kind":"reaction","to":{"author":"…","seq":7},"emoji":"👍"}
R->>C: fetch
C->>A: Reaction{to (Anna, 7), emoji "👍"}
```
### 2.1 The payloads
```json
{"kind":"text","body":"…","seq":8,"replyTo":{"author":"<22 chars>","seq":7}}
{"kind":"reaction","to":{"author":"<22 chars>","seq":7},"emoji":"👍"}
{"kind":"reaction","to":{"author":"<22 chars>","seq":7}}
```
- **`MessageRef`** `{author, seq}`: `author` is unpadded base64url of 16 bytes (the protocol crate's
new `Author`, like `MailboxId`); `seq` ≥ 1.
- **`text.replyTo`** is optional; without it a `text` is byte-for-byte today's.
- **`reaction`**: `emoji` present sets the sender's reaction to that message (replacing their
earlier one); absent removes it. One reaction per person per message is the app's rule, and the
wire makes it the only one expressible: there is no "add a second". `emoji` is 1–32 bytes of UTF-8
with no control characters (the longest emoji ZWJ sequences are 28 bytes). Which emoji are offered
is the app's choice; the client does not keep a list, so a newer app's emoji still arrives.
- A reaction carries **no `seq`**: it is not a message, it cannot be replied to or reacted to, and a
receipt does not cover it.
### 2.2 What the receiving client checks
A reference names a message only if its author is one of the two members of this conversation and
its `seq` is one that exists: ≤ our `sent_seq` when it names ours, ≤ their highest `seq` received
when it names theirs (blobs from one sender arrive in order, so their message is always before a
reaction to it).
| Received | Bad reference | Result |
|:--|:--|:--|
| `reaction` | author not a member, `seq` 0, or a `seq` that does not exist yet | dropped, never shown (like any blob that does not make sense) |
| `reaction` | emoji empty, over 32 bytes, or with a control character | dropped |
| `text` with `replyTo` | as above | the text is shown, **without** the reference: the words are real, only the quote is not |
| unknown `kind` with a `seq` ≥ 1 | — | `Unsupported{seq}`; counts for receipts like a text |
| unknown `kind` without a `seq`, or not JSON | — | dropped, as today |
A blocked contact's reactions and unsupported items are dropped, as their texts are.
### 2.3 The client's API (Amicitia pins it)
- `Event::Message` gains `seq: u64` and `reply_to: Option<MessageRef>`.
- New `Event::Reaction { contact, to: MessageRef, emoji: Option<String> }`.
- New `Event::Unsupported { contact, seq }`.
- `Client::author() -> Author` (ours) and `Client::contact_author(contact) -> Option<Author>` (theirs,
read from the MLS group's other member — nothing new in the snapshot).
- `Client::compose_text(contact, text, reply_to: Option<MessageRef>)`; `compose(contact, text)`
stays and means `compose_text(…, None)`. A reply whose reference fails §2.2's check on our own
side is refused with `ClientError::BadReference` before anything is sealed.
- `Client::react(contact, to: MessageRef, emoji: Option<&str>) -> Outgoing`; the same checks, and
`ClientError::TooLong` / `BadReference` for a bad emoji.
### 2.4 An older client
A client before this change has `deny_unknown_fields` on `text` and no `reaction`: a reply or a
reaction fails to parse there and is dropped (acknowledged, never shown). Nobody runs Amicitia
outside development yet; from this change on, unknown kinds degrade to *Unsupported*. **Unknown
fields in a known kind still fail** (`deny_unknown_fields` stays: a field the receiver ignores could
change what the sender meant). So a later change that adds a field to `text` would make older
clients drop those texts without a trace; new fields therefore go into **new kinds**, which older
clients show as *Unsupported*. `PROTOCOL.md` §4 says so.
## 3. Risks
- **Privacy:** members (the two people) learn the emoji and which message; they already see every
message. The relay sees one more blob. **A reaction's blob is small** (about the size of a
one-word text) — the relay could guess "a reaction or a very short text", which it can already do
for short texts; padding is G41's later work. Stated in §5's note on sizes.
- **Integrity:** a reaction can only come from a member (MLS authenticates the sender), so nobody else
can react in someone's name. A member can react to a message that exists only; they cannot
reference a message from another conversation (different authors).
- **Events (`Amicitia`):** none — reactions are not check-ins (full-chat §4).
- **Offline:** as every payload: staged, posted after the snapshot is saved.
## 4. Gaps and designed solutions
| Gap | Design |
|:--|:--|
| Unknown kinds vanish today | `Unsupported{seq}` (§2.2) |
| A known kind with new fields fails on older clients | New fields go into new kinds (§2.4), written into `PROTOCOL.md` §4 |
| Reaction blobs are small (size leak) | Same as short texts today; padding to buckets is G41's (later) |
| A reaction to a message the receiver deleted | The client cannot know; the app drops reactions to messages it does not have |
## 5. Verification
| Case | Test |
|:--|:--|
| A reply arrives with its reference; the app is told `seq` and both authors match | `client/tests/reactions.rs` |
| A reaction sets, replaces and removes (emoji absent) | same |
| A reaction to a `seq` that does not exist, or by a non-member author, is dropped | unit test through `receive_payload` |
| A reply with a bad reference is shown without the reference | unit test |
| Emoji empty, 33 bytes, or with a control character: refused when composing, dropped when received | unit + integration |
| An unknown kind with a `seq` → `Unsupported`, and a receipt covers it; without `seq` → nothing | unit test |
| A blocked contact's reaction is dropped | integration |
| `compose` unchanged on the wire (no `replyTo` key) | unit test on the JSON |
| The relay's database holds no emoji and no reply text (canary) | `real_relay.rs`, `client/tests/state.rs` |
| `Author` parses only canonical 22-char base64url of 16 bytes | protocol unit + proptest |
| Planted bugs | the review |
+462 -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,238 @@ 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));
}
/// Every kind this client sends is in `KNOWN_KINDS`: a variant left out would arrive as
/// *Unsupported* at a client of the same version.
#[test]
fn every_payload_kind_is_known() {
let to = MessageRef {
author: Author::from_bytes([1; 16]),
seq: 1,
};
let all = [
Payload::Hello {
mailbox: MailboxId::from_bytes([0; 16]),
post_token: Token::from_bytes([0; 32]),
name: "x".into(),
},
Payload::Text {
body: "x".into(),
seq: 1,
reply_to: None,
},
Payload::Receipt { upto: 1 },
Payload::Inbox {
post_token: Token::from_bytes([0; 32]),
},
Payload::Reaction { to, emoji: None },
];
assert_eq!(all.len(), KNOWN_KINDS.len());
for payload in all {
let json = serde_json::to_vec(&payload).expect("json");
assert!(
matches!(parse_payload(&json), Ok(Parsed::Known(p)) if p == payload),
"{}",
String::from_utf8_lossy(&json)
);
}
}
}
+12 -4
View File
@@ -59,11 +59,15 @@ fn two_people_pair_through_an_invite_and_talk_both_ways() {
vec![
Event::Message {
contact: jan_side,
text: "Ahoj Jane, pivo ve čtvrtek?".into()
text: "Ahoj Jane, pivo ve čtvrtek?".into(),
seq: 1,
reply_to: None,
},
Event::Message {
contact: jan_side,
text: "V sedm.".into()
text: "V sedm.".into(),
seq: 2,
reply_to: None,
},
]
);
@@ -72,7 +76,9 @@ fn two_people_pair_through_an_invite_and_talk_both_ways() {
eva.poll().expect("poll"),
vec![Event::Message {
contact: eva_side,
text: "Platí 🍺".into()
text: "Platí 🍺".into(),
seq: 1,
reply_to: None,
}]
);
// Everything delivered was acknowledged: nothing waits on the relay, and a second poll is
@@ -168,7 +174,9 @@ fn junk_in_a_mailbox_is_dropped_and_never_shown() {
eva.poll().expect("poll"),
vec![Event::Message {
contact: eva_side,
text: "still here".into()
text: "still here".into(),
seq: 1,
reply_to: None,
}]
);
}
+239
View File
@@ -0,0 +1,239 @@
//! Reactions and replies (`.agents/features/reactions-replies.md`). No I/O: runs on the Android
//! emulator too.
use tabellarius_client::*;
type C = Client<MemoryTransport>;
fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) {
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
// Receipts have their own tests; here they would only add events.
eva.set_receipts(false);
jan.set_receipts(false);
let invite = eva.create_invite().expect("invite");
let jan_side = jan.accept_invite(&invite).expect("accept");
let Some(Event::Joined {
contact: eva_side, ..
}) = eva.poll().expect("poll").first().cloned()
else {
panic!("no join")
};
jan.poll().expect("poll");
(eva, eva_side, jan, jan_side)
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
}
#[test]
fn both_sides_name_a_message_the_same_way_and_a_reply_carries_its_reference() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
assert_ne!(eva.author(), jan.author());
assert_eq!(jan.contact_author(jan_side), Some(eva.author()));
assert_eq!(eva.contact_author(eva_side), Some(jan.author()));
eva.send(eva_side, "Oběd?").expect("send");
let got = jan.poll().expect("poll");
let [Event::Message { seq, .. }] = got.as_slice() else {
panic!("{got:?}")
};
let lunch = MessageRef {
author: jan.contact_author(jan_side).expect("author"),
seq: *seq,
};
let out = jan
.compose_text(jan_side, "Jasně, ve 12", Some(lunch))
.expect("reply");
jan.deliver(&out).expect("deliver");
assert_eq!(
eva.poll().expect("poll"),
vec![Event::Message {
contact: eva_side,
text: "Jasně, ve 12".into(),
seq: 1,
reply_to: Some(MessageRef {
author: eva.author(),
seq: 1
}),
}]
);
// A reply to one's own message is a reply too.
let own = MessageRef {
author: jan.author(),
seq: 1,
};
let out = jan
.compose_text(jan_side, "Nebo ve 13?", Some(own))
.expect("reply");
jan.deliver(&out).expect("deliver");
let got = eva.poll().expect("poll");
assert!(
matches!(got.as_slice(), [Event::Message { seq: 2, reply_to: Some(r), .. }] if *r == MessageRef { author: jan.author(), seq: 1 }),
"{got:?}"
);
}
#[test]
fn a_reaction_is_set_replaced_and_removed() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
eva.send(eva_side, "Mám novou práci!").expect("send");
jan.poll().expect("poll");
let news = MessageRef {
author: eva.author(),
seq: 1,
};
for emoji in [Some("👍"), Some("🎉"), None] {
let out = jan.react(jan_side, news, emoji).expect("react");
jan.deliver(&out).expect("deliver");
}
assert_eq!(
eva.poll().expect("poll"),
vec![
Event::Reaction {
contact: eva_side,
to: news,
emoji: Some("👍".into())
},
Event::Reaction {
contact: eva_side,
to: news,
emoji: Some("🎉".into())
},
Event::Reaction {
contact: eva_side,
to: news,
emoji: None
},
]
);
// A family ZWJ sequence (25 bytes) is one emoji, and fits.
let family = "👨‍👩‍👧‍👦";
assert!(family.len() <= MAX_EMOJI_BYTES);
let out = eva
.react(eva_side, news, Some(family))
.expect("own message");
eva.deliver(&out).expect("deliver");
let got = jan.poll().expect("poll");
assert!(
matches!(got.as_slice(), [Event::Reaction { emoji: Some(e), .. }] if e == family),
"{got:?}"
);
}
#[test]
fn a_reference_to_a_message_that_does_not_exist_or_a_bad_emoji_is_refused_before_sealing() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
eva.send(eva_side, "jedna").expect("send");
jan.poll().expect("poll");
let first = MessageRef {
author: eva.author(),
seq: 1,
};
let stranger = Client::new("Cizí", relay.clone())
.expect("stranger")
.author();
let before = relay.waiting_blobs();
for bad in [
MessageRef { seq: 2, ..first },
MessageRef { seq: 0, ..first },
MessageRef {
author: jan.author(),
seq: 1,
},
MessageRef {
author: stranger,
seq: 1,
},
] {
assert_eq!(
jan.react(jan_side, bad, Some("👍")).err(),
Some(ClientError::BadReference),
"{bad:?}"
);
assert_eq!(
jan.compose_text(jan_side, "?", Some(bad)).err(),
Some(ClientError::BadReference),
"{bad:?}"
);
}
assert_eq!(
jan.react(jan_side, first, Some(&"a".repeat(MAX_EMOJI_BYTES + 1)))
.err(),
Some(ClientError::TooLong)
);
for bad in ["", "👍\n", "\u{7}"] {
assert_eq!(
jan.react(jan_side, first, Some(bad)).err(),
Some(ClientError::BadReference),
"{bad:?}"
);
}
assert_eq!(relay.waiting_blobs(), before, "nothing was posted");
// A refused reply used no seq: the next text is still Jan's first.
jan.send(jan_side, "ok").expect("send");
let got = eva.poll().expect("poll");
assert!(
matches!(got.as_slice(), [Event::Message { seq: 1, .. }]),
"{got:?}"
);
}
#[test]
fn a_blocked_contacts_reaction_is_dropped() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
eva.send(eva_side, "ahoj").expect("send");
jan.poll().expect("poll");
let out = jan
.react(
jan_side,
MessageRef {
author: eva.author(),
seq: 1,
},
Some("😡"),
)
.expect("react");
jan.deliver(&out).expect("deliver");
let rotate = eva.block(eva_side).expect("block");
eva.deliver(&rotate).expect("rotate");
assert_eq!(eva.poll().expect("poll"), vec![]);
}
#[test]
fn the_relay_holds_no_emoji_and_no_reply_text() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
eva.send(eva_side, "CANARY-first-text").expect("send");
jan.poll().expect("poll");
let first = MessageRef {
author: eva.author(),
seq: 1,
};
let emoji = "🦜CANARY🦜";
let out = jan.react(jan_side, first, Some(emoji)).expect("react");
jan.deliver(&out).expect("deliver");
let out = jan
.compose_text(jan_side, "CANARY-reply-text", Some(first))
.expect("reply");
jan.deliver(&out).expect("deliver");
let stored = relay.everything_stored();
for needle in [
emoji,
"CANARY",
"replyTo",
"reaction",
&eva.author().to_wire(),
] {
assert!(
!contains(&stored, needle.as_bytes()),
"{needle} is readable on the relay"
);
}
assert_eq!(eva.poll().expect("poll").len(), 2);
}
+25 -5
View File
@@ -206,6 +206,14 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
let canary = "CANARY-relay-test-4b2e-never-in-the-database";
eva.send(eva_side, canary).expect("send");
jan.send(jan_side, &format!("re: {canary}")).expect("send");
// A reaction (F27) waits with them: its emoji must not be readable either.
let emoji = "🦜CANARY🦜";
let mine = MessageRef {
author: jan.author(),
seq: 1,
};
let out = jan.react(jan_side, mine, Some(emoji)).expect("react");
jan.deliver(&out).expect("deliver");
// Snapshot the database while both messages wait, before anyone fetches.
let waiting = std::fs::read(&db).expect("db");
@@ -213,21 +221,33 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
jan.poll().expect("poll"),
vec![Event::Message {
contact: jan_side,
text: canary.into()
text: canary.into(),
seq: 1,
reply_to: None,
}]
);
assert_eq!(
eva.poll().expect("poll"),
vec![Event::Message {
contact: eva_side,
text: format!("re: {canary}")
}]
vec![
Event::Message {
contact: eva_side,
text: format!("re: {canary}"),
seq: 1,
reply_to: None,
},
Event::Reaction {
contact: eva_side,
to: mine,
emoji: Some(emoji.into()),
},
]
);
let after = std::fs::read(&db).expect("db");
for snapshot in [&invited, &waiting, &after] {
for (what, needle) in [
("canary", canary.as_bytes()),
("reaction", emoji.as_bytes()),
("inviter's name", "Eva Nováková".as_bytes()),
("invitee's name", "Jan Dvořák".as_bytes()),
("invite secret", invite.secret.as_bytes().as_slice()),
+3 -1
View File
@@ -174,7 +174,9 @@ fn a_crash_between_receive_and_finish_loses_nothing_and_shows_nothing_twice() {
eva.poll().expect("poll"),
[Event::Message {
contact,
text: "funguje to".into()
text: "funguje to".into(),
seq: 1,
reply_to: None,
}]
);
}
+7 -1
View File
@@ -148,6 +148,12 @@ fixed_bytes!(
InviteId,
16
);
fixed_bytes!(
/// A message's author: the 16 random bytes in their MLS credential, made on their device, never
/// a name. With the author's `seq` it names a message (`PROTOCOL.md` §4, reactions and replies).
Author,
16
);
fixed_bytes!(
/// SHA-256 of a token, or of a blob when it is acknowledged. The relay stores token hashes only.
Sha256Hash,
@@ -193,7 +199,7 @@ macro_rules! debug_as_wire {
}
)*};
}
debug_as_wire!(MailboxId, InviteId, Sha256Hash);
debug_as_wire!(MailboxId, InviteId, Sha256Hash, Author);
/// The SHA-256 of a blob: how its recipient acknowledges it.
pub fn blob_hash(blob: &[u8]) -> Sha256Hash {
+26 -1
View File
@@ -145,6 +145,7 @@ proptest! {
let _ = InviteId::parse(&text);
let _ = Sha256Hash::parse(&text);
let _ = Token::parse(&text);
let _ = Author::parse(&text);
let _ = Token::from_bearer(&text);
let _ = WireBytes::parse(&text, MAX_BLOB_BYTES);
}
@@ -172,7 +173,10 @@ proptest! {
#[test]
fn whatever_parses_has_one_spelling(text in "[A-Za-z0-9_-]{22}") {
if let Ok(id) = MailboxId::parse(&text) {
prop_assert_eq!(id.to_wire(), text);
prop_assert_eq!(&id.to_wire(), &text);
}
if let Ok(author) = Author::parse(&text) {
prop_assert_eq!(&author.to_wire(), &text);
}
}
@@ -264,3 +268,24 @@ proptest! {
let _ = PushEndpoint::parse(&format!("https://{text}"));
}
}
// Reactions and replies (`.agents/features/reactions-replies.md` §2.1): a message's author.
#[test]
fn an_author_is_16_bytes_in_22_canonical_characters_and_prints_as_its_wire() {
let author = Author::from_bytes([0x5A; 16]);
let wire = author.to_wire();
assert_eq!(wire.len(), 22);
assert_eq!(Author::parse(&wire), Ok(author));
assert_eq!(
serde_json::to_string(&author).expect("json"),
format!("\"{wire}\"")
);
assert!(Author::parse(&wire[..21]).is_err());
assert!(Author::parse(&Token::from_bytes([1; 32]).to_wire()).is_err());
let zero = Author::from_bytes([0; 16]).to_wire();
assert_eq!(
Author::parse(&format!("{}B", &zero[..21])),
Err(ParseError::Encoding)
);
assert_eq!(format!("{author:?}"), format!("Author({wire})"));
}
+15 -1
View File
@@ -51,10 +51,23 @@ Every MLS application message carries one JSON object. The relay sees none of it
| `kind` | Fields | Meaning |
|:--|:--|:--|
| `hello` | `mailbox`, `postToken`, `name` | where and how to post to the sender; once per conversation |
| `text` | `body`, `seq` | a message; `seq` counts the sender's texts to this contact from 1 |
| `text` | `body`, `seq`, `replyTo`? | a message; `seq` counts the sender's messages to this contact from 1. `replyTo` *(2026-11-21)*, when there, names the message it answers |
| `reaction` *(2026-11-21)* | `to`, `emoji`? | the sender's reaction to the message `to`: `emoji` (1–32 bytes of UTF-8, no control characters) sets it, replacing their earlier one; absent removes it. No `seq` |
| `receipt` | `upto` | the receiver has saved the sender's texts up to `upto`. Sent only by a client with receipts on; a client with them off also ignores them |
| `inbox` | `postToken` | a new post token for the mailbox the receiver already knows (after an unblock). It cannot name another mailbox |
**Naming a message** *(added 2026-11-21, Amicitia F27; `.agents/features/reactions-replies.md`)*:
`{"author", "seq"}`, where `author` is the 16 random bytes in the author's MLS credential (unpadded
base64url, 22 characters; made on the device, never a name) and `seq` the author's own. A receiver
accepts a reference only to a message that exists in that conversation (an author who is one of its
two members, a `seq` from 1 up to the last one sent or received); a reaction that names anything
else is dropped, and a text keeps its words but loses the reference.
**Kinds a client does not know** *(2026-11-21)*: one with a `seq` of at least 1 is shown as *update
the app to see this message* and counts for receipts; one without is dropped. A known kind with an
unknown field is dropped: **new fields go into new kinds**, so that older clients say so instead of
dropping a message without a trace.
**Block** (§3) is a rotate of the post token to the hash of a token nobody gets. Nothing is sent to
the blocked person: their posts get §8's ordinary 404. What they posted before is fetched and
dropped. **Unblock** rotates again and sends the new token in an `inbox` payload.
@@ -97,6 +110,7 @@ The platform facts above are Claude's understanding, to be verified in `.agents/
## 7. Tests that prove this document
- A canary string sent in a message never appears anywhere in the relay's database or logs.
- A reaction's emoji and a reply's text never appear in the relay's database (`client/tests/real_relay.rs`, `client/tests/reactions.rs`); a reaction or reply to a message that does not exist in the conversation is refused (`client/tests/reactions.rs`, the client's unit tests).
- A post without a valid token is refused; after rotation the old token is refused.
- A delivered blob is gone; an undelivered blob is gone after the TTL (clock injected).
- A wake carries the constant body and nothing of the mailbox, its tokens or the blob; a mailbox is