3a0944ebff
ci / check (pull_request) Has been cancelled
The relay stores files (id, upload and fetch token hashes, chunk count, uploaded hour) and chunks (file id, index, ciphertext): every chunk is 256 000 bytes, so it learns the size rounded up to 250 KiB and nothing finer, and it keeps no fetch count. Only the uploader's token puts or deletes, only the fetch token gets, a chunk never changes; per-file and relay-wide quotas answer 507; files go after 30 days, incomplete ones after 24 hours. The client pads a file to whole chunks and seals each with ChaCha20-Poly1305 in the aead crate's STREAM, under a key made for that file; the key, name, type, size and thumbnail travel only in the new `file` payload, which shares `seq` with text. Also: every route now answers a bare 413 (axum's own carried a text). PROTOCOL.md §1, §4, §5, §7, §8.
513 lines
17 KiB
Rust
513 lines
17 KiB
Rust
//! 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 <token>'"),
|
|
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<Vec<u8>, 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<const N: usize>(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<Self, ParseError> {
|
|
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<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
|
s.serialize_str(&self.to_wire())
|
|
}
|
|
}
|
|
|
|
impl<'de> Deserialize<'de> for $name {
|
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
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 <token>`.
|
|
pub fn from_bearer(header: &str) -> Result<Self, ParseError> {
|
|
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<u8>);
|
|
|
|
impl WireBytes {
|
|
pub fn parse(text: &str, max: usize) -> Result<Self, ParseError> {
|
|
// 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<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
|
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<u8>) -> Result<Self, ParseError> {
|
|
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: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
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<FetchedBlob>,
|
|
}
|
|
|
|
/// `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<Self, ParseError> {
|
|
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: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
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<Self, ParseError> {
|
|
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::<u16>() {
|
|
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<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
|
s.serialize_str(&self.url)
|
|
}
|
|
}
|
|
|
|
impl<'de> Deserialize<'de> for PushEndpoint {
|
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
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,
|
|
}
|