first commit
This commit is contained in:
commit
6d3ea3e2a6
43 files changed
+8204
No files matched your search
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "meow-client"
|
||||
description = "Meow v2 high-level async client API"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
meow-core = { path = "../meow-core" }
|
||||
meow-proto = { path = "../meow-proto" }
|
||||
meow-crypto = { path = "../meow-crypto" }
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
|
||||
tokio = { version = "1", features = ["fs", "time", "macros"] }
|
||||
futures-util = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
postcard = { version = "1", default-features = false, features = ["alloc"] }
|
||||
thiserror = "2"
|
||||
tracing = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
meow-server = { path = "../meow-server" }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,698 @@
|
||||
//! 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;
|
||||
pub use profile::{Content, HistoryEntry};
|
||||
|
||||
/// 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.
|
||||
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 c = self.profile.contacts.remove(i);
|
||||
self.profile.history.retain(|h| h.contact != c.id);
|
||||
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).
|
||||
pub async fn sync(&mut self, wait: Duration) -> Result<Vec<Event>> {
|
||||
// server (by signing key) → (server, mailbox keys)
|
||||
let mut jobs: BTreeMap<SignPublic, (ServerInfo, Vec<SigningKeyPair>)> = BTreeMap::new();
|
||||
for c in &self.profile.contacts {
|
||||
for (kp, servers) in c.mailboxes() {
|
||||
for s in servers {
|
||||
jobs.entry(s.sign_key)
|
||||
.or_insert_with(|| (s.clone(), Vec::new()))
|
||||
.1
|
||||
.push(kp.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if jobs.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let wait_s = wait.as_secs().min(u32::MAX as u64) as u32;
|
||||
let calls = jobs.values().map(|(server, kps)| {
|
||||
let rid = meow_crypto::random_bytes::<16>().to_vec();
|
||||
let ts = now();
|
||||
let auths = kps.iter().map(|kp| rpc::mailbox_auth(kp, server, &rid, ts)).collect();
|
||||
let req = v2::Request {
|
||||
request_id: rid,
|
||||
timestamp: ts,
|
||||
body: Some(Req::Pull(v2::Pull {
|
||||
auths,
|
||||
wait_seconds: wait_s,
|
||||
})),
|
||||
};
|
||||
self.transport.call_request(server, req, wait)
|
||||
});
|
||||
let results = join_all(calls).await;
|
||||
|
||||
let mut stored = Vec::new();
|
||||
let mut failures = 0;
|
||||
let mut last_err = None;
|
||||
for ((server, _), r) in jobs.values().zip(results) {
|
||||
match r {
|
||||
Ok(Resp::PullResult(p)) => stored.extend(p.messages),
|
||||
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())));
|
||||
}
|
||||
self.process(stored).await
|
||||
}
|
||||
|
||||
async fn process(&mut self, stored: Vec<v2::StoredMessage>) -> Result<Vec<Event>> {
|
||||
// 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"),
|
||||
}
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Provisional persistence: one encrypted file per identity (`*.mwid2`).
|
||||
//!
|
||||
//! Replaced by the SQLite store of `meow-store` in roadmap phase 4. The whole
|
||||
//! profile is serialised with postcard and encrypted with Argon2id +
|
||||
//! XChaCha20-Poly1305 ([`meow_crypto::password`]).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use meow_core::contact::{Contact, ContactId};
|
||||
use meow_core::server::ServerInfo;
|
||||
use meow_crypto::password::{self, KdfParams};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
const FORMAT_VERSION: u32 = 1;
|
||||
|
||||
/// One entry of a conversation history.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct HistoryEntry {
|
||||
pub id: Vec<u8>,
|
||||
pub contact: ContactId,
|
||||
pub outbound: bool,
|
||||
pub sent_at_ms: u64,
|
||||
pub received_at: u64,
|
||||
pub content: Content,
|
||||
}
|
||||
|
||||
/// Displayable content of a message.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum Content {
|
||||
Text(String),
|
||||
File { name: String, size: u64 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct Profile {
|
||||
pub format: u32,
|
||||
pub nickname: String,
|
||||
pub servers: Vec<ServerInfo>,
|
||||
pub contacts: Vec<Contact>,
|
||||
pub history: Vec<HistoryEntry>,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn new(nickname: &str) -> Self {
|
||||
Self {
|
||||
format: FORMAT_VERSION,
|
||||
nickname: nickname.to_string(),
|
||||
servers: vec![],
|
||||
contacts: vec![],
|
||||
history: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn load(path: &Path, password: &str) -> Result<Self> {
|
||||
let blob = tokio::fs::read(path).await?;
|
||||
let plain = password::decrypt(password.as_bytes(), &blob).map_err(|_| Error::BadPassword)?;
|
||||
let p: Profile = postcard::from_bytes(&plain).map_err(|e| Error::Corrupted(e.to_string()))?;
|
||||
if p.format != FORMAT_VERSION {
|
||||
return Err(Error::Corrupted(format!("unsupported profile format {}", p.format)));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Atomic save (write to a temporary file then rename).
|
||||
pub async fn save(&self, path: &Path, password: &str, kdf: KdfParams) -> Result<()> {
|
||||
let plain = postcard::to_allocvec(self).map_err(|e| Error::Corrupted(e.to_string()))?;
|
||||
let blob = password::encrypt(password.as_bytes(), &plain, kdf)?;
|
||||
let tmp = path.with_extension("tmp");
|
||||
tokio::fs::write(&tmp, blob).await?;
|
||||
tokio::fs::rename(&tmp, path).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! HTTP transport to meow servers.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use meow_core::rpc;
|
||||
use meow_core::server::{canonical_url, ServerInfo};
|
||||
use meow_proto::v2::{request::Body as Req, response::Body as Resp};
|
||||
|
||||
use crate::{now, Error, Result};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Transport {
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
pub fn new() -> Result<Self> {
|
||||
let http = reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_secs(10))
|
||||
.user_agent("meow/2")
|
||||
.build()
|
||||
.map_err(|e| Error::Network(e.to_string()))?;
|
||||
Ok(Self { http })
|
||||
}
|
||||
|
||||
/// Download and verify a server card.
|
||||
pub async fn fetch_card(&self, url: &str) -> Result<ServerInfo> {
|
||||
let url = canonical_url(url);
|
||||
let resp = self
|
||||
.http
|
||||
.get(format!("{url}/v2/card"))
|
||||
.timeout(Duration::from_secs(20))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Error::Network(e.to_string()))?
|
||||
.error_for_status()
|
||||
.map_err(|e| Error::Network(e.to_string()))?;
|
||||
let bytes = resp.bytes().await.map_err(|e| Error::Network(e.to_string()))?;
|
||||
Ok(ServerInfo::from_bytes(&bytes)?)
|
||||
}
|
||||
|
||||
/// One sealed RPC. `wait` extends the HTTP timeout for long-polls.
|
||||
pub async fn call(&self, server: &ServerInfo, body: Req, wait: Duration) -> Result<Resp> {
|
||||
let req = rpc::new_request(body, now());
|
||||
self.call_request(server, req, wait).await
|
||||
}
|
||||
|
||||
/// Same as [`Transport::call`] with a prepared request (needed when the body
|
||||
/// must be bound to the request id, as for pulls).
|
||||
pub async fn call_request(
|
||||
&self,
|
||||
server: &ServerInfo,
|
||||
req: meow_proto::v2::Request,
|
||||
wait: Duration,
|
||||
) -> Result<Resp> {
|
||||
let (wire, pending) = rpc::seal_request(server, &req)?;
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}/v2/rpc", server.url))
|
||||
.header("content-type", "application/x-protobuf")
|
||||
.timeout(wait + Duration::from_secs(30))
|
||||
.body(wire)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Error::Network(e.to_string()))?
|
||||
.error_for_status()
|
||||
.map_err(|e| Error::Network(e.to_string()))?;
|
||||
let bytes = resp.bytes().await.map_err(|e| Error::Network(e.to_string()))?;
|
||||
Ok(rpc::open_response(&pending, &bytes)?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! End-to-end in-process test: two real HTTP servers (memory store) and three clients.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use meow_client::{Event, MeowClient, State};
|
||||
use meow_crypto::password::KdfParams;
|
||||
use meow_server::store::MemoryStore;
|
||||
use meow_server::{encode_card, AppState, Limits};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
async fn spawn_server() -> String {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let keys = meow_core::server::ServerKeys::generate();
|
||||
let (notify, _) = broadcast::channel(1024);
|
||||
let state = Arc::new(AppState {
|
||||
card: encode_card(&keys, &url, "test", ""),
|
||||
keys,
|
||||
store: Arc::new(MemoryStore::new(notify.clone(), 1000)),
|
||||
notify,
|
||||
limits: Limits::default(),
|
||||
});
|
||||
tokio::spawn(meow_server::serve(listener, state));
|
||||
url
|
||||
}
|
||||
|
||||
fn tmpdir() -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("meow-test-{}", rand_suffix()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn rand_suffix() -> String {
|
||||
meow_crypto::random_bytes::<8>()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn client(dir: &std::path::Path, name: &str, servers: &[String]) -> MeowClient {
|
||||
let mut c = MeowClient::create(
|
||||
&dir.join(format!("{name}.mwid2")),
|
||||
name,
|
||||
"pw",
|
||||
KdfParams::INSECURE_TEST,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for s in servers {
|
||||
c.add_server(s).await.unwrap();
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
fn texts(events: &[Event]) -> Vec<String> {
|
||||
events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::Message { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn file_and_server_invitations_then_messaging() {
|
||||
let s1 = spawn_server().await;
|
||||
let s2 = spawn_server().await;
|
||||
let servers = vec![s1.clone(), s2.clone()];
|
||||
let dir = tmpdir();
|
||||
let mut bob = client(&dir, "bob", &servers).await;
|
||||
let mut alice = client(&dir, "alice", &servers).await;
|
||||
let mut remote = client(&dir, "remote", &servers).await;
|
||||
|
||||
// ── file invitation ──
|
||||
let offer = bob.create_invitation("alice", &[], "hello alice", 3600).await.unwrap();
|
||||
assert_eq!(alice.inspect_invitation(&offer).unwrap().initiator_name, "bob");
|
||||
let answer = alice.answer_invitation(&offer, None, &[]).await.unwrap();
|
||||
let confirm = bob.accept_answer(&answer).await.unwrap();
|
||||
assert_eq!(bob.contact("alice").unwrap().state, State::ConfirmSent);
|
||||
bob.send_text("alice", "sent before finalize").await.unwrap();
|
||||
alice.finalize_invitation(&confirm).await.unwrap();
|
||||
assert_eq!(alice.contact("bob").unwrap().state, State::Active);
|
||||
|
||||
let ev = bob.sync(Duration::ZERO).await.unwrap();
|
||||
assert!(ev.contains(&Event::ContactActivated {
|
||||
contact: "alice".into()
|
||||
}));
|
||||
assert_eq!(bob.contact("alice").unwrap().state, State::Active);
|
||||
|
||||
// ── messaging, delivered on both servers but processed once ──
|
||||
bob.send_text("alice", "hello").await.unwrap();
|
||||
let r = bob.send_text("alice", "again").await.unwrap();
|
||||
assert_eq!(r.delivered_to, 2);
|
||||
let ev = alice.sync(Duration::ZERO).await.unwrap();
|
||||
assert_eq!(texts(&ev), vec!["sent before finalize", "hello", "again"]);
|
||||
assert!(alice.sync(Duration::ZERO).await.unwrap().is_empty());
|
||||
|
||||
alice.send_text("bob", "hi bob").await.unwrap();
|
||||
assert_eq!(texts(&bob.sync(Duration::ZERO).await.unwrap()), vec!["hi bob"]);
|
||||
|
||||
// ── file ──
|
||||
let f = dir.join("note.txt");
|
||||
std::fs::write(&f, b"file content").unwrap();
|
||||
bob.send_file("alice", &f).await.unwrap();
|
||||
let ev = alice.sync(Duration::ZERO).await.unwrap();
|
||||
assert!(ev.contains(&Event::File {
|
||||
contact: "bob".into(),
|
||||
name: "note.txt".into(),
|
||||
data: b"file content".to_vec()
|
||||
}));
|
||||
|
||||
// ── server invitation ──
|
||||
let url = bob
|
||||
.publish_invitation("remote", &[], "via server", "secret", 3600)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(remote
|
||||
.accept_published_invitation(&url, "wrong", None, &[])
|
||||
.await
|
||||
.is_err());
|
||||
let who = remote
|
||||
.accept_published_invitation(&url, "secret", None, &[])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(who, "bob");
|
||||
let ev = bob.sync(Duration::ZERO).await.unwrap();
|
||||
assert_eq!(
|
||||
ev,
|
||||
vec![Event::InvitationAccepted {
|
||||
contact: "remote".into()
|
||||
}]
|
||||
);
|
||||
let ev = remote.sync(Duration::ZERO).await.unwrap();
|
||||
assert_eq!(ev, vec![Event::ContactActivated { contact: "bob".into() }]);
|
||||
let ev = bob.sync(Duration::ZERO).await.unwrap();
|
||||
assert_eq!(
|
||||
ev,
|
||||
vec![Event::ContactActivated {
|
||||
contact: "remote".into()
|
||||
}]
|
||||
);
|
||||
|
||||
// ── long poll ──
|
||||
let path = dir.join("alice.mwid2");
|
||||
drop(alice);
|
||||
let waiter = tokio::spawn(async move {
|
||||
let mut alice = MeowClient::open(&path, "pw", KdfParams::INSECURE_TEST).await.unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let ev = alice.sync(Duration::from_secs(20)).await.unwrap();
|
||||
(texts(&ev), start.elapsed())
|
||||
});
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
bob.send_text("alice", "wake up").await.unwrap();
|
||||
let (got, elapsed) = waiter.await.unwrap();
|
||||
assert_eq!(got, vec!["wake up"]);
|
||||
assert!(elapsed < Duration::from_secs(10), "long poll took {elapsed:?}");
|
||||
|
||||
// ── one process at a time per identity ──
|
||||
assert!(matches!(
|
||||
MeowClient::open(&dir.join("bob.mwid2"), "pw", KdfParams::INSECURE_TEST).await,
|
||||
Err(meow_client::Error::Locked(_))
|
||||
));
|
||||
drop(bob);
|
||||
|
||||
// ── persistence & wrong password ──
|
||||
assert!(
|
||||
MeowClient::open(&dir.join("bob.mwid2"), "nope", KdfParams::INSECURE_TEST)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let bob2 = MeowClient::open(&dir.join("bob.mwid2"), "pw", KdfParams::INSECURE_TEST)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(bob2.contacts().len(), 2);
|
||||
assert_eq!(bob2.history("alice").unwrap().len(), 6); // 5 sent + "hi bob"
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
Reference in new issue
Block a user