first commit

This commit is contained in:
yves committed 2026-11-20 21:47:33 +01:00
commit 6d3ea3e2a6
43 files changed
+8204

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
[package]
name = "meow-core"
description = "Meow v2 protocol logic (no I/O): cards, invitations, messaging, server requests"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
meow-proto = { path = "../meow-proto" }
meow-crypto = { path = "../meow-crypto" }
prost = "0.14"
serde = { version = "1", features = ["derive"] }
thiserror = "2"
[lints]
workspace = true
+197
View File
@@ -0,0 +1,197 @@
//! Contacts: per-relationship keys, peer public material and state.
use meow_crypto::{ratchet::Session, DhKeyPair, DhPublic, SignPublic, SigningKeyPair};
use meow_proto::{v2, PROTOCOL_VERSION};
use serde::{Deserialize, Serialize};
use crate::server::ServerInfo;
use crate::{proto_err, Error, Result};
/// Random contact identifier (16 bytes, hex encoded).
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ContactId(pub String);
impl ContactId {
pub fn random() -> Self {
Self(crate::hex(&meow_crypto::random_bytes::<16>()))
}
}
impl std::fmt::Display for ContactId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
/// My own key material for one relationship. Never shared between contacts.
#[derive(Clone, Serialize, Deserialize)]
pub struct OwnKeys {
pub identity: SigningKeyPair,
pub dh: DhKeyPair,
pub mailbox: SigningKeyPair,
pub ratchet: DhKeyPair,
}
impl OwnKeys {
pub fn generate() -> Self {
Self {
identity: SigningKeyPair::generate(),
dh: DhKeyPair::generate(),
mailbox: SigningKeyPair::generate(),
ratchet: DhKeyPair::generate(),
}
}
/// The card I give to this contact.
pub fn card(&self, my_name: &str, pull_servers: &[ServerInfo]) -> v2::ContactCard {
v2::ContactCard {
version: PROTOCOL_VERSION,
name: my_name.to_string(),
identity_key: self.identity.public().to_vec(),
dh_key: self.dh.public().to_vec(),
mailbox: self.mailbox.public().to_vec(),
ratchet_key: self.ratchet.public().to_vec(),
pull_servers: pull_servers.iter().map(ServerInfo::to_card).collect(),
}
}
}
/// Public material received from a contact.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerCard {
pub name: String,
pub identity: SignPublic,
pub dh: DhPublic,
pub mailbox: SignPublic,
pub ratchet: DhPublic,
pub pull_servers: Vec<ServerInfo>,
}
impl PeerCard {
pub fn from_proto(c: &v2::ContactCard) -> Result<Self> {
if c.version != PROTOCOL_VERSION {
return Err(proto_err("unsupported contact card version"));
}
let pull_servers = c
.pull_servers
.iter()
.map(ServerInfo::from_card)
.collect::<Result<Vec<_>>>()?;
if pull_servers.is_empty() {
return Err(proto_err("contact card has no pull server"));
}
Ok(Self {
name: c.name.clone(),
identity: SignPublic::from_slice(&c.identity_key)?,
dh: DhPublic::from_slice(&c.dh_key)?,
mailbox: SignPublic::from_slice(&c.mailbox)?,
ratchet: DhPublic::from_slice(&c.ratchet_key)?,
pull_servers,
})
}
}
/// Secrets kept by the initiator between steps 1 and 3.
#[derive(Clone, Serialize, Deserialize)]
pub struct OfferSecrets {
pub offer_dh: DhKeyPair,
pub answer_mailbox: SigningKeyPair,
/// Exact encoded offer, hashed into the transcript.
pub offer_bytes: Vec<u8>,
pub expires_at: u64,
}
/// Lifecycle of a contact.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContactState {
/// Initiator, step 1 done: waiting for the invitee's answer.
OfferSent,
/// Invitee, step 2 done: waiting for the initiator's confirmation.
AnswerSent,
/// Initiator, step 3 done: can send; waiting for the invitee's ack.
ConfirmSent,
/// Handshake complete on this side.
Active,
}
/// A contact (one relationship).
#[derive(Clone, Serialize, Deserialize)]
pub struct Contact {
pub id: ContactId,
/// Local name for this contact.
pub name: String,
/// Name I present to this contact.
pub my_name: String,
pub state: ContactState,
pub invitation_id: [u8; 16],
pub invitation_message: String,
/// Initiator only, until step 3.
pub offer: Option<OfferSecrets>,
/// My keys (created at step 2 for the invitee, step 3 for the initiator).
pub keys: Option<OwnKeys>,
/// Servers where I poll my mailbox for this contact.
pub my_pull_servers: Vec<ServerInfo>,
pub peer: Option<PeerCard>,
/// Serialised Double Ratchet session.
pub session: Option<Vec<u8>>,
/// Invitee only, between steps 2 and 4: hash of the received offer.
pub offer_hash: Option<[u8; 32]>,
/// Invitee only, between steps 2 and 4: the exact card sent in the answer.
pub sent_card: Option<Vec<u8>>,
/// Final handshake transcript hash, usable as a safety number.
pub transcript: Option<[u8; 32]>,
pub created_at: u64,
}
impl Contact {
pub fn can_send(&self) -> bool {
matches!(self.state, ContactState::ConfirmSent | ContactState::Active) && self.session.is_some()
}
pub(crate) fn load_session(&self) -> Result<Session> {
let bytes = self.session.as_ref().ok_or(Error::State("no ratchet session"))?;
Ok(Session::from_bytes(bytes)?)
}
pub(crate) fn keys(&self) -> Result<&OwnKeys> {
self.keys.as_ref().ok_or(Error::State("contact keys not created yet"))
}
pub(crate) fn peer(&self) -> Result<&PeerCard> {
self.peer.as_ref().ok_or(Error::State("peer card unknown"))
}
/// The mailbox I currently poll for this contact, with the key that proves ownership.
pub fn my_mailbox(&self) -> Option<&SigningKeyPair> {
match (&self.keys, &self.offer) {
(Some(k), _) => Some(&k.mailbox),
(None, Some(o)) => Some(&o.answer_mailbox),
_ => None,
}
}
/// Mailboxes to poll, with the servers to poll them on.
///
/// While an offer is pending, the initiator also keeps polling the answer mailbox.
pub fn mailboxes(&self) -> Vec<(&SigningKeyPair, &[ServerInfo])> {
let mut v = Vec::new();
if let Some(k) = &self.keys {
v.push((&k.mailbox, self.my_pull_servers.as_slice()));
}
if let Some(o) = &self.offer {
v.push((&o.answer_mailbox, self.my_pull_servers.as_slice()));
}
v
}
/// Short human-comparable safety number derived from the handshake transcript.
pub fn safety_number(&self) -> Option<String> {
self.transcript.map(|t| {
t[..10]
.chunks(2)
.map(|c| format!("{:05}", u16::from_be_bytes([c[0], c[1]])))
.collect::<Vec<_>>()
.join(" ")
})
}
}
+386
View File
@@ -0,0 +1,386 @@
//! Four-step invitation handshake (see ARCHITECTURE.md §3.3).
//!
//! The functions here only transform data; how the bytes travel (file, QR code,
//! server shortcode, mailbox, BLE...) is up to the caller.
//!
//! | step | who | function | produces |
//! |------|-----------|----------------|-------------------------------------------|
//! | 1 | initiator | [`create_offer`] | `InvitationOffer` |
//! | 2 | invitee | [`answer`] | `InvitationMessage` (step 2, sealed) |
//! | 3 | initiator | [`accept`] | `InvitationMessage` (step 3, sealed) |
//! | 4 | invitee | [`finalize`] | `PeerEnvelope` (ratchet `HandshakeAck`) |
//!
//! The initiator becomes `Active` when it decrypts the step-4 ack
//! ([`crate::messaging::decrypt`]).
use meow_crypto::ratchet::Session;
use meow_crypto::seal::{self, SealedBox};
use meow_crypto::{kdf, sha256, DhKeyPair, DhPublic, SignPublic, SigningKeyPair};
use meow_proto::{v2, Message, PROTOCOL_VERSION};
use crate::contact::{Contact, ContactId, ContactState, OfferSecrets, OwnKeys, PeerCard};
use crate::messaging;
use crate::server::ServerInfo;
use crate::{proto_err, Error, Result};
const CTX_ANSWER: &str = "invite/answer";
const CTX_CONFIRM: &str = "invite/confirm";
fn offer_hash(offer_bytes: &[u8]) -> [u8; 32] {
sha256(&[b"meow/v2/invite/offer", offer_bytes])
}
fn answer_transcript(offer_hash: &[u8; 32], invitee_card: &[u8]) -> [u8; 32] {
sha256(&[b"meow/v2/invite/answer", offer_hash, invitee_card])
}
fn confirm_transcript(offer_hash: &[u8; 32], invitee_card: &[u8], initiator_card: &[u8], eph: &DhPublic) -> [u8; 32] {
sha256(&[
b"meow/v2/invite/confirm",
offer_hash,
invitee_card,
initiator_card,
eph.as_bytes(),
])
}
fn shared_key(dh1: &[u8; 32], dh2: &[u8; 32], dh3: &[u8; 32], transcript: &[u8; 32]) -> Result<[u8; 32]> {
let ikm = [dh1.as_slice(), dh2, dh3].concat();
Ok(kdf::derive(&ikm, transcript, "invite/x3dh")?)
}
fn to_sealed(b: SealedBox) -> v2::Sealed {
v2::Sealed {
version: PROTOCOL_VERSION,
ephemeral_key: b.ephemeral.to_vec(),
ciphertext: b.ciphertext,
}
}
fn from_sealed(s: &v2::Sealed) -> Result<SealedBox> {
Ok(SealedBox {
ephemeral: DhPublic::from_slice(&s.ephemeral_key)?,
ciphertext: s.ciphertext.clone(),
})
}
fn invitation_id(b: &[u8]) -> Result<[u8; 16]> {
b.try_into().map_err(|_| proto_err("bad invitation id"))
}
// ───────────────────────────── Step 1 ─────────────────────────────
/// Result of step 1: the pending contact (to store) and the encoded offer (to transmit).
pub struct NewOffer {
pub contact: Contact,
pub offer_bytes: Vec<u8>,
}
/// Step 1 (initiator): create an offer.
///
/// `my_pull_servers` are the servers where the answer may be posted and where I will
/// later receive messages from this contact.
pub fn create_offer(
contact_name: &str,
my_name: &str,
my_pull_servers: Vec<ServerInfo>,
message: &str,
now: u64,
ttl_seconds: u64,
) -> Result<NewOffer> {
if my_pull_servers.is_empty() {
return Err(proto_err("at least one server is required"));
}
let id: [u8; 16] = meow_crypto::random_bytes();
let offer_dh = DhKeyPair::generate();
let answer_mailbox = SigningKeyPair::generate();
let expires_at = now + ttl_seconds;
let offer = v2::InvitationOffer {
version: PROTOCOL_VERSION,
invitation_id: id.to_vec(),
initiator_name: my_name.to_string(),
offer_dh_key: offer_dh.public().to_vec(),
answer_mailbox: answer_mailbox.public().to_vec(),
answer_servers: my_pull_servers.iter().map(ServerInfo::to_card).collect(),
message: message.to_string(),
expires_at,
};
let offer_bytes = offer.encode_to_vec();
let contact = Contact {
id: ContactId::random(),
name: contact_name.to_string(),
my_name: my_name.to_string(),
state: ContactState::OfferSent,
invitation_id: id,
invitation_message: message.to_string(),
offer: Some(OfferSecrets {
offer_dh,
answer_mailbox,
offer_bytes: offer_bytes.clone(),
expires_at,
}),
keys: None,
my_pull_servers,
peer: None,
session: None,
offer_hash: None,
sent_card: None,
transcript: None,
created_at: now,
};
Ok(NewOffer { contact, offer_bytes })
}
/// Decoded, validated view of an offer, e.g. for "invitation check".
#[derive(Debug, Clone)]
pub struct OfferInfo {
pub invitation_id: [u8; 16],
pub initiator_name: String,
pub message: String,
pub expires_at: u64,
pub answer_servers: Vec<ServerInfo>,
pub answer_mailbox: SignPublic,
}
/// Parse and validate an offer.
pub fn inspect_offer(offer_bytes: &[u8], now: u64) -> Result<OfferInfo> {
let o = v2::InvitationOffer::decode(offer_bytes)?;
if o.version != PROTOCOL_VERSION {
return Err(proto_err("unsupported invitation version"));
}
if o.expires_at < now {
return Err(Error::Expired);
}
DhPublic::from_slice(&o.offer_dh_key)?;
Ok(OfferInfo {
invitation_id: invitation_id(&o.invitation_id)?,
initiator_name: o.initiator_name,
message: o.message,
expires_at: o.expires_at,
answer_servers: o
.answer_servers
.iter()
.map(ServerInfo::from_card)
.collect::<Result<_>>()?,
answer_mailbox: SignPublic::from_slice(&o.answer_mailbox)?,
})
}
// ───────────────────────────── Step 2 ─────────────────────────────
/// Step 2 (invitee): answer an offer. Returns the pending contact and the answer.
pub fn answer(
offer_bytes: &[u8],
contact_name: &str,
my_name: &str,
my_pull_servers: Vec<ServerInfo>,
now: u64,
) -> Result<(Contact, v2::InvitationMessage)> {
if my_pull_servers.is_empty() {
return Err(proto_err("at least one server is required"));
}
inspect_offer(offer_bytes, now)?;
let offer = v2::InvitationOffer::decode(offer_bytes)?;
let id = invitation_id(&offer.invitation_id)?;
let oh = offer_hash(offer_bytes);
let keys = OwnKeys::generate();
let card = keys.card(my_name, &my_pull_servers);
let card_bytes = card.encode_to_vec();
let signature = keys.identity.sign(&answer_transcript(&oh, &card_bytes)).to_vec();
let body = v2::InvitationAnswerBody {
invitation_id: id.to_vec(),
invitee: Some(card),
signature,
};
let (sealed, _) = seal::seal(
&DhPublic::from_slice(&offer.offer_dh_key)?,
CTX_ANSWER,
&body.encode_to_vec(),
)?;
let msg = v2::InvitationMessage {
version: PROTOCOL_VERSION,
step: 2,
invitation_id: id.to_vec(),
sealed: Some(to_sealed(sealed)),
};
let contact = Contact {
id: ContactId::random(),
name: contact_name.to_string(),
my_name: my_name.to_string(),
state: ContactState::AnswerSent,
invitation_id: id,
invitation_message: offer.message,
offer: None,
keys: Some(keys),
my_pull_servers,
peer: None,
session: None,
offer_hash: Some(oh),
sent_card: Some(card_bytes),
transcript: None,
created_at: now,
};
Ok((contact, msg))
}
// ───────────────────────────── Step 3 ─────────────────────────────
/// Step 3 (initiator): process the answer, create my keys and the confirmation.
///
/// After this call the contact can already send messages (`ConfirmSent`).
pub fn accept(contact: &mut Contact, msg: &v2::InvitationMessage, now: u64) -> Result<v2::InvitationMessage> {
if contact.state != ContactState::OfferSent {
return Err(Error::State("contact is not waiting for an answer"));
}
if msg.step != 2 || msg.invitation_id != contact.invitation_id {
return Err(proto_err("not an answer to this invitation"));
}
let offer = contact.offer.as_ref().ok_or(Error::State("offer secrets missing"))?;
if offer.expires_at < now {
return Err(Error::Expired);
}
let sealed = from_sealed(msg.sealed.as_ref().ok_or_else(|| proto_err("missing sealed body"))?)?;
let (pt, _) = seal::open(&offer.offer_dh, CTX_ANSWER, &sealed)?;
let body = v2::InvitationAnswerBody::decode(pt.as_slice())?;
if body.invitation_id != contact.invitation_id {
return Err(proto_err("invitation id mismatch"));
}
let invitee_card = body.invitee.ok_or_else(|| proto_err("missing invitee card"))?;
let invitee_bytes = invitee_card.encode_to_vec();
let peer = PeerCard::from_proto(&invitee_card)?;
let oh = offer_hash(&offer.offer_bytes);
peer.identity
.verify(&answer_transcript(&oh, &invitee_bytes), &body.signature)?;
let keys = OwnKeys::generate();
let my_card = keys.card(&contact.my_name, &contact.my_pull_servers);
let my_card_bytes = my_card.encode_to_vec();
let eph = DhKeyPair::generate();
let th = confirm_transcript(&oh, &invitee_bytes, &my_card_bytes, &eph.public());
let sk = shared_key(
keys.dh.dh(&peer.dh)?.as_bytes(),
eph.dh(&peer.dh)?.as_bytes(),
eph.dh(&peer.ratchet)?.as_bytes(),
&th,
)?;
let mut session = Session::init_sender(sk, peer.ratchet)?;
let ack = messaging::new_message(
v2::user_message::Body::HandshakeAck(v2::HandshakeAck {
invitation_id: contact.invitation_id.to_vec(),
}),
now * 1000,
);
let first = messaging::seal_with(
&mut session,
&ack,
&messaging::ad(&keys.identity.public(), &peer.identity),
)?;
let confirm = v2::InvitationConfirmBody {
invitation_id: contact.invitation_id.to_vec(),
initiator: Some(my_card),
ephemeral_key: eph.public().to_vec(),
signature: keys.identity.sign(&th).to_vec(),
first_message: Some(first),
};
let (sealed, _) = seal::seal(&peer.dh, CTX_CONFIRM, &confirm.encode_to_vec())?;
if contact.name.is_empty() {
contact.name = peer.name.clone();
}
contact.keys = Some(keys);
contact.peer = Some(peer);
contact.session = Some(session.to_bytes());
contact.offer = None;
contact.transcript = Some(th);
contact.state = ContactState::ConfirmSent;
Ok(v2::InvitationMessage {
version: PROTOCOL_VERSION,
step: 3,
invitation_id: contact.invitation_id.to_vec(),
sealed: Some(to_sealed(sealed)),
})
}
// ───────────────────────────── Step 4 ─────────────────────────────
/// Step 4 (invitee): verify the confirmation, activate the contact and build the ack
/// (a ratchet message to deposit in the initiator's mailbox).
pub fn finalize(contact: &mut Contact, msg: &v2::InvitationMessage) -> Result<v2::PeerEnvelope> {
if contact.state != ContactState::AnswerSent {
return Err(Error::State("contact is not waiting for a confirmation"));
}
if msg.step != 3 || msg.invitation_id != contact.invitation_id {
return Err(proto_err("not a confirmation for this invitation"));
}
let keys = contact.keys()?.clone();
let sealed = from_sealed(msg.sealed.as_ref().ok_or_else(|| proto_err("missing sealed body"))?)?;
let (pt, _) = seal::open(&keys.dh, CTX_CONFIRM, &sealed)?;
let body = v2::InvitationConfirmBody::decode(pt.as_slice())?;
if body.invitation_id != contact.invitation_id {
return Err(proto_err("invitation id mismatch"));
}
let initiator_card = body.initiator.ok_or_else(|| proto_err("missing initiator card"))?;
let peer = PeerCard::from_proto(&initiator_card)?;
let eph = DhPublic::from_slice(&body.ephemeral_key)?;
let oh = contact.offer_hash.ok_or(Error::State("offer hash missing"))?;
let sent_card = contact.sent_card.as_ref().ok_or(Error::State("sent card missing"))?;
let th = confirm_transcript(&oh, sent_card, &initiator_card.encode_to_vec(), &eph);
peer.identity.verify(&th, &body.signature)?;
let sk = shared_key(
keys.dh.dh(&peer.dh)?.as_bytes(),
keys.dh.dh(&eph)?.as_bytes(),
keys.ratchet.dh(&eph)?.as_bytes(),
&th,
)?;
let mut session = Session::init_receiver(sk, keys.ratchet.clone());
let first = body.first_message.ok_or_else(|| proto_err("missing first message"))?;
let hello = messaging::open_with(
&mut session,
&first,
&messaging::ad(&peer.identity, &keys.identity.public()),
)?;
match hello.body {
Some(v2::user_message::Body::HandshakeAck(a)) if a.invitation_id == contact.invitation_id => {}
_ => return Err(proto_err("unexpected first message")),
}
if contact.name.is_empty() {
contact.name = peer.name.clone();
}
contact.peer = Some(peer);
contact.session = Some(session.to_bytes());
contact.offer_hash = None;
contact.sent_card = None;
contact.transcript = Some(th);
contact.state = ContactState::Active;
let ack = messaging::new_message(
v2::user_message::Body::HandshakeAck(v2::HandshakeAck {
invitation_id: contact.invitation_id.to_vec(),
}),
hello.sent_at_ms,
);
messaging::encrypt(contact, &ack)
}
/// Wrap a step-2 answer for deposit into the offer's answer mailbox.
pub fn answer_deposit(offer: &OfferInfo, answer: &v2::InvitationMessage) -> v2::Deposit {
let env = v2::PeerEnvelope {
version: PROTOCOL_VERSION,
body: Some(v2::peer_envelope::Body::Invitation(answer.clone())),
};
v2::Deposit {
mailbox: offer.answer_mailbox.to_vec(),
payload: env.encode_to_vec(),
}
}
/// Wrap a step-3 confirmation for deposit into the invitee's mailbox.
pub fn confirm_deposit(contact: &Contact, confirm: &v2::InvitationMessage) -> Result<v2::Deposit> {
let env = v2::PeerEnvelope {
version: PROTOCOL_VERSION,
body: Some(v2::peer_envelope::Body::Invitation(confirm.clone())),
};
messaging::deposit_for(contact, &env)
}
+59
View File
@@ -0,0 +1,59 @@
//! Meow v2 protocol logic.
//!
//! This crate performs **no I/O**: no network, no disk, no implicit clock (the current
//! time is always passed as a parameter). It is shared by the server, the CLI and the
//! mobile FFI layer, and is fully deterministic to test.
//!
//! * [`server`]: server cards, server key material;
//! * [`contact`]: per-contact keys and state;
//! * [`invitation`]: the 4-step invitation handshake;
//! * [`messaging`]: user messages ↔ Double Ratchet envelopes;
//! * [`rpc`]: sealed client ↔ server requests and mailbox authentication.
#![forbid(unsafe_code)]
#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))]
pub mod contact;
pub mod invitation;
pub mod messaging;
pub mod rpc;
pub mod server;
pub use meow_crypto as crypto;
pub use meow_proto::v2 as proto;
/// Errors of the protocol layer.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("crypto: {0}")]
Crypto(#[from] meow_crypto::CryptoError),
#[error("decode: {0}")]
Decode(#[from] prost::DecodeError),
#[error("protocol: {0}")]
Protocol(String),
#[error("invalid state: {0}")]
State(&'static str),
#[error("expired")]
Expired,
}
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) fn proto_err(msg: impl Into<String>) -> Error {
Error::Protocol(msg.into())
}
pub(crate) fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
/// Parse a lower/upper-case hex string.
pub fn from_hex(s: &str) -> Option<Vec<u8>> {
if !s.len().is_multiple_of(2) {
return None;
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
.collect()
}
+99
View File
@@ -0,0 +1,99 @@
//! User messages ↔ Double Ratchet envelopes.
//!
//! ```text
//! UserMessage → protobuf → pad → DR encrypt (ad = label ‖ sender id ‖ receiver id) → RatchetMessage
//! ```
//! There is no signature: authenticity comes from the ratchet, which keeps messages deniable.
use meow_crypto::ratchet::{Header, Session};
use meow_crypto::{pad, DhPublic, SignPublic};
use meow_proto::{v2, Message, PROTOCOL_VERSION};
use crate::contact::{Contact, ContactState};
use crate::{proto_err, Error, Result};
const AD_LABEL: &[u8] = b"meow/v2/msg";
pub(crate) fn ad(sender: &SignPublic, receiver: &SignPublic) -> Vec<u8> {
[AD_LABEL, sender.as_bytes(), receiver.as_bytes()].concat()
}
/// Build a user message with a fresh random id.
pub fn new_message(body: v2::user_message::Body, now_ms: u64) -> v2::UserMessage {
v2::UserMessage {
id: meow_crypto::random_bytes::<16>().to_vec(),
sent_at_ms: now_ms,
body: Some(body),
reply_to: Vec::new(),
}
}
pub fn text(text: &str, now_ms: u64) -> v2::UserMessage {
new_message(
v2::user_message::Body::Text(v2::TextBody { text: text.to_string() }),
now_ms,
)
}
pub(crate) fn seal_with(session: &mut Session, msg: &v2::UserMessage, ad: &[u8]) -> Result<v2::RatchetMessage> {
let padded = pad::pad(&msg.encode_to_vec());
let (h, ciphertext) = session.encrypt(&padded, ad)?;
Ok(v2::RatchetMessage {
header: Some(v2::RatchetHeader {
dh_key: h.dh.to_vec(),
previous_count: h.pn,
message_number: h.n,
}),
ciphertext,
})
}
pub(crate) fn open_with(session: &mut Session, rm: &v2::RatchetMessage, ad: &[u8]) -> Result<v2::UserMessage> {
let h = rm.header.as_ref().ok_or_else(|| proto_err("missing ratchet header"))?;
let header = Header {
dh: DhPublic::from_slice(&h.dh_key)?,
pn: h.previous_count,
n: h.message_number,
};
let padded = session.decrypt(&header, &rm.ciphertext, ad)?;
Ok(v2::UserMessage::decode(pad::unpad(&padded)?)?)
}
/// Encrypt a message for `contact`; updates the stored session.
pub fn encrypt(contact: &mut Contact, msg: &v2::UserMessage) -> Result<v2::PeerEnvelope> {
if !contact.can_send() {
return Err(Error::State("contact cannot receive messages yet"));
}
let ad = ad(&contact.keys()?.identity.public(), &contact.peer()?.identity);
let mut session = contact.load_session()?;
let rm = seal_with(&mut session, msg, &ad)?;
contact.session = Some(session.to_bytes());
Ok(v2::PeerEnvelope {
version: PROTOCOL_VERSION,
body: Some(v2::peer_envelope::Body::Ratchet(rm)),
})
}
/// Decrypt a ratchet message from `contact`; updates the stored session.
///
/// A `HandshakeAck` received by the initiator completes the invitation (state → Active).
pub fn decrypt(contact: &mut Contact, rm: &v2::RatchetMessage) -> Result<v2::UserMessage> {
let ad = ad(&contact.peer()?.identity, &contact.keys()?.identity.public());
let mut session = contact.load_session()?;
let msg = open_with(&mut session, rm, &ad)?;
contact.session = Some(session.to_bytes());
if let Some(v2::user_message::Body::HandshakeAck(ack)) = &msg.body {
if ack.invitation_id == contact.invitation_id && contact.state == ContactState::ConfirmSent {
contact.state = ContactState::Active;
}
}
Ok(msg)
}
/// Wrap an envelope into a deposit for the contact's mailbox.
pub fn deposit_for(contact: &Contact, env: &v2::PeerEnvelope) -> Result<v2::Deposit> {
Ok(v2::Deposit {
mailbox: contact.peer()?.mailbox.to_vec(),
payload: env.encode_to_vec(),
})
}
+189
View File
@@ -0,0 +1,189 @@
//! Sealed client ↔ server requests and mailbox authentication.
//!
//! Requests are sealed to the server's X25519 key; the response is encrypted with the
//! key derived alongside (`k_resp`). The client is therefore anonymous to the server.
//! Pulling a mailbox requires a signature with the mailbox private key, bound to the
//! server, the request id and a timestamp.
use meow_crypto::aead::{self, Key};
use meow_crypto::seal::{self, SealedBox};
use meow_crypto::{DhPublic, SignPublic, SigningKeyPair};
use meow_proto::{v2, Message, PROTOCOL_VERSION};
use crate::server::{ServerInfo, ServerKeys};
use crate::{proto_err, Error, Result};
const CTX_REQUEST: &str = "rpc/request";
const AAD_RESPONSE: &[u8] = b"meow/v2/rpc/response";
const PULL_LABEL: &[u8] = b"meow/v2/pull";
/// Maximum accepted clock skew for mailbox authentications, in seconds.
pub const AUTH_WINDOW_SECS: u64 = 300;
/// Client-side state needed to read the response of a sealed request.
pub struct PendingCall {
key: Key,
request_id: Vec<u8>,
}
/// Build a request with a fresh random id.
pub fn new_request(body: v2::request::Body, now: u64) -> v2::Request {
v2::Request {
request_id: meow_crypto::random_bytes::<16>().to_vec(),
timestamp: now,
body: Some(body),
}
}
/// Client: seal a request for `server`.
pub fn seal_request(server: &ServerInfo, req: &v2::Request) -> Result<(Vec<u8>, PendingCall)> {
let (sealed, key) = seal::seal(&server.dh_key, CTX_REQUEST, &req.encode_to_vec())?;
let wire = v2::SealedRequest {
version: PROTOCOL_VERSION,
ephemeral_key: sealed.ephemeral.to_vec(),
ciphertext: sealed.ciphertext,
};
Ok((
wire.encode_to_vec(),
PendingCall {
key,
request_id: req.request_id.clone(),
},
))
}
/// Client: decrypt and check a response. Server-side errors become [`Error::Protocol`].
pub fn open_response(call: &PendingCall, bytes: &[u8]) -> Result<v2::response::Body> {
let wire = v2::SealedResponse::decode(bytes)?;
let pt = aead::decrypt(&call.key, &wire.ciphertext, AAD_RESPONSE)?;
let resp = v2::Response::decode(pt.as_slice())?;
if resp.request_id != call.request_id {
return Err(proto_err("response does not match request"));
}
match resp.body {
Some(v2::response::Body::Error(e)) => Err(proto_err(format!(
"server error {:?}: {}",
v2::error::Code::try_from(e.code).unwrap_or(v2::error::Code::Unspecified),
e.message
))),
Some(b) => Ok(b),
None => Err(proto_err("empty response")),
}
}
/// Server: open a sealed request. Returns the request and the response key.
pub fn open_request(keys: &ServerKeys, bytes: &[u8]) -> Result<(v2::Request, Key)> {
let wire = v2::SealedRequest::decode(bytes)?;
if wire.version != PROTOCOL_VERSION {
return Err(proto_err("unsupported request version"));
}
let sealed = SealedBox {
ephemeral: DhPublic::from_slice(&wire.ephemeral_key)?,
ciphertext: wire.ciphertext,
};
let (pt, key) = seal::open(&keys.dh, CTX_REQUEST, &sealed)?;
Ok((v2::Request::decode(pt.as_slice())?, key))
}
/// Server: encrypt a response with the key returned by [`open_request`].
pub fn seal_response(key: &Key, resp: &v2::Response) -> Vec<u8> {
v2::SealedResponse {
version: PROTOCOL_VERSION,
ciphertext: aead::encrypt(key, &resp.encode_to_vec(), AAD_RESPONSE),
}
.encode_to_vec()
}
fn pull_message(server_sign: &SignPublic, mailbox: &SignPublic, ts: u64, request_id: &[u8]) -> Vec<u8> {
[
PULL_LABEL,
server_sign.as_bytes(),
mailbox.as_bytes(),
&ts.to_be_bytes(),
request_id,
]
.concat()
}
/// Client: prove ownership of a mailbox for one pull request.
pub fn mailbox_auth(mailbox: &SigningKeyPair, server: &ServerInfo, request_id: &[u8], now: u64) -> v2::MailboxAuth {
let pk = mailbox.public();
v2::MailboxAuth {
mailbox: pk.to_vec(),
timestamp: now,
signature: mailbox
.sign(&pull_message(&server.sign_key, &pk, now, request_id))
.to_vec(),
}
}
/// Server: verify a mailbox authentication. Replay protection on `request_id` is the
/// caller's job (it needs shared state).
pub fn verify_mailbox_auth(
server_sign: &SignPublic,
request_id: &[u8],
auth: &v2::MailboxAuth,
now: u64,
) -> Result<SignPublic> {
let mailbox = SignPublic::from_slice(&auth.mailbox)?;
if auth.timestamp.abs_diff(now) > AUTH_WINDOW_SECS {
return Err(Error::Expired);
}
mailbox.verify(
&pull_message(server_sign, &mailbox, auth.timestamp, request_id),
&auth.signature,
)?;
Ok(mailbox)
}
/// Server helper: build an error response.
pub fn error_response(request_id: Vec<u8>, code: v2::error::Code, message: &str) -> v2::Response {
v2::Response {
request_id,
body: Some(v2::response::Body::Error(v2::Error {
code: code as i32,
message: message.to_string(),
})),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn request_response_roundtrip() {
let keys = ServerKeys::generate();
let info = ServerInfo::from_card(&keys.card("http://s", "s", "", 1)).unwrap();
let req = new_request(v2::request::Body::Ping(v2::Ping {}), 10);
let (wire, call) = seal_request(&info, &req).unwrap();
let (got, key) = open_request(&keys, &wire).unwrap();
assert_eq!(got, req);
let resp = v2::Response {
request_id: got.request_id.clone(),
body: Some(v2::response::Body::Pong(v2::Pong { server_time: 11 })),
};
let body = open_response(&call, &seal_response(&key, &resp)).unwrap();
assert_eq!(body, v2::response::Body::Pong(v2::Pong { server_time: 11 }));
// a response for another request is rejected
let other = v2::Response {
request_id: vec![0; 16],
..resp
};
assert!(open_response(&call, &seal_response(&key, &other)).is_err());
}
#[test]
fn mailbox_auth_checks() {
let keys = ServerKeys::generate();
let info = ServerInfo::from_card(&keys.card("http://s", "s", "", 1)).unwrap();
let mb = SigningKeyPair::generate();
let auth = mailbox_auth(&mb, &info, b"rid", 1000);
let sp = keys.sign.public();
assert_eq!(verify_mailbox_auth(&sp, b"rid", &auth, 1100).unwrap(), mb.public());
assert!(verify_mailbox_auth(&sp, b"other", &auth, 1100).is_err());
assert!(verify_mailbox_auth(&sp, b"rid", &auth, 1000 + AUTH_WINDOW_SECS + 1).is_err());
let other_server = ServerKeys::generate().sign.public();
assert!(verify_mailbox_auth(&other_server, b"rid", &auth, 1000).is_err());
}
}
+121
View File
@@ -0,0 +1,121 @@
//! Server cards and server key material.
use meow_crypto::{DhKeyPair, DhPublic, SignPublic, SigningKeyPair};
use meow_proto::{v2, Message, PROTOCOL_VERSION};
use serde::{Deserialize, Serialize};
use crate::{proto_err, Result};
/// Normalise a server URL (no trailing slash).
pub fn canonical_url(url: &str) -> String {
url.trim().trim_end_matches('/').to_string()
}
/// A verified server card, as known by clients.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerInfo {
pub url: String,
pub name: String,
pub description: String,
pub sign_key: SignPublic,
pub dh_key: DhPublic,
pub issued_at: u64,
pub signature: Vec<u8>,
}
fn signed_bytes(card: &v2::ServerCard) -> Vec<u8> {
let mut c = card.clone();
c.signature.clear();
[b"meow/v2/server-card".as_slice(), &c.encode_to_vec()].concat()
}
impl ServerInfo {
/// Parse and verify a self-signed card.
pub fn from_card(card: &v2::ServerCard) -> Result<Self> {
if card.version != PROTOCOL_VERSION {
return Err(proto_err("unsupported server card version"));
}
let sign_key = SignPublic::from_slice(&card.sign_key)?;
sign_key.verify(&signed_bytes(card), &card.signature)?;
Ok(Self {
url: canonical_url(&card.url),
name: card.name.clone(),
description: card.description.clone(),
sign_key,
dh_key: DhPublic::from_slice(&card.dh_key)?,
issued_at: card.issued_at,
signature: card.signature.clone(),
})
}
pub fn from_bytes(b: &[u8]) -> Result<Self> {
Self::from_card(&v2::ServerCard::decode(b)?)
}
pub fn to_card(&self) -> v2::ServerCard {
v2::ServerCard {
version: PROTOCOL_VERSION,
name: self.name.clone(),
description: self.description.clone(),
url: self.url.clone(),
sign_key: self.sign_key.to_vec(),
dh_key: self.dh_key.to_vec(),
issued_at: self.issued_at,
signature: self.signature.clone(),
}
}
/// Same server keys (used to detect key changes when re-fetching a card).
pub fn same_keys(&self, other: &ServerInfo) -> bool {
self.sign_key == other.sign_key && self.dh_key == other.dh_key
}
}
/// Private key material of a server.
#[derive(Clone, Serialize, Deserialize)]
pub struct ServerKeys {
pub sign: SigningKeyPair,
pub dh: DhKeyPair,
}
impl ServerKeys {
pub fn generate() -> Self {
Self {
sign: SigningKeyPair::generate(),
dh: DhKeyPair::generate(),
}
}
/// Build the self-signed card for this server.
pub fn card(&self, url: &str, name: &str, description: &str, now: u64) -> v2::ServerCard {
let mut card = v2::ServerCard {
version: PROTOCOL_VERSION,
name: name.to_string(),
description: description.to_string(),
url: canonical_url(url),
sign_key: self.sign.public().to_vec(),
dh_key: self.dh.public().to_vec(),
issued_at: now,
signature: Vec::new(),
};
card.signature = self.sign.sign(&signed_bytes(&card)).to_vec();
card
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn card_roundtrip_and_tamper() {
let keys = ServerKeys::generate();
let card = keys.card("http://localhost:8080/", "srv", "desc", 42);
let info = ServerInfo::from_card(&card).unwrap();
assert_eq!(info.url, "http://localhost:8080");
assert_eq!(info.to_card(), card);
let mut bad = card.clone();
bad.url = "http://evil".into();
assert!(ServerInfo::from_card(&bad).is_err());
}
}
+121
View File
@@ -0,0 +1,121 @@
//! Full protocol flow without any I/O: invitation then bidirectional messaging.
use meow_core::contact::ContactState;
use meow_core::proto::{peer_envelope, user_message};
use meow_core::server::{ServerInfo, ServerKeys};
use meow_core::{invitation, messaging};
fn server() -> ServerInfo {
ServerInfo::from_card(&ServerKeys::generate().card("http://localhost:8080", "s", "", 1)).unwrap()
}
fn ratchet(env: &meow_core::proto::PeerEnvelope) -> &meow_core::proto::RatchetMessage {
match env.body.as_ref().unwrap() {
peer_envelope::Body::Ratchet(r) => r,
_ => panic!("not a ratchet message"),
}
}
fn text_of(m: &meow_core::proto::UserMessage) -> &str {
match m.body.as_ref().unwrap() {
user_message::Body::Text(t) => &t.text,
_ => panic!("not text"),
}
}
#[test]
fn full_invitation_and_messaging() {
let now = 1_000_000;
let srv = server();
// 1. bob invites alice
let offer = invitation::create_offer("alice", "bob", vec![srv.clone()], "hi!", now, 3600).unwrap();
let mut bob_side = offer.contact;
assert_eq!(bob_side.state, ContactState::OfferSent);
let info = invitation::inspect_offer(&offer.offer_bytes, now).unwrap();
assert_eq!(info.initiator_name, "bob");
assert_eq!(info.message, "hi!");
// 2. alice answers
let (mut alice_side, answer) =
invitation::answer(&offer.offer_bytes, "bob", "alice", vec![srv.clone()], now).unwrap();
assert_eq!(alice_side.state, ContactState::AnswerSent);
assert!(!alice_side.can_send());
// 3. bob accepts: he can send right away
let confirm = invitation::accept(&mut bob_side, &answer, now).unwrap();
assert_eq!(bob_side.state, ContactState::ConfirmSent);
let early = messaging::encrypt(&mut bob_side, &messaging::text("early bird", 1)).unwrap();
// 4. alice finalizes and produces the ack
let ack = invitation::finalize(&mut alice_side, &confirm).unwrap();
assert_eq!(alice_side.state, ContactState::Active);
assert_eq!(alice_side.transcript, bob_side.transcript);
assert_eq!(alice_side.safety_number(), bob_side.safety_number());
// the early message is readable after finalisation
let m = messaging::decrypt(&mut alice_side, ratchet(&early)).unwrap();
assert_eq!(text_of(&m), "early bird");
// bob gets the ack → active
messaging::decrypt(&mut bob_side, ratchet(&ack)).unwrap();
assert_eq!(bob_side.state, ContactState::Active);
// conversation
for i in 0..3 {
let e = messaging::encrypt(&mut alice_side, &messaging::text(&format!("a{i}"), 2)).unwrap();
assert_eq!(
text_of(&messaging::decrypt(&mut bob_side, ratchet(&e)).unwrap()),
format!("a{i}")
);
let e = messaging::encrypt(&mut bob_side, &messaging::text(&format!("b{i}"), 3)).unwrap();
assert_eq!(
text_of(&messaging::decrypt(&mut alice_side, ratchet(&e)).unwrap()),
format!("b{i}")
);
}
// deposits target the peer's mailbox
let d = messaging::deposit_for(&bob_side, &early).unwrap();
assert_eq!(d.mailbox, alice_side.keys.as_ref().unwrap().mailbox.public().to_vec());
}
#[test]
fn tampered_answer_is_rejected() {
let now = 10;
let srv = server();
let offer = invitation::create_offer("alice", "bob", vec![srv.clone()], "", now, 60).unwrap();
let mut bob_side = offer.contact;
let (_, mut answer) = invitation::answer(&offer.offer_bytes, "bob", "alice", vec![srv.clone()], now).unwrap();
let sealed = answer.sealed.as_mut().unwrap();
let n = sealed.ciphertext.len();
sealed.ciphertext[n - 1] ^= 1;
assert!(invitation::accept(&mut bob_side, &answer, now).is_err());
assert_eq!(bob_side.state, ContactState::OfferSent);
}
#[test]
fn confirm_for_another_invitee_is_rejected() {
let now = 10;
let srv = server();
let offer = invitation::create_offer("alice", "bob", vec![srv.clone()], "", now, 60).unwrap();
let mut bob_side = offer.contact;
let (mut alice_side, answer) =
invitation::answer(&offer.offer_bytes, "bob", "alice", vec![srv.clone()], now).unwrap();
// mallory answers the same offer too; bob accepts mallory's answer
let (_, mallory_answer) = invitation::answer(&offer.offer_bytes, "bob", "mallory", vec![srv.clone()], now).unwrap();
let confirm = invitation::accept(&mut bob_side, &mallory_answer, now).unwrap();
// the confirm is sealed to mallory: alice cannot use it
assert!(invitation::finalize(&mut alice_side, &confirm).is_err());
assert_eq!(alice_side.state, ContactState::AnswerSent);
// and bob cannot accept twice
assert!(invitation::accept(&mut bob_side, &answer, now).is_err());
}
#[test]
fn expired_offer() {
let srv = server();
let offer = invitation::create_offer("alice", "bob", vec![srv.clone()], "", 100, 10).unwrap();
assert!(invitation::inspect_offer(&offer.offer_bytes, 111).is_err());
assert!(invitation::answer(&offer.offer_bytes, "bob", "alice", vec![srv], 111).is_err());
}