Files
Amicitia-Tabellarius/crates/protocol/src/lib.rs
T

330 lines
11 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;
/// 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 },
}
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"),
}
}
}
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!(
/// 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
);
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);
/// 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,
}
/// 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)
}