//! Wire types for the Tabellarius protocol v0 (`docs/PROTOCOL.md`, approved 2026-11-08). //! //! No I/O. Every value that crosses the wire has exactly one spelling: ids and tokens are unpadded //! base64url of a fixed number of bytes, and parsing refuses anything else with a [`ParseError`]. //! The HTTP routes that carry these types are listed in `.agents/features/relay.md` §2. use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use sha2::{Digest, Sha256}; use std::borrow::Cow; use std::fmt; /// The protocol version, as it appears in every path (`/v0/...`). pub const VERSION: &str = "v0"; /// The largest blob (one MLS message) the relay accepts. pub const MAX_BLOB_BYTES: usize = 256 * 1024; /// The largest KeyPackage an invite may carry. pub const MAX_KEY_PACKAGE_BYTES: usize = 16 * 1024; /// At most this many blobs come back from one fetch; the rest wait for the next. pub const MAX_BLOBS_PER_FETCH: usize = 100; /// A blob not acknowledged is deleted after this many seconds (30 days, `PROTOCOL.md` §5). pub const BLOB_TTL_SECS: i64 = 30 * 24 * 3600; /// An unclaimed invite expires after this many seconds (7 days, `PROTOCOL.md` §4). pub const INVITE_TTL_SECS: i64 = 7 * 24 * 3600; /// The longest push endpoint a mailbox may hold (UnifiedPush's own limit, `wake-up.md` §2.1). pub const MAX_PUSH_ENDPOINT_BYTES: usize = 1000; /// The body of every wake: a constant, so it carries nothing (`PROTOCOL.md` §6). pub const WAKE_BODY: &[u8] = b"wake"; /// A mailbox is woken at most once in this many seconds. pub const WAKE_EVERY_SECS: i64 = 60; /// Every file chunk on the wire is exactly this many bytes, the last one too (250 KiB; G41, /// `.agents/features/files.md` §2.1). pub const FILE_CHUNK_BYTES: usize = 256_000; /// The most chunks one file may have: 100 MiB of plaintext at 255 984 bytes a chunk. pub const MAX_FILE_CHUNKS: u32 = 410; /// A file that is not complete this long after it was created is purged (`files.md` §2.3). pub const INCOMPLETE_FILE_TTL_SECS: i64 = 24 * 3600; /// Why a value from the wire was refused. Carries no part of the input. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ParseError { /// Not unpadded base64url, or not its one canonical spelling. Encoding, /// Decoded to the wrong number of bytes. Length { expected: usize, got: usize }, /// The bearer header is missing its `Bearer ` prefix. Scheme, /// More bytes than the protocol allows. TooLarge { max: usize }, /// Not a push endpoint the protocol accepts (`wake-up.md` §2.1). Endpoint, } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ParseError::Encoding => write!(f, "not canonical unpadded base64url"), ParseError::Length { expected, got } => { write!(f, "expected {expected} bytes, got {got}") } ParseError::Scheme => write!(f, "expected 'Bearer '"), ParseError::TooLarge { max } => write!(f, "more than {max} bytes"), ParseError::Endpoint => write!(f, "not an https push endpoint"), } } } impl std::error::Error for ParseError {} fn is_base64url(text: &str) -> bool { text.bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') } /// Decodes canonical unpadded base64url: refuses other alphabets, padding, and spellings whose /// unused trailing bits are not zero (those would give one value a second spelling). fn decode_canonical(text: &str) -> Result, ParseError> { if !is_base64url(text) { return Err(ParseError::Encoding); } let bytes = URL_SAFE_NO_PAD .decode(text) .map_err(|_| ParseError::Encoding)?; if URL_SAFE_NO_PAD.encode(&bytes) != text { return Err(ParseError::Encoding); } Ok(bytes) } fn decode_exact(text: &str) -> Result<[u8; N], ParseError> { // A cheap bound first: anything longer than N bytes' worth of characters is refused unread. if text.len() > N.div_ceil(3) * 4 { return Err(ParseError::Length { expected: N, got: text.len() / 4 * 3, }); } let bytes = decode_canonical(text)?; let got = bytes.len(); bytes .try_into() .map_err(|_| ParseError::Length { expected: N, got }) } macro_rules! fixed_bytes { ($(#[$doc:meta])* $name:ident, $len:expr) => { $(#[$doc])* #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct $name([u8; $len]); impl $name { pub const LEN: usize = $len; pub fn from_bytes(bytes: [u8; $len]) -> Self { Self(bytes) } pub fn as_bytes(&self) -> &[u8; $len] { &self.0 } /// Parses the wire spelling: unpadded base64url of exactly `LEN` bytes. pub fn parse(text: &str) -> Result { decode_exact::<$len>(text).map(Self) } pub fn to_wire(&self) -> String { URL_SAFE_NO_PAD.encode(self.0) } } impl Serialize for $name { fn serialize(&self, s: S) -> Result { s.serialize_str(&self.to_wire()) } } impl<'de> Deserialize<'de> for $name { fn deserialize>(d: D) -> Result { let text = Cow::<'de, str>::deserialize(d)?; Self::parse(&text).map_err(serde::de::Error::custom) } } }; } fixed_bytes!( /// A mailbox: 16 random bytes made by its owner. One per contact (`PROTOCOL.md` §3). MailboxId, 16 ); fixed_bytes!( /// An invite: 16 random bytes made by the inviter (`PROTOCOL.md` §4). InviteId, 16 ); fixed_bytes!( /// A file on the relay: 16 random bytes made by its uploader (`PROTOCOL.md` §8, files). FileId, 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, 32 ); fixed_bytes!( /// A capability: a post token, a fetch token or an invite's one-time secret. 32 random bytes. /// Never stored by the relay; only its [`Sha256Hash`] is. Token, 32 ); fixed_bytes!( /// A file's key: 32 random bytes made for one file, travelling only inside MLS (`PROTOCOL.md` /// §4, `file`). The relay never sees it. FileKey, 32 ); // A file key is a secret: never printed. impl fmt::Debug for FileKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("FileKey(..)") } } impl Token { /// The hash the relay stores and compares against. pub fn hash(&self) -> Sha256Hash { Sha256Hash(Sha256::digest(self.0).into()) } /// Parses an `Authorization` header value: `Bearer `. pub fn from_bearer(header: &str) -> Result { let token = header.strip_prefix("Bearer ").ok_or(ParseError::Scheme)?; Self::parse(token) } pub fn to_bearer(&self) -> String { format!("Bearer {}", self.to_wire()) } } // Tokens are secrets: never printed, not even in a debug log. impl fmt::Debug for Token { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Token(..)") } } macro_rules! debug_as_wire { ($($name:ident),*) => {$( impl fmt::Debug for $name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}({})", stringify!($name), self.to_wire()) } } )*}; } debug_as_wire!(MailboxId, InviteId, Sha256Hash, Author, FileId); /// The SHA-256 of a blob: how its recipient acknowledges it. pub fn blob_hash(blob: &[u8]) -> Sha256Hash { Sha256Hash(Sha256::digest(blob).into()) } /// Bytes inside JSON as unpadded base64url, with an upper bound checked before decoding. #[derive(Clone, PartialEq, Eq)] pub struct WireBytes(pub Vec); impl WireBytes { pub fn parse(text: &str, max: usize) -> Result { // 4 characters carry 3 bytes: anything longer cannot fit, and is refused before decoding. if text.len() > max.div_ceil(3) * 4 { return Err(ParseError::TooLarge { max }); } let bytes = decode_canonical(text)?; if bytes.len() > max { return Err(ParseError::TooLarge { max }); } Ok(Self(bytes)) } } impl fmt::Debug for WireBytes { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "WireBytes({} bytes)", self.0.len()) } } impl Serialize for WireBytes { fn serialize(&self, s: S) -> Result { s.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0)) } } macro_rules! bounded_bytes { ($(#[$doc:meta])* $name:ident, $max:expr) => { $(#[$doc])* #[derive(Clone, PartialEq, Eq, Debug, Serialize)] #[serde(transparent)] pub struct $name(pub WireBytes); impl $name { pub fn new(bytes: Vec) -> Result { if bytes.len() > $max { return Err(ParseError::TooLarge { max: $max }); } Ok(Self(WireBytes(bytes))) } pub fn bytes(&self) -> &[u8] { &self.0 .0 } } impl<'de> Deserialize<'de> for $name { fn deserialize>(d: D) -> Result { let text = Cow::<'de, str>::deserialize(d)?; WireBytes::parse(&text, $max) .map(Self) .map_err(serde::de::Error::custom) } } }; } bounded_bytes!( /// A KeyPackage inside an invite, at most [`MAX_KEY_PACKAGE_BYTES`]. KeyPackageBytes, MAX_KEY_PACKAGE_BYTES ); bounded_bytes!( /// A blob inside a fetch response, at most [`MAX_BLOB_BYTES`]. BlobBytes, MAX_BLOB_BYTES ); /// `POST /v0/mailboxes`. The owner sends hashes, so the relay never sees the tokens themselves here. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CreateMailbox { pub id: MailboxId, pub post_token_hash: Sha256Hash, pub fetch_token_hash: Sha256Hash, } /// `PUT /v0/mailboxes/{id}/post-token`: blocking someone = giving everyone else a new post token. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct RotatePostToken { pub post_token_hash: Sha256Hash, } /// One waiting blob in `GET /v0/mailboxes/{id}/blobs`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FetchedBlob { pub blob: BlobBytes, /// Unix time in hours, rounded down: all the relay keeps of when it arrived. pub received_hour: i64, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FetchedBlobs { pub blobs: Vec, } /// `POST /v0/invites`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CreateInvite { pub id: InviteId, pub secret_hash: Sha256Hash, pub key_package: KeyPackageBytes, } /// `GET /v0/invites/{id}`: the inviter's KeyPackage, handed out once. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ClaimedInvite { pub key_package: KeyPackageBytes, } /// `GET /version`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct VersionInfo { pub protocol: String, pub relay: String, } /// How many chunks a file has: 1 to [`MAX_FILE_CHUNKS`]; anything else does not parse. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(transparent)] pub struct ChunkCount(u32); impl ChunkCount { pub fn new(n: u32) -> Result { if (1..=MAX_FILE_CHUNKS).contains(&n) { Ok(Self(n)) } else { Err(ParseError::TooLarge { max: MAX_FILE_CHUNKS as usize, }) } } pub fn get(&self) -> u32 { self.0 } } impl<'de> Deserialize<'de> for ChunkCount { fn deserialize>(d: D) -> Result { ChunkCount::new(u32::deserialize(d)?).map_err(serde::de::Error::custom) } } /// `POST /v0/files`: the uploader sends hashes of the two tokens it made, and the chunk count. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CreateFile { pub id: FileId, pub upload_token_hash: Sha256Hash, pub fetch_token_hash: Sha256Hash, pub chunks: ChunkCount, } /// Rounds unix seconds down to the hour, as the relay stores arrival times. pub fn hour_of(unix_secs: i64) -> i64 { unix_secs.div_euclid(3600) } /// Rounds unix seconds down to the day, as the relay stores when a mailbox was made. pub fn day_of(unix_secs: i64) -> i64 { unix_secs.div_euclid(86_400) } /// A push endpoint (`PROTOCOL.md` §6, `.agents/features/wake-up.md` §2.1): a capability URL at the /// push server the mailbox's owner chose. `https://` with a host, no user info, no fragment, printable /// ASCII, at most [`MAX_PUSH_ENDPOINT_BYTES`]; `http://` only to a loopback host, which a relay /// accepts only when its operator allows it (tests). #[derive(Clone, PartialEq, Eq)] pub struct PushEndpoint { url: String, host: String, https: bool, } impl PushEndpoint { pub fn parse(text: &str) -> Result { let bad = || ParseError::Endpoint; if text.len() > MAX_PUSH_ENDPOINT_BYTES { return Err(ParseError::TooLarge { max: MAX_PUSH_ENDPOINT_BYTES, }); } if !text.bytes().all(|b| (0x21..=0x7e).contains(&b)) || text.contains('#') { return Err(bad()); } let (https, rest) = if let Some(r) = text.strip_prefix("https://") { (true, r) } else if let Some(r) = text.strip_prefix("http://") { (false, r) } else { return Err(bad()); }; let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())]; if authority.contains('@') { return Err(bad()); } let (host, port) = if let Some(v6) = authority.strip_prefix('[') { let end = v6.find(']').ok_or_else(bad)?; (&v6[..end], &v6[end + 1..]) } else { match authority.find(':') { Some(i) => (&authority[..i], &authority[i..]), None => (authority, ""), } }; if host.is_empty() || host.contains(['[', ']']) && !authority.starts_with('[') { return Err(bad()); } if !port.is_empty() { let digits = port.strip_prefix(':').ok_or_else(bad)?; match digits.parse::() { Ok(p) if p > 0 && !digits.starts_with('0') => {} _ => return Err(bad()), } } let host = host.to_ascii_lowercase(); if !https && !matches!(host.as_str(), "127.0.0.1" | "::1" | "localhost") { return Err(bad()); } Ok(Self { url: text.to_string(), host, https, }) } pub fn as_str(&self) -> &str { &self.url } /// The host, lower case, without brackets or port. pub fn host(&self) -> &str { &self.host } /// `http://` to a loopback host: only for a relay whose operator allows it. pub fn is_loopback_http(&self) -> bool { !self.https } } /// The endpoint is a capability: `Debug` shows its host only. impl fmt::Debug for PushEndpoint { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "PushEndpoint({})", self.host) } } impl Serialize for PushEndpoint { fn serialize(&self, s: S) -> Result { s.serialize_str(&self.url) } } impl<'de> Deserialize<'de> for PushEndpoint { fn deserialize>(d: D) -> Result { let text = Cow::<'de, str>::deserialize(d)?; PushEndpoint::parse(&text).map_err(serde::de::Error::custom) } } /// `PUT /v0/mailboxes/{id}/push`: where to wake the mailbox's owner (`PROTOCOL.md` §6). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SetPush { pub endpoint: PushEndpoint, }