//! OnionWire Android/Kotlin SDK. //! //! UniFFI façade over the existing `onionwire` library — the same crate the //! Linux TUI runs on. Nothing about the wire protocol is reimplemented here: //! an Android peer and a Linux peer that exchange invites interoperate. //! //! Locked facts this surface assumes: //! * Identity is an ed25519 pubkey. Fingerprint is a display of that key. //! * `onionwire:v1:k=…:o=…:spk=…:sig=…` — the onion is a *locator* and can //! change; re-scanning the same `k` updates the locator, never duplicates //! the friend. //! * Transport is in-process Arti. There is no `tor` binary, no torrc, no //! Orbot pipe. If the onion service cannot publish, this fails closed. //! * Chat bodies are encrypted at rest, and the whole sqlite file is //! SQLCipher on top of that (see the root crate). //! * A chat send that cannot reach the peer's onion is queued in a local //! outbox and retried — see [`SendState`]. Nothing leaves the device. //! //! The façade deliberately exposes only plain data (records + hex strings) so //! no TUI/ratatui type leaks into the AAR. use std::path::PathBuf; use std::sync::{Arc, OnceLock}; use onionwire::node::Node; use onionwire::outbox::OutboxStatus; use onionwire::qr; uniffi::setup_scaffolding!(); /// Install rustls's process-level default `CryptoProvider`, exactly once. /// /// Belt and braces. `Cargo.toml` pins `rustls` with the `ring` feature, which /// is what actually fixes the missing-provider failure: with it, rustls /// resolves a provider from crate features on its own. This function exists /// because the cdylib is loaded into a process we do not own — an explicitly /// installed provider makes the SDK independent of how the surrounding app's /// feature graph happens to resolve rustls. /// /// Idempotent and cheap after the first call (`OnceLock` short-circuits it). /// An `Err` means some provider is already installed process-wide, which is the /// outcome we want, so it is deliberately ignored — including the case of a /// consumer that installed `aws-lc-rs` itself. A genuine *conflict* — both /// provider features compiled in — is a build-graph bug, not something to /// paper over here; `Cargo.toml` enables `ring` only. /// /// Not exported over UniFFI: it is Rust-side plumbing, not part of the Kotlin /// surface. pub fn install_crypto_provider() { static INSTALLED: OnceLock<()> = OnceLock::new(); INSTALLED.get_or_init(|| { let _ = rustls::crypto::ring::default_provider().install_default(); }); } #[derive(Debug, thiserror::Error, uniffi::Error)] #[uniffi(flat_error)] pub enum WireError { #[error("{message}")] Failed { message: String }, } impl WireError { fn new(e: impl std::fmt::Display) -> Self { Self::Failed { message: e.to_string(), } } } type WResult = std::result::Result; #[derive(Debug, Clone, uniffi::Record)] pub struct FriendInfo { /// ed25519 identity pubkey, lowercase hex. This is the roster key. pub pubkey_hex: String, /// Display form of the same key. pub fingerprint: String, /// Local label. Never sent on the wire. pub petname: Option, /// Current locator. May be stale if the peer rotated while you were down. pub onion: String, pub last_connect_ok: bool, } /// What `send()` did with the message. /// /// The core has a local outbox: when a friend's onion is unreachable the /// message is written to the local sqlite store and a background worker /// retries it with backoff. Nothing is handed to a third party — every attempt /// is a fresh handshake straight to that friend's onion — but until a circuit /// takes it the message exists only on this device. A consumer must not render /// `Queued` as delivered. #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] pub enum SendState { /// The frame reached the peer's onion service during this call. Sent, /// The peer's onion was unreachable: the message is in the local outbox, /// local-only until the retry worker delivers it (or it ends `Failed`). Queued, } #[derive(Debug, Clone, uniffi::Record)] pub struct ChatMessage { /// "in" or "out". pub direction: String, pub body: String, /// Outgoing messages only: `"sent"`, `"queued"`, `"sending"` or /// `"failed: "`. `None` for incoming messages. An outgoing row with /// no outbox row is one the peer accepted on the first attempt, so it reads /// `"sent"` — never treat a missing value as "delivered" on the app side, /// read this field. pub delivery: Option, } #[derive(Debug, Clone, uniffi::Record)] pub struct RotateOutcome { pub notified: u32, pub friends: u32, } #[derive(Debug, Clone, uniffi::Record)] pub struct InviteInfo { pub pubkey_hex: String, pub onion: String, } /// A running OnionWire node: identity + Arti client + hosted v3 onion service. #[derive(uniffi::Object)] pub struct Wire { inner: Arc, } /// Open (or create) the identity in `home` and start hosting an onion service. /// /// `home` must be app-private storage (`context.filesDir`), not external. /// `passphrase` wraps the local message key; an empty passphrase fails closed. /// /// This resolves only once the onion service is published — on a cold network /// that is minutes, not seconds. Call it off the main thread. #[uniffi::export(async_runtime = "tokio")] pub async fn open_wire(home: String, passphrase: String) -> WResult> { // Before anything that can build a TLS config: Arti's rustls backend dies // with "Could not automatically determine the process-level CryptoProvider" // if no provider is resolvable. See `install_crypto_provider`. install_crypto_provider(); let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase) .await .map_err(WireError::new)?; Ok(Arc::new(Wire { inner: node })) } /// Decode an invite without adding the friend. Verifies the signature. #[uniffi::export] pub fn decode_invite(invite: String) -> WResult { let p = qr::decode(&invite).map_err(WireError::new)?; Ok(InviteInfo { pubkey_hex: hex(&p.pubkey), onion: p.onion, }) } #[uniffi::export(async_runtime = "tokio")] impl Wire { /// Fingerprint of our own identity key. Stable forever for this install. pub async fn fingerprint(&self) -> WResult { self.inner.fingerprint().map_err(WireError::new) } /// Current onion locator. Changes on rotate; identity does not. pub async fn onion(&self) -> String { self.inner.onion() } /// `onionwire:v1:…` invite string to hand to the other person out of band. pub async fn invite(&self) -> WResult { self.inner.qr_payload().map_err(WireError::new) } /// Roster, sorted by petname then fingerprint. pub async fn friends(&self) -> WResult> { let list = self.inner.list_friends().map_err(WireError::new)?; Ok(list .into_iter() .map(|f| FriendInfo { pubkey_hex: hex(&f.pubkey), fingerprint: f.fingerprint, petname: f.petname, onion: f.onion, last_connect_ok: f.last_connect_ok, }) .collect()) } /// Add a friend from an invite, or update the locator if the key is known. /// Same `k` never creates a second row. pub async fn add_friend(&self, invite: String) -> WResult { self.inner.add_friend_from_qr(&invite).map_err(WireError::new)?; let p = qr::decode(&invite).map_err(WireError::new)?; let f = self.inner.friend(&p.pubkey).map_err(WireError::new)?; Ok(FriendInfo { pubkey_hex: hex(&f.pubkey), fingerprint: f.fingerprint, petname: f.petname, onion: f.onion, last_connect_ok: f.last_connect_ok, }) } /// Local label. Pass `None` to clear. Never goes on the wire. pub async fn set_petname(&self, pubkey_hex: String, petname: Option) -> WResult<()> { let pk = unhex(&pubkey_hex)?; self.inner .set_petname(&pk, petname.as_deref()) .map_err(WireError::new) } /// Send one chat message. /// /// Returns [`SendState::Sent`] when the frame reached the peer's onion /// service during this call, and [`SendState::Queued`] when it did not: the /// message is then in the local outbox and a background worker retries it /// with exponential backoff (30s doubling, capped at 30 min, 8 attempts) /// until it lands or ends terminally failed. A queued send is local-only — /// show it as pending, not delivered. /// /// A protocol error (signature mismatch, malformed or oversize frame) is /// not retryable and still fails here; nothing is queued in that case. pub async fn send(&self, pubkey_hex: String, body: String) -> WResult { let pk = unhex(&pubkey_hex)?; let status = self .inner .send(&pk, body.as_bytes()) .await .map_err(WireError::new)?; Ok(send_state(status)) } /// Chat history for a friend, oldest first. Bodies are decrypted here; /// they are stored encrypted at rest. Outgoing rows carry their delivery /// state in [`ChatMessage::delivery`]. pub async fn messages(&self, pubkey_hex: String) -> WResult> { let pk = unhex(&pubkey_hex)?; let rows = self.inner.list_messages(&pk).map_err(WireError::new)?; let mut out = Vec::with_capacity(rows.len()); for m in rows { let status = self .inner .outbox_status_of_message(m.id) .map_err(WireError::new)?; out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(), delivery: delivery_of(&m.dir, status), direction: m.dir, }); } Ok(out) } /// Delete every message body. Identity and friends survive. pub async fn wipe_messages(&self) -> WResult<()> { self.inner.wipe_messages().map_err(WireError::new) } /// Publish a NEW onion service and hard-cut the old one, then push a signed /// location update to every reachable friend. /// /// The identity key does not change. Friends who are offline cannot find /// you until they rescan your invite — that is the documented v1 behaviour, /// not a bug. Confirm with a typed phrase in the UI; never one tap. pub async fn rotate_onion(&self) -> WResult { let r = self.inner.rotate().await.map_err(WireError::new)?; Ok(RotateOutcome { notified: r.notified as u32, friends: r.friends as u32, }) } /// SDK version, for diagnostics. pub async fn version(&self) -> String { env!("CARGO_PKG_VERSION").to_string() } } fn hex(bytes: &[u8]) -> String { let mut s = String::with_capacity(bytes.len() * 2); for b in bytes { s.push_str(&format!("{b:02x}")); } s } fn unhex(s: &str) -> WResult> { if s.is_empty() || !s.len().is_multiple_of(2) || !s.bytes().all(|c| c.is_ascii_hexdigit()) { return Err(WireError::new("pubkey_hex must be even-length hex")); } (0..s.len()) .step_by(2) .map(|i| { u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| WireError::new(format!("hex: {e}"))) }) .collect() } /// `Node::send` only ever yields `Sent` or `Queued`; `Sending`/`Failed` exist /// only on stored outbox rows. Everything that is not a completed send maps to /// `Queued`, so a status this build does not know about is never reported as /// delivered — the fail-safe direction for a caller that hides its retry UI. fn send_state(status: OutboxStatus) -> SendState { match status { OutboxStatus::Sent => SendState::Sent, _ => SendState::Queued, } } /// Delivery string for one stored chat row. `None` for incoming rows. An /// outgoing row with no outbox row was accepted on the first attempt, so it is /// reported as `"sent"` rather than left blank. fn delivery_of(dir: &str, status: Option) -> Option { if dir != "out" { return None; } Some(match status { None | Some(OutboxStatus::Sent) => "sent".to_string(), Some(other) => other.to_string(), }) } #[cfg(test)] mod tests { use super::*; use onionwire::outbox::OutboxStatus; #[test] fn sent_is_sent_everything_else_is_queued() { assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent); assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued); // `Node::send` never returns these today, but they exist on stored // rows. Unknown states map to `Queued` — the safe direction: never // report a send as delivered unless the core says `Sent`. assert_eq!(send_state(OutboxStatus::Sending), SendState::Queued); assert_eq!( send_state(OutboxStatus::Failed("no route".into())), SendState::Queued ); } #[test] fn delivery_is_reported_for_outgoing_rows_only() { assert_eq!(delivery_of("in", Some(OutboxStatus::Queued)), None); // Outgoing row with no outbox row: delivered on the first attempt. assert_eq!(delivery_of("out", None).as_deref(), Some("sent")); assert_eq!( delivery_of("out", Some(OutboxStatus::Sent)).as_deref(), Some("sent") ); assert_eq!( delivery_of("out", Some(OutboxStatus::Queued)).as_deref(), Some("queued") ); assert_eq!( delivery_of("out", Some(OutboxStatus::Sending)).as_deref(), Some("sending") ); assert_eq!( delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(), Some("failed: no route") ); } }