Files
meow/crates/meow-client/src/lib.rs
T

831 lines
32 KiB
Rust
Raw Normal View History

2026-11-20 21:47:33 +01:00
//! High-level async client API for Meow v2.
//!
//! [`MeowClient`] owns one identity (profile) and exposes servers, contacts,
//! invitations, messaging and synchronisation. It is the API mirrored by the CLI
//! and, later, by the Flutter FFI layer (`meow-ffi`).
//!
//! Invariant: any ratchet/contact state change is **persisted before** the
//! resulting bytes leave the device, so a crash can never make us reuse a key.
#![forbid(unsafe_code)]
#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))]
pub mod profile;
pub mod transport;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use futures_util::future::join_all;
use meow_core::contact::{Contact, ContactState};
use meow_core::invitation::{self, OfferInfo};
use meow_core::server::{canonical_url, ServerInfo};
use meow_core::{messaging, rpc};
use meow_crypto::password::KdfParams;
use meow_crypto::{SignPublic, SigningKeyPair};
use meow_proto::v2::{self, request::Body as Req, response::Body as Resp};
use meow_proto::Message;
pub use meow_core::contact::ContactState as State;
use profile::RetiredMailbox;
pub use profile::{Content, HistoryEntry, PendingAck};
2026-11-20 21:47:33 +01:00
/// Maximum file size sent in a single message (chunking: roadmap 5.7).
pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
/// Default invitation lifetime.
pub const DEFAULT_INVITATION_TTL: u64 = 7 * 86_400;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("wrong password or corrupted identity file")]
BadPassword,
#[error("corrupted identity file: {0}")]
Corrupted(String),
#[error("i/o: {0}")]
Io(#[from] std::io::Error),
#[error("network: {0}")]
Network(String),
#[error(transparent)]
Protocol(#[from] meow_core::Error),
#[error("crypto: {0}")]
Crypto(#[from] meow_crypto::CryptoError),
#[error("unknown server: {0}")]
UnknownServer(String),
#[error("server {0} changed its keys: refusing (remove and re-add it if this is expected)")]
ServerKeyChanged(String),
#[error("unknown contact: {0}")]
UnknownContact(String),
#[error("a contact named {0:?} already exists")]
NameTaken(String),
#[error("{0}")]
Invalid(String),
#[error("identity {0} is in use by another process")]
Locked(String),
}
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
/// Something that happened during [`MeowClient::sync`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
/// Initiator side: the invitee answered a server-published invitation; the
/// confirmation has been sent automatically.
InvitationAccepted { contact: String },
/// The handshake is complete on this side.
ContactActivated { contact: String },
Message {
contact: String,
id: Vec<u8>,
text: String,
sent_at_ms: u64,
},
File {
contact: String,
name: String,
data: Vec<u8>,
},
}
/// Outcome of a send.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendReport {
pub message_id: Vec<u8>,
/// Number of servers that accepted the deposit.
pub delivered_to: usize,
}
/// One identity, with its servers, contacts and history.
/// Acknowledged ids sent per mailbox and pull (server limit: 1024).
const MAX_ACKS_PER_MAILBOX: usize = 512;
#[derive(Default)]
struct PullRound {
/// Messages to process.
new: Vec<v2::StoredMessage>,
/// A server held messages back.
more: bool,
}
2026-11-20 21:47:33 +01:00
pub struct MeowClient {
path: PathBuf,
password: String,
kdf: KdfParams,
profile: profile::Profile,
transport: transport::Transport,
/// Exclusive OS lock on `<identity>.lock`, held for the client's lifetime:
/// two processes saving the same ratchet state would roll sessions back.
_lock: std::fs::File,
}
fn lock_identity(path: &Path) -> Result<std::fs::File> {
let mut lock_path = path.as_os_str().to_owned();
lock_path.push(".lock");
let f = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(PathBuf::from(lock_path))?;
match f.try_lock() {
Ok(()) => Ok(f),
Err(std::fs::TryLockError::WouldBlock) => Err(Error::Locked(path.display().to_string())),
Err(std::fs::TryLockError::Error(e)) => Err(Error::Io(e)),
}
}
impl MeowClient {
// ───────────────────────── lifecycle ─────────────────────────
/// Create a new identity file. Fails if it exists, unless `overwrite`.
pub async fn create(path: &Path, nickname: &str, password: &str, kdf: KdfParams, overwrite: bool) -> Result<Self> {
if !overwrite && path.exists() {
return Err(Error::Invalid(format!(
"{} already exists (use --force)",
path.display()
)));
}
let c = Self {
path: path.to_path_buf(),
password: password.to_string(),
kdf,
profile: profile::Profile::new(nickname),
transport: transport::Transport::new()?,
_lock: lock_identity(path)?,
};
c.save().await?;
Ok(c)
}
/// Open an existing identity file. `kdf` is used for subsequent saves.
pub async fn open(path: &Path, password: &str, kdf: KdfParams) -> Result<Self> {
Ok(Self {
path: path.to_path_buf(),
password: password.to_string(),
kdf,
_lock: lock_identity(path)?,
profile: profile::Profile::load(path, password).await?,
transport: transport::Transport::new()?,
})
}
pub async fn save(&self) -> Result<()> {
self.profile.save(&self.path, &self.password, self.kdf).await
}
pub fn nickname(&self) -> &str {
&self.profile.nickname
}
// ───────────────────────── servers ─────────────────────────
/// Add a server: fetch its card, verify it and pin its keys (TOFU).
pub async fn add_server(&mut self, url: &str) -> Result<ServerInfo> {
let info = self.transport.fetch_card(url).await?;
if canonical_url(url) != info.url {
tracing::warn!("server announces {} (contacted as {url})", info.url);
}
if let Some(known) = self
.profile
.servers
.iter()
.find(|s| s.url == info.url || s.sign_key == info.sign_key)
{
if !known.same_keys(&info) {
return Err(Error::ServerKeyChanged(info.url));
}
return Ok(known.clone());
}
self.profile.servers.push(info.clone());
self.save().await?;
Ok(info)
}
pub fn servers(&self) -> &[ServerInfo] {
&self.profile.servers
}
pub async fn remove_server(&mut self, url_or_name: &str) -> Result<()> {
let u = canonical_url(url_or_name);
let before = self.profile.servers.len();
self.profile.servers.retain(|s| s.url != u && s.name != url_or_name);
if self.profile.servers.len() == before {
return Err(Error::UnknownServer(url_or_name.to_string()));
}
self.save().await
}
/// Resolve URLs to known servers; an empty list means "all my servers".
fn resolve_servers(&self, urls: &[String]) -> Result<Vec<ServerInfo>> {
if urls.is_empty() {
if self.profile.servers.is_empty() {
return Err(Error::Invalid("no server configured: add one first".into()));
}
return Ok(self.profile.servers.clone());
}
urls.iter()
.map(|u| {
let cu = canonical_url(u);
self.profile
.servers
.iter()
.find(|s| s.url == cu || s.name == *u)
.cloned()
.ok_or_else(|| Error::UnknownServer(u.clone()))
})
.collect()
}
// ───────────────────────── contacts ─────────────────────────
pub fn contacts(&self) -> &[Contact] {
&self.profile.contacts
}
pub fn contact(&self, name: &str) -> Result<&Contact> {
self.profile
.contacts
.iter()
.find(|c| c.name == name)
.ok_or_else(|| Error::UnknownContact(name.to_string()))
}
fn contact_index(&self, name: &str) -> Result<usize> {
self.profile
.contacts
.iter()
.position(|c| c.name == name)
.ok_or_else(|| Error::UnknownContact(name.to_string()))
}
fn ensure_free_name(&self, name: &str) -> Result<()> {
if self.profile.contacts.iter().any(|c| c.name == name) {
return Err(Error::NameTaken(name.to_string()));
}
Ok(())
}
pub async fn remove_contact(&mut self, name: &str) -> Result<()> {
let i = self.contact_index(name)?;
let before = self.contact_mailboxes();
2026-11-20 21:47:33 +01:00
let c = self.profile.contacts.remove(i);
self.profile.history.retain(|h| h.contact != c.id);
self.retire_mailboxes(before);
2026-11-20 21:47:33 +01:00
self.save().await
}
pub fn history(&self, name: &str) -> Result<Vec<&HistoryEntry>> {
let id = &self.contact(name)?.id;
Ok(self.profile.history.iter().filter(|h| &h.contact == id).collect())
}
// ───────────────────────── invitations ─────────────────────────
/// Step 1: create an invitation for `contact_name`. Returns the encoded offer.
pub async fn create_invitation(
&mut self,
contact_name: &str,
server_urls: &[String],
message: &str,
ttl: u64,
) -> Result<Vec<u8>> {
self.ensure_free_name(contact_name)?;
let servers = self.resolve_servers(server_urls)?;
let offer = invitation::create_offer(contact_name, &self.profile.nickname, servers, message, now(), ttl)?;
self.profile.contacts.push(offer.contact);
self.save().await?;
Ok(offer.offer_bytes)
}
pub fn inspect_invitation(&self, offer_bytes: &[u8]) -> Result<OfferInfo> {
Ok(invitation::inspect_offer(offer_bytes, now())?)
}
/// Step 2: answer an offer. Returns the encoded answer (file flow).
pub async fn answer_invitation(
&mut self,
offer_bytes: &[u8],
contact_name: Option<&str>,
server_urls: &[String],
) -> Result<Vec<u8>> {
let info = self.inspect_invitation(offer_bytes)?;
let name = contact_name.unwrap_or(&info.initiator_name).to_string();
self.ensure_free_name(&name)?;
if self
.profile
.contacts
.iter()
.any(|c| c.invitation_id == info.invitation_id)
{
return Err(Error::Invalid("this invitation was already answered".into()));
}
let servers = self.resolve_servers(server_urls)?;
let (contact, answer) = invitation::answer(offer_bytes, &name, &self.profile.nickname, servers, now())?;
self.profile.contacts.push(contact);
self.save().await?;
Ok(answer.encode_to_vec())
}
fn by_invitation(&mut self, id: &[u8]) -> Result<&mut Contact> {
self.profile
.contacts
.iter_mut()
.find(|c| c.invitation_id.as_slice() == id)
.ok_or_else(|| Error::Invalid("no pending invitation matches".into()))
}
/// Step 3 (file flow): process an answer, returns the encoded confirmation.
pub async fn accept_answer(&mut self, answer_bytes: &[u8]) -> Result<Vec<u8>> {
let msg = v2::InvitationMessage::decode(answer_bytes).map_err(meow_core::Error::from)?;
let contact = self.by_invitation(&msg.invitation_id)?;
let confirm = invitation::accept(contact, &msg, now())?;
self.save().await?;
Ok(confirm.encode_to_vec())
}
/// Step 4 (file flow): process a confirmation and send the ack through the network.
pub async fn finalize_invitation(&mut self, confirm_bytes: &[u8]) -> Result<String> {
let msg = v2::InvitationMessage::decode(confirm_bytes).map_err(meow_core::Error::from)?;
let contact = self.by_invitation(&msg.invitation_id)?;
let ack = invitation::finalize(contact, &msg)?;
let deposit = messaging::deposit_for(contact, &ack)?;
let servers = contact
.peer
.as_ref()
.map(|p| p.pull_servers.clone())
.unwrap_or_default();
let name = contact.name.clone();
self.save().await?;
self.deliver(&servers, vec![deposit]).await?;
Ok(name)
}
/// Step 1 through a server: publish the offer and return its URL
/// (`<server>/inv/<shortcode>`).
pub async fn publish_invitation(
&mut self,
contact_name: &str,
server_urls: &[String],
message: &str,
password: &str,
ttl: u64,
) -> Result<String> {
let offer = self.create_invitation(contact_name, server_urls, message, ttl).await?;
let server = self.resolve_servers(server_urls)?.remove(0);
let resp = self
.transport
.call(
&server,
Req::InvPublish(v2::InvitationPublish {
payload: offer,
ttl_seconds: ttl.min(u32::MAX as u64) as u32,
shortcode_len: 10,
password: password.to_string(),
}),
Duration::ZERO,
)
.await?;
match resp {
Resp::InvPublished(p) => Ok(format!("{}/inv/{}", server.url, p.shortcode)),
_ => Err(Error::Network("unexpected response".into())),
}
}
/// Step 2 through a server: fetch an offer by URL, answer it and post the answer
/// in the initiator's answer mailbox. Returns the initiator's name.
pub async fn accept_published_invitation(
&mut self,
url: &str,
password: &str,
contact_name: Option<&str>,
server_urls: &[String],
) -> Result<String> {
let (base, code) = url
.rsplit_once("/inv/")
.ok_or_else(|| Error::Invalid("invitation URL must look like <server>/inv/<code>".into()))?;
let server = self.transport.fetch_card(base).await?;
let resp = self
.transport
.call(
&server,
Req::InvFetch(v2::InvitationFetch {
shortcode: code.to_string(),
password: password.to_string(),
}),
Duration::ZERO,
)
.await?;
let Resp::InvFetched(f) = resp else {
return Err(Error::Network("unexpected response".into()));
};
let info = self.inspect_invitation(&f.payload)?;
let answer_bytes = self.answer_invitation(&f.payload, contact_name, server_urls).await?;
let answer = v2::InvitationMessage::decode(answer_bytes.as_slice()).map_err(meow_core::Error::from)?;
self.deliver(&info.answer_servers, vec![invitation::answer_deposit(&info, &answer)])
.await?;
Ok(info.initiator_name)
}
// ───────────────────────── messaging ─────────────────────────
pub async fn send_text(&mut self, contact_name: &str, text: &str) -> Result<SendReport> {
let msg = messaging::text(text, now_ms());
self.send(contact_name, msg, Content::Text(text.to_string())).await
}
pub async fn send_file(&mut self, contact_name: &str, path: &Path) -> Result<SendReport> {
let data = tokio::fs::read(path).await?;
if data.len() > MAX_FILE_BYTES {
return Err(Error::Invalid(format!("file larger than {MAX_FILE_BYTES} bytes")));
}
let name = path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.ok_or_else(|| Error::Invalid("bad file name".into()))?;
let size = data.len() as u64;
let body = v2::user_message::Body::File(v2::FileBody {
filename: name.clone(),
size,
chunk: 0,
chunks: 1,
data,
mime: String::new(),
});
self.send(
contact_name,
messaging::new_message(body, now_ms()),
Content::File { name, size },
)
.await
}
async fn send(&mut self, contact_name: &str, msg: v2::UserMessage, content: Content) -> Result<SendReport> {
let i = self.contact_index(contact_name)?;
let contact = &mut self.profile.contacts[i];
let env = messaging::encrypt(contact, &msg)?;
let deposit = messaging::deposit_for(contact, &env)?;
let servers = contact
.peer
.as_ref()
.map(|p| p.pull_servers.clone())
.unwrap_or_default();
self.profile.history.push(HistoryEntry {
id: msg.id.clone(),
contact: contact.id.clone(),
outbound: true,
sent_at_ms: msg.sent_at_ms,
received_at: now(),
content,
});
self.save().await?;
let delivered_to = self.deliver(&servers, vec![deposit]).await?;
Ok(SendReport {
message_id: msg.id,
delivered_to,
})
}
/// Post deposits to every server; succeeds if at least one accepted them.
async fn deliver(&self, servers: &[ServerInfo], deposits: Vec<v2::Deposit>) -> Result<usize> {
if servers.is_empty() {
return Err(Error::Invalid("contact has no server".into()));
}
let calls = servers.iter().map(|s| {
self.transport.call(
s,
Req::Post(v2::Post {
deposits: deposits.clone(),
}),
Duration::ZERO,
)
});
let mut ok = 0;
let mut last_err = None;
for (s, r) in servers.iter().zip(join_all(calls).await) {
match r {
Ok(Resp::PostAck(_)) => ok += 1,
Ok(_) => last_err = Some(Error::Network(format!("{}: unexpected response", s.url))),
Err(e) => {
tracing::warn!("deposit on {} failed: {e}", s.url);
last_err = Some(e);
}
}
}
match (ok, last_err) {
(0, Some(e)) => Err(e),
(n, _) => Ok(n),
}
}
// ───────────────────────── sync ─────────────────────────
/// Pull every mailbox on every server (one request per server), process what
/// arrived and return the resulting events. With `wait > 0` the servers hold the
/// request until something arrives or the delay expires (long-poll).
///
/// Delivery is at-least-once: servers keep messages until they are acknowledged,
/// and a message is acknowledged (in the next pull) only once its effects are saved.
/// After a round that brought messages, `sync` pulls again without waiting, which
/// sends the acknowledgements and fetches what the servers held back.
2026-11-20 21:47:33 +01:00
pub async fn sync(&mut self, wait: Duration) -> Result<Vec<Event>> {
const MAX_ROUNDS: usize = 16;
let mut events = Vec::new();
let mut wait = wait;
for round in 0..MAX_ROUNDS {
let r = match self.pull_round(wait).await {
Ok(r) => r,
// A later round only flushes acks and backlog: keep what we already got.
Err(e) if round > 0 => {
tracing::warn!("follow-up pull failed: {e}");
break;
2026-11-20 21:47:33 +01:00
}
Err(e) => return Err(e),
};
let got_new = !r.new.is_empty();
if got_new {
events.extend(self.process(r.new).await?);
}
// Pull again (without waiting) only to acknowledge what just arrived and to
// fetch what servers held back. Redeliveries alone do not loop.
if !got_new && !r.more {
break;
}
wait = Duration::ZERO;
}
Ok(events)
}
/// One pull per server, carrying the pending acks. New (not yet processed) messages
/// are returned and recorded as pending acks; they are saved by [`Self::process`].
async fn pull_round(&mut self, wait: Duration) -> Result<PullRound> {
// server (by signing key) → (server, mailbox keys)
let pending = &self.profile.pending_acks;
self.profile.retired_mailboxes.retain(|r| {
pending
.iter()
.any(|a| a.mailbox.as_slice() == r.key.public().as_bytes().as_slice())
});
let mut jobs: BTreeMap<SignPublic, (ServerInfo, Vec<SigningKeyPair>)> = BTreeMap::new();
let retired = self
.profile
.retired_mailboxes
.iter()
.map(|r| (r.key.clone(), r.servers.clone()));
for (kp, servers) in self.contact_mailboxes().into_iter().chain(retired) {
for s in servers {
jobs.entry(s.sign_key)
.or_insert_with(|| (s.clone(), Vec::new()))
.1
.push(kp.clone());
2026-11-20 21:47:33 +01:00
}
}
// Drop acks nobody can send any more (contact or server removed).
self.profile.pending_acks.retain(|a| {
jobs.get(&a.server).is_some_and(|(_, kps)| {
kps.iter()
.any(|kp| kp.public().as_bytes().as_slice() == a.mailbox.as_slice())
})
});
let mut round = PullRound::default();
2026-11-20 21:47:33 +01:00
if jobs.is_empty() {
return Ok(round);
2026-11-20 21:47:33 +01:00
}
let wait_s = wait.as_secs().min(u32::MAX as u64) as u32;
let pending = &self.profile.pending_acks;
let mut sent_acks: Vec<Vec<PendingAck>> = Vec::with_capacity(jobs.len());
let mut requests = Vec::with_capacity(jobs.len());
for (server, kps) in jobs.values() {
2026-11-20 21:47:33 +01:00
let rid = meow_crypto::random_bytes::<16>().to_vec();
let ts = now();
let mut sent = Vec::new();
let auths = kps
.iter()
.map(|kp| {
let mb = kp.public();
let acks: Vec<Vec<u8>> = pending
.iter()
.filter(|a| a.server == server.sign_key && a.mailbox.as_slice() == mb.as_bytes().as_slice())
.take(MAX_ACKS_PER_MAILBOX)
.inspect(|a| sent.push((*a).clone()))
.map(|a| a.id.clone())
.collect();
rpc::mailbox_auth(kp, server, &rid, acks, ts)
})
.collect();
sent_acks.push(sent);
requests.push(v2::Request {
2026-11-20 21:47:33 +01:00
request_id: rid,
timestamp: ts,
body: Some(Req::Pull(v2::Pull {
auths,
wait_seconds: wait_s,
})),
});
}
let calls = jobs
.values()
.zip(requests)
.map(|((server, _), req)| self.transport.call_request(server, req, wait));
2026-11-20 21:47:33 +01:00
let results = join_all(calls).await;
let mut failures = 0;
let mut last_err = None;
for (((server, _), r), sent) in jobs.values().zip(results).zip(sent_acks) {
2026-11-20 21:47:33 +01:00
match r {
Ok(Resp::PullResult(p)) => {
// The server applied our acks before answering. Forgetting them
// needs no save: at worst they are sent again (acks are idempotent).
self.profile.pending_acks.retain(|a| !sent.contains(a));
round.more |= p.more;
for m in p.messages {
let ack = PendingAck {
server: server.sign_key,
mailbox: m.mailbox.clone(),
id: m.id.clone(),
};
// Already processed (its ack was lost): only re-acknowledge.
if !self.profile.pending_acks.contains(&ack) {
self.profile.pending_acks.push(ack);
round.new.push(m);
}
}
}
2026-11-20 21:47:33 +01:00
Ok(_) => failures += 1,
Err(e) => {
tracing::warn!("pull on {} failed: {e}", server.url);
failures += 1;
last_err = Some(e);
}
}
}
if failures == jobs.len() {
return Err(last_err.unwrap_or_else(|| Error::Network("all servers failed".into())));
}
Ok(round)
}
/// Every mailbox currently used by a contact, with its pull servers.
fn contact_mailboxes(&self) -> Vec<(SigningKeyPair, Vec<ServerInfo>)> {
self.profile
.contacts
.iter()
.flat_map(|c| c.mailboxes())
.map(|(kp, servers)| (kp.clone(), servers.to_vec()))
.collect()
}
/// Keep the keys of mailboxes that disappeared (`before` → now) while they still
/// have pending acks, so the next pull can acknowledge their last messages.
fn retire_mailboxes(&mut self, before: Vec<(SigningKeyPair, Vec<ServerInfo>)>) {
let current: Vec<SignPublic> = self.contact_mailboxes().iter().map(|(kp, _)| kp.public()).collect();
for (key, servers) in before {
let pk = key.public();
let has_acks = self
.profile
.pending_acks
.iter()
.any(|a| a.mailbox.as_slice() == pk.as_bytes().as_slice());
let known = self.profile.retired_mailboxes.iter().any(|r| r.key.public() == pk);
if has_acks && !known && !current.contains(&pk) {
self.profile.retired_mailboxes.push(RetiredMailbox { key, servers });
}
}
2026-11-20 21:47:33 +01:00
}
async fn process(&mut self, stored: Vec<v2::StoredMessage>) -> Result<Vec<Event>> {
let mailboxes_before = self.contact_mailboxes();
2026-11-20 21:47:33 +01:00
// Handshake messages first (step 2 before step 3), then ratchet messages by arrival.
let mut envs: Vec<(u32, u64, Vec<u8>, v2::PeerEnvelope)> = stored
.into_iter()
.filter_map(|m| {
let env = v2::PeerEnvelope::decode(m.payload.as_slice()).ok()?;
let rank = match &env.body {
Some(v2::peer_envelope::Body::Invitation(i)) => i.step,
_ => 10,
};
Some((rank, m.received_at, m.mailbox, env))
})
.collect();
envs.sort_by_key(|(rank, at, _, _)| (*rank, *at));
let mut events = Vec::new();
let mut outgoing: Vec<(Vec<ServerInfo>, v2::Deposit)> = Vec::new();
for (_, received_at, mailbox, env) in envs {
let Some(i) = self.profile.contacts.iter().position(|c| {
c.mailboxes()
.iter()
.any(|(kp, _)| kp.public().as_bytes().as_slice() == mailbox.as_slice())
}) else {
tracing::debug!("message for an unknown mailbox");
continue;
};
let contact = &mut self.profile.contacts[i];
match env.body {
Some(v2::peer_envelope::Body::Invitation(inv)) if inv.step == 2 => {
match invitation::accept(contact, &inv, now()) {
Ok(confirm) => {
let servers = contact
.peer
.as_ref()
.map(|p| p.pull_servers.clone())
.unwrap_or_default();
outgoing.push((servers, invitation::confirm_deposit(contact, &confirm)?));
events.push(Event::InvitationAccepted {
contact: contact.name.clone(),
});
}
Err(e) => tracing::debug!("ignoring answer: {e}"),
}
}
Some(v2::peer_envelope::Body::Invitation(inv)) if inv.step == 3 => {
match invitation::finalize(contact, &inv) {
Ok(ack) => {
let servers = contact
.peer
.as_ref()
.map(|p| p.pull_servers.clone())
.unwrap_or_default();
outgoing.push((servers, messaging::deposit_for(contact, &ack)?));
events.push(Event::ContactActivated {
contact: contact.name.clone(),
});
}
Err(e) => tracing::debug!("ignoring confirmation: {e}"),
}
}
Some(v2::peer_envelope::Body::Ratchet(rm)) => {
let was = contact.state;
let msg = match messaging::decrypt(contact, &rm) {
Ok(m) => m,
// Typically the same deposit received from a second server.
Err(e) => {
tracing::debug!("dropping undecryptable message: {e}");
continue;
}
};
let name = contact.name.clone();
let cid = contact.id.clone();
if was != ContactState::Active && contact.state == ContactState::Active {
events.push(Event::ContactActivated { contact: name.clone() });
}
let mut record = |content| {
self.profile.history.push(HistoryEntry {
id: msg.id.clone(),
contact: cid.clone(),
outbound: false,
sent_at_ms: msg.sent_at_ms,
received_at,
content,
})
};
match &msg.body {
Some(v2::user_message::Body::Text(t)) => {
record(Content::Text(t.text.clone()));
events.push(Event::Message {
contact: name,
id: msg.id.clone(),
text: t.text.clone(),
sent_at_ms: msg.sent_at_ms,
});
}
Some(v2::user_message::Body::File(f)) => {
record(Content::File {
name: f.filename.clone(),
size: f.size,
});
events.push(Event::File {
contact: name,
name: f.filename.clone(),
data: f.data.clone(),
});
}
_ => {}
}
}
_ => tracing::debug!("ignoring unsupported envelope"),
}
}
self.retire_mailboxes(mailboxes_before);
2026-11-20 21:47:33 +01:00
// Persist before anything leaves the device.
self.save().await?;
for (servers, deposit) in outgoing {
if let Err(e) = self.deliver(&servers, vec![deposit]).await {
tracing::warn!("could not deliver handshake message: {e}");
}
}
Ok(events)
}
}