Compare commits

...

6 Commits

12 changed files with 1928 additions and 33 deletions
+124
View File
@@ -0,0 +1,124 @@
# Polls — three payloads, and a poll the client keeps (`PROTOCOL.md` §4)
Amicitia F28, step 3 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
*Where shall we eat — the Italian place or the Thai one?* A chat people move to lets them ask a
question with a few answers, lets everyone vote and change their vote, and shows who chose what. The
person who asked closes it, and from then on the result is the same on every device.
So this change adds:
1. `poll`, a message (it has a `seq`, so it can be replied to and reacted to, and a receipt covers
it): a question, 2–10 options, single or multiple choice;
2. `vote`, a member's choices in a poll, replacing their earlier vote; no choices takes it back;
3. `pollClose`, sent by the asker only: the poll is closed, and **these are the final votes**.
## 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_poll(ben, "Where?", ["Italian","Thai"], false) → seq 8
C->>R: {"kind":"poll","seq":8,"question":"Where?","options":["Italian","Thai"],"multiple":false}
R->>D: fetch
D->>B: Poll{seq 8, …}; D remembers (Anna, 8): 2 options, single choice, open
B->>D: vote(anna, (Anna, 8), [1])
D->>R: {"kind":"vote","poll":{"author":"…","seq":8},"choices":[1]}
R->>C: fetch
C->>A: Vote{poll (Anna, 8), choices [1]}
A->>C: close_poll(ben, (Anna, 8))
C->>R: {"kind":"pollClose","poll":{…},"ballots":[{"author":"<Ben>","choices":[1]}]}
R->>D: fetch
D->>B: PollClosed{poll, ballots}: the final result
```
### 2.1 The payloads
```json
{"kind":"poll","seq":8,"question":"Where?","options":["Italian","Thai"],"multiple":false}
{"kind":"vote","poll":{"author":"<22 chars>","seq":8},"choices":[1]}
{"kind":"vote","poll":{"author":"<22 chars>","seq":8},"choices":[]}
{"kind":"pollClose","poll":{"author":"<22 chars>","seq":8},"ballots":[{"author":"<22 chars>","choices":[1]}]}
```
- **`poll`**: `question` 1–300 characters, `options` 2–10 of 1–100 characters each, all different;
none blank, none with a control character. `multiple` says whether a vote may hold several choices.
It shares the sender's one `seq` counter with `text`.
- **`vote`**: `choices` are indexes into `options`, ascending, each once; with `multiple` false, at
most one. `[]` takes the vote back. A vote replaces the sender's earlier one in that poll. No `seq`.
- **`pollClose`**: only the poll's author may send it. `ballots` are the votes the author's client
had accepted when it closed, one per member who has a vote (an empty vote is left out). No `seq`.
### 2.2 Why the close carries the votes
Without them two devices can disagree for ever: Ben votes while Anna closes; Anna's client receives
the vote after its close and drops it, Ben's app counted it. With `ballots`, the result after a close
is *what the asker's device saw*, and every device shows that. A vote that crossed the close is not
counted anywhere, and Ben's app sees that his vote is not in the result.
### 2.3 What the client keeps
For each conversation, the polls in it: who asked and the `seq`, how many options, `multiple`,
whether it is closed, and each member's current choices (at most two in a 1:1 chat). This goes into
the snapshot (`polls`, absent in older snapshots, so `SNAPSHOT_VERSION` stays 1). With it the client
— not each app — decides whether a vote or a close makes sense, and the close's `ballots` come from
what it accepted, not from the app.
### 2.4 What the receiving client checks
| Received | Dropped when | Otherwise |
|:--|:--|:--|
| `poll` | a field over its limit, fewer than 2 or more than 10 options, a blank or repeated option, a control character | `Event::Poll`; remembered; its `seq` counts like a text's |
| `vote` | the poll is not one it remembers in this conversation, or is closed; a choice out of range, repeated, not ascending; two choices in a single-choice poll | `Event::Vote`; replaces the sender's choices |
| `pollClose` | the sender is not the poll's author; the poll is unknown or already closed; a ballot by someone not in the conversation, twice for one person, empty, or invalid as a vote | `Event::PollClosed` with the ballots; the poll is closed, its votes are the ballots |
Blocked contacts' polls, votes and closes are dropped, as their texts are. Sending checks the same
rules and refuses with `ClientError::BadPoll` (a malformed poll or vote, a poll that is not ours to
close) or `ClientError::PollClosed`.
### 2.5 The client's API (Amicitia pins it)
- `compose_poll(contact, question, options: &[String], multiple) -> Outgoing`; `sent_seq` names it.
- `vote(contact, poll: MessageRef, choices: &[u8]) -> Outgoing`.
- `close_poll(contact, poll: MessageRef) -> Outgoing`; only our own poll.
- `Event::Poll { contact, seq, question, options, multiple }`, `Event::Vote { contact, poll, choices }`,
`Event::PollClosed { contact, poll, ballots: Vec<Ballot> }`; `Ballot { author, choices }`.
- Constants `MIN_POLL_OPTIONS` 2, `MAX_POLL_OPTIONS` 10, `MAX_OPTION_CHARS` 100,
`MAX_QUESTION_CHARS` 300.
### 2.6 An older client
A client from F27 does not know these kinds: a `poll` (it has a `seq`) shows as *Update Amicitia to
see this message*; a `vote` and a `pollClose` (no `seq`) are dropped. That is F27's rule working.
## 3. Risks
- **Privacy:** the two members learn the question, the options and who voted for what — **there is
no anonymous poll**: MLS authenticates every sender, so an anonymous vote could not be honest. The
app says *Everyone in this chat sees who voted for what* on the poll. The relay sees three more
kinds of blob, sized like short texts; the close's size grows with the number of votes (§5's note
on sizes; padding is G41's later work).
- **Integrity:** only a member can vote (MLS), only for themselves (a vote has no author field: it is
the sender's), only the asker can close, and the close can only name members.
- **Snapshot growth:** a few dozen bytes per poll, kept while the conversation exists.
- **Events (Amicitia):** none — votes and closes are not check-ins; a poll is a message like a text.
- **Offline:** staged as every payload; the app delivers them in order (F27's `deliver_older`).
## 4. Gaps and designed solutions
| Gap | Design |
|:--|:--|
| A vote and a close cross | The close carries the ballots (§2.2) |
| The app could invent a close's result | The client fills `ballots` from what it accepted (§2.3) |
| A poll from before the client kept polls (none exist: nobody sent one) | — |
| Polls in groups (F32): more members, more ballots | `Ballot` already names its author; F32 checks membership against the roster |
| The close's size reveals roughly how many voted | Up to two ballots in 1:1; G41's padding later |
| A peer reuses the `seq` of an earlier text for a poll, so one name means two messages (texts allow it too) | Later, for every kind with a `seq` at once: refuse a `seq` at or below the highest received, with care for a blob fetched again after a crash |
## 5. Verification
| Case | Test |
|:--|:--|
| A poll arrives with its seq, question, options and `multiple`; a receipt covers it | `client/tests/polls.rs` |
| A vote is set, replaced and taken back; both sides' own and their votes | same |
| A close carries the ballots the asker had, and the result is the same on both sides | same |
| A vote that crosses the close is not in the result anywhere | same |
| Only the asker closes; a vote or a second close after the close is refused and dropped | same + unit |
| Malformed polls, votes and closes are refused when sending and dropped when received | unit through `receive_payload` |
| A blocked contact's poll and vote are dropped | unit |
| The poll survives a snapshot and restore, closed or open, with its votes | `client/tests/polls.rs` |
| An F27 client shows a poll as Unsupported | F27's rule, its own test (`a_newer_apps_message_is_unsupported_and_counts_for_receipts`, now with `file` as the newer kind) |
| The relay's database holds no question and no option (canary; a choice is a small number, which no canary can find) | `real_relay.rs` |
| Planted bugs | the review |
+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 |
+1086 -18
View File
File diff suppressed because it is too large Load Diff
+7 -2
View File
@@ -3,8 +3,8 @@
//! keys, fetch tokens and post tokens. `Debug` is not implemented for any of it.
use crate::{
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, Transport, WelcomeBox,
CIPHERSUITE, MAX_NAME_CHARS,
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, PollState, Transport,
WelcomeBox, CIPHERSUITE, MAX_NAME_CHARS,
};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
@@ -54,6 +54,9 @@ struct ContactState {
sent_seq: u64,
#[serde(default)]
received_seq: u64,
// F28 (`.agents/features/polls.md` §2.3); absent in older snapshots.
#[serde(default)]
polls: Vec<PollState>,
}
fn yes() -> bool {
@@ -107,6 +110,7 @@ impl<T: Transport> Client<T> {
blocked: c.blocked,
sent_seq: c.sent_seq,
received_seq: c.received_seq,
polls: c.polls.clone(),
})
.collect(),
welcome_boxes: self.welcome_boxes.clone(),
@@ -163,6 +167,7 @@ impl<T: Transport> Client<T> {
blocked: c.blocked,
sent_seq: c.sent_seq,
received_seq: c.received_seq,
polls: c.polls,
});
}
Ok(Client {
+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,
}]
);
}
+241
View File
@@ -0,0 +1,241 @@
//! Polls (`.agents/features/polls.md`). No I/O: runs on the Android emulator too.
use tabellarius_client::*;
type C = Client<MemoryTransport>;
fn pair(relay: &MemoryTransport, receipts: bool) -> (C, ContactId, C, ContactId) {
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
eva.set_receipts(receipts);
jan.set_receipts(receipts);
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 strings(xs: &[&str]) -> Vec<String> {
xs.iter().map(|x| x.to_string()).collect()
}
fn send(c: &mut C, out: Result<Outgoing, ClientError>) {
let out = out.expect("compose");
c.deliver(&out).expect("deliver");
}
#[test]
fn a_poll_arrives_votes_change_and_the_close_gives_both_sides_the_same_result() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
eva.send(eva_side, "Ahoj").expect("send");
let options = strings(&["Italská", "Thajská", "Doma"]);
let out = eva.compose_poll(eva_side, "Kam na večeři?", &options, true);
send(&mut eva, out);
assert_eq!(eva.sent_seq(eva_side), Some(2), "a poll is a message");
let poll = MessageRef {
author: eva.author(),
seq: 2,
};
let got = jan.poll().expect("poll");
assert_eq!(
got[1],
Event::Poll {
contact: jan_side,
seq: 2,
question: "Kam na večeři?".into(),
options: options.clone(),
multiple: true,
}
);
// Jan votes, changes his mind, takes it back, votes again; Eva votes in her own poll.
for choices in [&[0u8][..], &[0, 1], &[], &[1, 2]] {
let out = jan.vote(jan_side, poll, choices);
send(&mut jan, out);
}
let out = eva.vote(eva_side, poll, &[1]);
send(&mut eva, out);
let votes: Vec<Vec<u8>> = eva
.poll()
.expect("poll")
.into_iter()
.map(|e| match e {
Event::Vote {
contact,
poll: p,
choices,
} if contact == eva_side && p == poll => choices,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(votes, vec![vec![0], vec![0, 1], vec![], vec![1, 2]]);
assert_eq!(
jan.poll().expect("poll"),
vec![Event::Vote {
contact: jan_side,
poll,
choices: vec![1]
}]
);
// A poll can be answered and reacted to like a text.
let out = jan.compose_text(jan_side, "Thajská!", Some(poll));
send(&mut jan, out);
let out = jan.react(jan_side, poll, Some("👍"));
send(&mut jan, out);
assert_eq!(eva.poll().expect("poll").len(), 2);
// Jan cannot close Eva's poll; Eva closes it.
assert_eq!(
jan.close_poll(jan_side, poll).err(),
Some(ClientError::BadPoll)
);
let out = eva.close_poll(eva_side, poll);
send(&mut eva, out);
let final_ = vec![
Ballot {
author: jan.author(),
choices: vec![1, 2],
},
Ballot {
author: eva.author(),
choices: vec![1],
},
];
let got = jan.poll().expect("poll");
let [Event::PollClosed {
contact,
poll: p,
ballots,
}] = got.as_slice()
else {
panic!("{got:?}")
};
assert_eq!((*contact, *p), (jan_side, poll));
let mut sorted = ballots.clone();
sorted.sort_by_key(|b| b.author.as_bytes().to_vec());
let mut expected = final_.clone();
expected.sort_by_key(|b| b.author.as_bytes().to_vec());
assert_eq!(sorted, expected);
assert_eq!(
jan.vote(jan_side, poll, &[0]).err(),
Some(ClientError::PollClosed)
);
assert_eq!(
eva.vote(eva_side, poll, &[0]).err(),
Some(ClientError::PollClosed)
);
}
#[test]
fn a_vote_that_crosses_the_close_is_counted_nowhere() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
let out = eva.compose_poll(eva_side, "Pátek?", &strings(&["ano", "ne"]), false);
send(&mut eva, out);
jan.poll().expect("poll");
let poll = MessageRef {
author: eva.author(),
seq: 1,
};
let out = jan.vote(jan_side, poll, &[0]);
send(&mut jan, out);
eva.poll().expect("poll");
// Both at once: Jan changes his vote while Eva closes.
let out = jan.vote(jan_side, poll, &[1]);
send(&mut jan, out);
let out = eva.close_poll(eva_side, poll);
send(&mut eva, out);
assert_eq!(
eva.poll().expect("poll"),
vec![],
"the late vote is dropped"
);
let got = jan.poll().expect("poll");
assert_eq!(
got,
vec![Event::PollClosed {
contact: jan_side,
poll,
ballots: vec![Ballot {
author: jan.author(),
choices: vec![0]
}],
}],
"Jan's result is Eva's: his first vote, not the one that crossed"
);
}
#[test]
fn a_receipt_covers_a_poll() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay, true);
let out = eva.compose_poll(eva_side, "Pivo?", &strings(&["ano", "jasně"]), false);
send(&mut eva, out);
let got = jan.poll().expect("poll");
assert!(
matches!(got.as_slice(), [Event::Poll { seq: 1, .. }]),
"{got:?}"
);
assert!(eva.poll().expect("poll").contains(&Event::Delivered {
contact: eva_side,
upto: 1
}));
}
#[test]
fn a_poll_survives_a_restart_open_or_closed_with_its_votes() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
let out = eva.compose_poll(eva_side, "Kdy?", &strings(&["pá", "so", "ne"]), true);
send(&mut eva, out);
let out = eva.compose_poll(eva_side, "Kde?", &strings(&["u nás", "u vás"]), false);
send(&mut eva, out);
jan.poll().expect("poll");
let when = MessageRef {
author: eva.author(),
seq: 1,
};
let where_ = MessageRef {
author: eva.author(),
seq: 2,
};
let out = jan.vote(jan_side, when, &[0, 2]);
send(&mut jan, out);
eva.poll().expect("poll");
let out = eva.close_poll(eva_side, where_);
send(&mut eva, out);
jan.poll().expect("poll");
let mut eva = C::restore(&eva.snapshot().expect("snapshot"), relay.clone()).expect("eva");
let mut jan = C::restore(&jan.snapshot().expect("snapshot"), relay.clone()).expect("jan");
// Closed stays closed, on both sides.
assert_eq!(
jan.vote(jan_side, where_, &[0]).err(),
Some(ClientError::PollClosed)
);
assert_eq!(
eva.close_poll(eva_side, where_).err(),
Some(ClientError::PollClosed)
);
// The open one keeps Jan's vote: Eva's close after the restart carries it.
let out = eva.close_poll(eva_side, when);
send(&mut eva, out);
assert_eq!(
jan.poll().expect("poll"),
vec![Event::PollClosed {
contact: jan_side,
poll: when,
ballots: vec![Ballot {
author: jan.author(),
choices: vec![0, 2]
}],
}]
);
}
+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);
}
+42 -5
View File
@@ -206,6 +206,21 @@ 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");
// And a poll (F28): its question and options neither.
let question = "POLL-QUESTION-CANARY";
let options = vec!["OPTION-CANARY-A".to_string(), "OPTION-CANARY-B".to_string()];
let out = jan
.compose_poll(jan_side, question, &options, false)
.expect("poll");
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 +228,43 @@ 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()),
},
Event::Poll {
contact: eva_side,
seq: 2,
question: question.into(),
options: options.clone(),
multiple: false,
},
]
);
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()),
("poll question", question.as_bytes()),
("poll option", options[0].as_bytes()),
("poll option", options[1].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})"));
}
+19 -1
View File
@@ -51,10 +51,26 @@ 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` |
| `poll` *(2026-11-22)* | `seq`, `question`, `options`, `multiple` | a message (it shares `seq` with `text`): a question of 1–300 characters and 2–10 different options of 1–100, none blank, no control characters; `multiple` allows several choices in a vote |
| `vote` *(2026-11-22)* | `poll`, `choices` | the sender's choices in the poll `poll` names, replacing their earlier ones: indexes into `options`, ascending, each once, at most one unless `multiple`; `[]` takes the vote back. Refused once the poll is closed. No `seq` |
| `pollClose` *(2026-11-22)* | `poll`, `ballots` | sent by the poll's author only: the poll is closed, and `ballots` (`{author, choices}`, one per member with a non-empty vote) are **the final votes**, as the author's client had accepted them, so a vote that crossed the close counts nowhere. 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 +113,8 @@ 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 poll's question and options never appear in the relay's database (`client/tests/real_relay.rs`); a vote or close that does not fit its poll, a close by anyone but the poll's author, and anything after the close are refused and dropped (`client/tests/polls.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