//! The Tabellarius client: MLS 1:1 conversations (OpenMLS), a mailbox per contact, invites. //! No cryptography is written here by hand: MLS is OpenMLS, HKDF and SHA-256 are RustCrypto. //! //! Pairing (`.agents/features/client.md` §2): //! 1. The inviter makes a KeyPackage and a link (invite id + secret). It also makes a *welcome //! mailbox*, whose id and post token are derived from the secret. //! 2. The invitee claims the KeyPackage, creates the MLS group, and posts the Welcome and an MLS //! `hello` (its own mailbox and post token, and its name) to the welcome mailbox. //! 3. The inviter joins, and answers with its own `hello` to the invitee's mailbox. //! //! The relay only ever holds MLS ciphertext, KeyPackages, ids and token hashes. //! //! **An app that keeps the client across restarts** (`.agents/features/client-state.md`) uses the //! staged calls — [`Client::compose`], [`Client::accept`], [`Client::receive`] — then saves //! [`Client::snapshot`] together with what they returned, and only then calls [`Client::deliver`] //! or [`Client::finish`]. Nothing reaches the relay after a state change before the app has saved //! it. [`Client::send`], [`Client::accept_invite`] and [`Client::poll`] do both steps at once, for //! use without persistence. pub mod transport; mod snapshot; pub use snapshot::SNAPSHOT_VERSION; use hkdf::Hkdf; use openmls::prelude::tls_codec::{Deserialize as _, Serialize as _}; use openmls::prelude::*; use openmls_basic_credential::SignatureKeyPair; use openmls_rust_crypto::OpenMlsRustCrypto; use serde::{Deserialize, Serialize}; use sha2::Sha256; use snapshot::Bytes; use std::fmt; use tabellarius_protocol::{ blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, Sha256Hash, Token, MAX_BLOB_BYTES, }; pub use transport::{MemoryTransport, Transport, TransportError}; /// RFC 9420's mandatory ciphersuite. pub const CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519; /// The longest display name sent in a `hello`. 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; const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox"; const WELCOME_POST_LABEL: &[u8] = b"tabellarius v0 welcome mailbox post"; /// Why something failed. Never carries a message's text, a name, or a token. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ClientError { Transport(TransportError), /// MLS refused: a bad KeyPackage, a Welcome that is not for us, a message that does not verify. Mls, /// No randomness from the system. Random, /// A name or text over its limit. TooLong, /// No such contact, or a contact whose mailbox is not known yet. UnknownContact, /// A snapshot that does not parse, has another version, or does not match OpenMLS's storage. State, } impl From for ClientError { fn from(e: TransportError) -> Self { ClientError::Transport(e) } } /// What the link to share carries, besides the relay's address. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Invite { pub id: InviteId, pub secret: Token, } /// The welcome mailbox's id and post token, derived from an invite secret with HKDF-SHA256. pub fn welcome_mailbox(secret: &Token) -> (MailboxId, Token) { let hk = Hkdf::::new(None, secret.as_bytes()); let mut id = [0u8; 16]; let mut post = [0u8; 32]; // Lengths within HKDF's limit (255 × 32 bytes): expand cannot fail here. let _ = hk.expand(WELCOME_ID_LABEL, &mut id); let _ = hk.expand(WELCOME_POST_LABEL, &mut post); (MailboxId::from_bytes(id), Token::from_bytes(post)) } /// A local handle for a contact. Means nothing outside this client. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)] pub struct ContactId(pub u32); /// What [`Client::receive`] found. #[derive(Clone, PartialEq, Eq, Debug)] pub enum Event { /// The other side's `hello` arrived: the conversation can be used both ways. On the /// inviter's side, `via` is the invite it came through; on the invitee's side it is `None` /// (the app already knows the contact from [`Client::accept`]). Joined { contact: ContactId, name: String, via: Option, }, Message { contact: ContactId, text: String, }, } /// One blob for the relay, to deliver once the app has saved the snapshot. An app may keep it in /// an outbox and deliver it again after a crash: a second copy is refused by MLS as a replay. /// `Debug` shows neither the post token nor the bytes. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Outgoing { to: MailboxId, post: Token, blob: Bytes, } impl fmt::Debug for Outgoing { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Outgoing({} bytes)", self.blob.0.len()) } } /// A fetched blob to acknowledge once the app has saved what it produced. #[derive(Clone, PartialEq, Eq)] struct Ack { mailbox: MailboxId, fetch: Token, hash: Sha256Hash, } /// What one [`Client::receive`] produced. Save the snapshot and the events, keep the `outgoing` /// blobs if the app has an outbox, then call [`Client::finish`]. #[derive(Debug)] pub struct Received { pub events: Vec, /// Our answering `hello`s. pub outgoing: Vec, /// The relay failed part-way: what was fetched before it is here, the rest waits there. pub interrupted: Option, acks: Vec, } impl fmt::Debug for Ack { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Ack") } } /// 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)] enum Payload { #[serde(rename_all = "camelCase")] Hello { mailbox: MailboxId, post_token: Token, name: String, }, Text { body: String, }, } #[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] struct Mailbox { id: MailboxId, fetch: Token, } /// A welcome mailbox and the invite it belongs to. #[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] struct WelcomeBox { mailbox: Mailbox, invite: InviteId, } struct Contact { id: ContactId, group: MlsGroup, name: Option, /// Where the other side posts to us. `None` on the inviter's side until our `hello` is ready. inbox: Option, /// Where we post to the other side: their mailbox and its post token. outbox: Option<(MailboxId, Token)>, /// The invite this contact came through, on the inviter's side. via: Option, } pub struct Client { provider: OpenMlsRustCrypto, signer: SignatureKeyPair, credential: CredentialWithKey, identity: Vec, name: String, transport: T, contacts: Vec, welcome_boxes: Vec, next_contact: u32, } impl Client { /// A new identity: an Ed25519 key and a credential holding 16 random bytes, never a name. pub fn new(name: &str, transport: T) -> Result { if name.chars().count() > MAX_NAME_CHARS { return Err(ClientError::TooLong); } let provider = OpenMlsRustCrypto::default(); let signer = SignatureKeyPair::new(CIPHERSUITE.signature_algorithm()) .map_err(|_| ClientError::Mls)?; signer .store(provider.storage()) .map_err(|_| ClientError::Mls)?; let identity: [u8; 16] = provider .rand() .random_array() .map_err(|_| ClientError::Random)?; let credential = credential_with_key(&identity, &signer); Ok(Self { provider, signer, credential, identity: identity.to_vec(), name: name.to_string(), transport, contacts: Vec::new(), welcome_boxes: Vec::new(), next_contact: 0, }) } fn random(&self) -> Result<[u8; N], ClientError> { self.provider .rand() .random_array() .map_err(|_| ClientError::Random) } /// A fresh mailbox on the relay: we keep the fetch token, the post token goes to the contact. fn new_mailbox(&self) -> Result<(Mailbox, Token), ClientError> { let id = MailboxId::from_bytes(self.random()?); let post = Token::from_bytes(self.random()?); let fetch = Token::from_bytes(self.random()?); self.transport.create_mailbox(&CreateMailbox { id, post_token_hash: post.hash(), fetch_token_hash: fetch.hash(), })?; Ok((Mailbox { id, fetch }, post)) } /// Step 1: a KeyPackage on the relay and a welcome mailbox. Save the snapshot, then share the /// result as a link. pub fn create_invite(&mut self) -> Result { let bundle = KeyPackage::builder() .build( CIPHERSUITE, &self.provider, &self.signer, self.credential.clone(), ) .map_err(|_| ClientError::Mls)?; let kp = bundle .key_package() .tls_serialize_detached() .map_err(|_| ClientError::Mls)?; let invite = Invite { id: InviteId::from_bytes(self.random()?), secret: Token::from_bytes(self.random()?), }; let (welcome_id, welcome_post) = welcome_mailbox(&invite.secret); let fetch = Token::from_bytes(self.random()?); self.transport.create_mailbox(&CreateMailbox { id: welcome_id, post_token_hash: welcome_post.hash(), fetch_token_hash: fetch.hash(), })?; self.transport.create_invite(&CreateInvite { id: invite.id, secret_hash: invite.secret.hash(), key_package: KeyPackageBytes::new(kp).map_err(|_| ClientError::Mls)?, })?; self.welcome_boxes.push(WelcomeBox { mailbox: Mailbox { id: welcome_id, fetch, }, invite: invite.id, }); Ok(invite) } /// Stops fetching an invite's welcome mailbox: the invite was cancelled, or is older than the /// relay keeps unclaimed invites (7 days; the app has the clock, the library has none). /// Otherwise an unclaimed invite's mailbox is fetched for ever. Save the snapshot after it. pub fn forget_invite(&mut self, invite: &InviteId) { self.welcome_boxes.retain(|w| w.invite != *invite); } /// Forgets a contact: its MLS group is deleted from storage, its name and tokens from the /// client, and its mailbox is no longer fetched. The other side is not told, and anything it /// still posts waits on the relay until it expires. Save the snapshot after it. Returns whether /// there was such a contact. pub fn forget_contact(&mut self, contact: ContactId) -> Result { let Some(index) = self.contacts.iter().position(|c| c.id == contact) else { return Ok(false); }; let mut c = self.contacts.remove(index); c.group .delete(self.provider.storage()) .map_err(|_| ClientError::State)?; Ok(true) } /// Step 2, on the other device, staged: claims the KeyPackage (which uses the link up) and /// creates our mailbox, then makes the group. The Welcome and our `hello` come back for the /// app to deliver after saving. pub fn accept(&mut self, invite: &Invite) -> Result<(ContactId, Vec), ClientError> { let kp_bytes = self.transport.claim_invite(&invite.id, &invite.secret)?; let key_package = KeyPackageIn::tls_deserialize_exact(&kp_bytes) .map_err(|_| ClientError::Mls)? .validate(self.provider.crypto(), ProtocolVersion::Mls10) .map_err(|_| ClientError::Mls)?; let (inbox, inbox_post) = self.new_mailbox()?; let config = MlsGroupCreateConfig::builder() .ciphersuite(CIPHERSUITE) .use_ratchet_tree_extension(true) .build(); let mut group = MlsGroup::new( &self.provider, &self.signer, &config, self.credential.clone(), ) .map_err(|_| ClientError::Mls)?; let (_commit, welcome, _info) = group .add_members(&self.provider, &self.signer, &[key_package]) .map_err(|_| ClientError::Mls)?; group .merge_pending_commit(&self.provider) .map_err(|_| ClientError::Mls)?; let hello = Payload::Hello { mailbox: inbox.id, post_token: inbox_post, name: self.name.clone(), }; let (welcome_id, welcome_post) = welcome_mailbox(&invite.secret); let welcome = welcome .tls_serialize_detached() .map_err(|_| ClientError::Mls)?; let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?; let out = vec![ Outgoing { to: welcome_id, post: welcome_post, blob: Bytes(welcome), }, Outgoing { to: welcome_id, post: welcome_post, blob: Bytes(hello), }, ]; let id = self.add_contact(group, Some(inbox), None, None); Ok((id, out)) } /// [`Client::accept`] and delivering at once, for use without persistence. pub fn accept_invite(&mut self, invite: &Invite) -> Result { let (id, out) = self.accept(invite)?; for o in &out { self.deliver(o)?; } Ok(id) } fn add_contact( &mut self, group: MlsGroup, inbox: Option, outbox: Option<(MailboxId, Token)>, via: Option, ) -> ContactId { let id = ContactId(self.next_contact); self.next_contact += 1; self.contacts.push(Contact { id, group, name: None, inbox, outbox, via, }); id } fn seal( provider: &OpenMlsRustCrypto, signer: &SignatureKeyPair, group: &mut MlsGroup, payload: &Payload, ) -> Result, ClientError> { let json = serde_json::to_vec(payload).map_err(|_| ClientError::Mls)?; let blob = group .create_message(provider, signer, &json) .map_err(|_| ClientError::Mls)? .tls_serialize_detached() .map_err(|_| ClientError::Mls)?; if blob.len() > MAX_BLOB_BYTES { return Err(ClientError::TooLong); } Ok(blob) } /// 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 { 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 (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?; let blob = Self::seal( &self.provider, &self.signer, &mut c.group, &Payload::Text { body: text.to_string(), }, )?; Ok(Outgoing { to, post, blob: Bytes(blob), }) } /// Posts one blob to the relay. pub fn deliver(&self, out: &Outgoing) -> Result<(), ClientError> { self.transport.post(&out.to, &out.post, &out.blob.0)?; Ok(()) } /// [`Client::compose`] and [`Client::deliver`] at once, for use without persistence. pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> { let out = self.compose(contact, text)?; self.deliver(&out) } /// The contact's name, once its `hello` has arrived. pub fn contact_name(&self, contact: ContactId) -> Option<&str> { self.contacts .iter() .find(|c| c.id == contact) .and_then(|c| c.name.as_deref()) } /// Fetches every own mailbox and processes each blob in order. Posts nothing and acknowledges /// nothing: save the snapshot and the events, then call [`Client::finish`]. A blob that is /// not valid MLS for one of our groups is dropped without a trace: nothing from it is shown, /// and it is acknowledged with the rest. /// /// If the relay fails part-way, what was processed so far is returned (with `interrupted` /// set), because the client's state already includes it. pub fn receive(&mut self) -> Result { let mut got = Received { events: Vec::new(), outgoing: Vec::new(), interrupted: None, acks: Vec::new(), }; let mut sources: Vec<(Mailbox, Option)> = self .welcome_boxes .iter() .map(|w| (w.mailbox, Some(w.invite))) .collect(); sources.extend( self.contacts .iter() .filter_map(|c| c.inbox.map(|m| (m, None))), ); for (mailbox, via) in sources { let blobs = match self.transport.fetch(&mailbox.id, &mailbox.fetch) { Ok(blobs) => blobs, Err(e) => { got.interrupted = Some(e); break; } }; for blob in blobs { // A failure to understand one blob must not stop the rest, nor be shown. if let Ok(Some(event)) = self.process(&blob, via) { got.events.push(event); } got.acks.push(Ack { mailbox: mailbox.id, fetch: mailbox.fetch, hash: blob_hash(&blob), }); } } // The inviter's side: each contact whose `hello` arrived gets ours, with a new mailbox. A // relay that fails here leaves the contact owing its answer until the next receive. for index in 0..self.contacts.len() { let c = &self.contacts[index]; let Some((to, post)) = c.outbox else { continue }; if c.inbox.is_some() || got.interrupted.is_some() { continue; } match self.new_mailbox() { Ok((inbox, inbox_post)) => { let hello = Payload::Hello { mailbox: inbox.id, post_token: inbox_post, name: self.name.clone(), }; let c = &mut self.contacts[index]; // Failing to seal leaves the answer owed, like a relay failure: the events // already processed must still reach the app. let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &hello) else { continue; }; c.inbox = Some(inbox); got.outgoing.push(Outgoing { to, post, blob: Bytes(blob), }); } Err(ClientError::Transport(e)) => got.interrupted = Some(e), Err(_) => continue, } } Ok(got) } /// After saving: delivers the `outgoing` blobs, then acknowledges the fetched ones. On an /// error, call it again later; anything delivered twice is refused by MLS as a replay. /// /// Then a welcome mailbox whose contact has said hello is dropped, so junk posted to it later /// is never fetched. Not before: a snapshot saved between `receive` and `finish` must still /// know the mailbox, so that a restored client fetches its blobs again and acknowledges them. /// Save the snapshot again after `finish`. pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> { for out in &received.outgoing { self.deliver(out)?; } for ack in &received.acks { self.transport .acknowledge(&ack.mailbox, &ack.fetch, &ack.hash)?; } let joined: Vec = self .contacts .iter() .filter(|c| c.name.is_some()) .filter_map(|c| c.via) .collect(); self.welcome_boxes.retain(|w| !joined.contains(&w.invite)); Ok(()) } /// [`Client::receive`] and [`Client::finish`] at once, for use without persistence. pub fn poll(&mut self) -> Result, ClientError> { let got = self.receive()?; self.finish(&got)?; match got.interrupted { Some(e) if got.events.is_empty() => Err(ClientError::Transport(e)), _ => Ok(got.events), } } fn process( &mut self, blob: &[u8], via: Option, ) -> Result, ClientError> { let message = MlsMessageIn::tls_deserialize_exact(blob).map_err(|_| ClientError::Mls)?; match message.extract() { // Only a welcome mailbox carries a Welcome. MlsMessageBodyIn::Welcome(welcome) if via.is_some() => { let config = MlsGroupJoinConfig::builder() .use_ratchet_tree_extension(true) .build(); let staged = StagedWelcome::new_from_welcome(&self.provider, &config, welcome, None) .map_err(|_| ClientError::Mls)?; // The same group twice (a Welcome fetched again after a crash): refused. let group_id = staged.group_context().group_id(); if self.contacts.iter().any(|c| c.group.group_id() == group_id) { return Err(ClientError::Mls); } let group = staged .into_group(&self.provider) .map_err(|_| ClientError::Mls)?; // Not a contact to show yet: the hello right behind the Welcome makes it one. self.add_contact(group, None, None, via); Ok(None) } MlsMessageBodyIn::PrivateMessage(private) => { let protocol: ProtocolMessage = private.into(); let group_id = protocol.group_id().clone(); let index = self .contacts .iter() .position(|c| c.group.group_id() == &group_id) .ok_or(ClientError::UnknownContact)?; let processed = self.contacts[index] .group .process_message(&self.provider, protocol) .map_err(|_| ClientError::Mls)?; let ProcessedMessageContent::ApplicationMessage(app) = processed.into_content() else { return Ok(None); }; let payload: Payload = serde_json::from_slice(&app.into_bytes()).map_err(|_| ClientError::Mls)?; self.receive_payload(index, payload) } _ => Err(ClientError::Mls), } } fn receive_payload( &mut self, index: usize, payload: Payload, ) -> Result, ClientError> { match payload { Payload::Hello { mailbox, post_token, name, } => { if name.chars().count() > MAX_NAME_CHARS || self.contacts[index].name.is_some() { return Err(ClientError::Mls); } let c = &mut self.contacts[index]; c.outbox = Some((mailbox, post_token)); c.name = Some(name.clone()); Ok(Some(Event::Joined { contact: c.id, name, via: c.via, })) } Payload::Text { body } => { 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); } Ok(Some(Event::Message { contact: c.id, text: body, })) } } } } fn credential_with_key(identity: &[u8], signer: &SignatureKeyPair) -> CredentialWithKey { CredentialWithKey { credential: BasicCredential::new(identity.to_vec()).into(), signature_key: signer.public().into(), } } #[cfg(test)] mod tests { use super::*; /// A contact who sends a second `hello` must not redirect our messages to another mailbox, /// nor rename themselves. Only the contact can send one (MLS authenticates it), so this guards /// against a misbehaving contact or a replayed message. #[test] fn a_second_hello_changes_nothing() { let relay = MemoryTransport::default(); let mut eva = Client::new("Eva", relay.clone()).expect("eva"); let mut jan = Client::new("Jan", relay.clone()).expect("jan"); let invite = eva.create_invite().expect("invite"); jan.accept_invite(&invite).expect("accept"); let joined = eva.poll().expect("poll"); assert_eq!(joined.len(), 1); let before = eva.contacts[0].outbox.map(|(m, _)| m); let other = MailboxId::from_bytes([9; 16]); let again = Payload::Hello { mailbox: other, post_token: Token::from_bytes([9; 32]), name: "Mallory".into(), }; assert_eq!(eva.receive_payload(0, again), Err(ClientError::Mls)); assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before); assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan")); } }