From 2c3d9fd1764286f7084b60d887a2273419b99b7a Mon Sep 17 00:00:00 2001 From: t Date: Sat, 12 Sep 2026 15:56:33 -0400 Subject: [PATCH 1/5] fix(store): checkpoint the WAL on the store's own keyed connection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The WAL checkpoint that `Node::shutdown`/`flush` promise ran through a short-lived second connection that no longer works: since the SQLCipher store every db is encrypted and its key lives inside `Store`, so an unkeyed second connection reads the file as noise and the checkpoint degenerated to "store is SQLCipher-encrypted — skipped (file is not a database)". `Store::checkpoint_wal()` now runs `PRAGMA wal_checkpoint(TRUNCATE)` on the connection `Store` owns, and `wipe_messages` reuses it instead of its inline copy. The node-side helper and its doc caveat are gone; the offline test moves with the code into `store.rs` and runs against a real encrypted store (it failed on the old implementation with exactly the SQLITE_NOTADB skip above). The live shutdown test now checks the WAL is 0 bytes after `flush` on a bootstrapped node. Public signatures of `Node::shutdown`/`flush` are unchanged. --- src/node.rs | 105 ++++------------------------------------- src/store.rs | 54 ++++++++++++++++++++- tests/tor_lifecycle.rs | 17 ++++++- 3 files changed, 77 insertions(+), 99 deletions(-) diff --git a/src/node.rs b/src/node.rs index a051f4d..627ca3a 100644 --- a/src/node.rs +++ b/src/node.rs @@ -293,7 +293,14 @@ impl Node { /// so this is about leaving less to replay (and less on disk) if the /// process is killed right after teardown — not about correctness. fn checkpoint(&self) { - if let Err(e) = checkpoint_wal(&self.home) { + let store = match self.store.lock() { + Ok(s) => s, + Err(e) => { + eprintln!("wal checkpoint: store lock poisoned: {e}"); + return; + } + }; + if let Err(e) = store.checkpoint_wal() { eprintln!("wal checkpoint: {e}"); } } @@ -1036,49 +1043,6 @@ fn spawn_flush_friend(outbox: Arc, friend_pk: Vec) { }); } -/// Checkpoint the sqlite WAL into the main db file and truncate it. -/// -/// `Store` owns the write connection and deliberately does not lend it out, and -/// a checkpoint is a property of the *database*, not of one connection — so a -/// short-lived second connection to the same file is the least invasive way to -/// reach it from the node without widening `Store`'s API. -/// -/// That works because the connection needs no passphrase: it moves -/// already-committed pages, it does not decrypt them. It stops working the -/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only -/// inside `Store` and a second connection cannot read the file at all. That case -/// is detected and reported as a skip rather than a failure: nothing is lost -/// (sqlite folds the WAL into the db when the last connection closes) — the -/// explicit truncation just has to move inside `Store` to happen here. -fn checkpoint_wal(home: &Path) -> Result<(), String> { - let db = home.join("onionwire.db"); - if !db.exists() { - return Ok(()); - } - let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?; - let (busy, log, checkpointed): (i64, i64, i64) = conn - .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { - Ok((row.get(0)?, row.get(1)?, row.get(2)?)) - }) - .map_err(|e| { - let msg = e.to_string(); - if msg.contains("not a database") { - // SQLCipher store: no key here, so this connection sees noise. - format!("store is SQLCipher-encrypted — skipped ({msg})") - } else { - format!("wal_checkpoint: {msg}") - } - })?; - if busy != 0 { - // Another connection is reading/writing: pages are still safe in the - // WAL, they just were not moved this time. - return Err(format!( - "busy ({checkpointed}/{log} pages moved, another connection active)" - )); - } - Ok(()) -} - fn next_hs_nickname(cur: &str) -> String { let n = cur .strip_prefix("ow") @@ -1122,56 +1086,3 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { false } -#[cfg(test)] -mod lifecycle_tests { - //! Offline half of the shutdown contract. The live-Tor half lives in - //! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI. - - use super::*; - - /// `checkpoint_wal` reaches the database through a *second* connection, - /// because `Store` owns the write one. That assumption is the whole reason - /// the helper can live in `node.rs`, so prove it against a real WAL. - #[test] - fn checkpoint_wal_truncates_a_live_wal() { - let root = tempfile::tempdir().expect("tempdir"); - let home = root.path(); - let db = home.join("onionwire.db"); - let conn = rusqlite::Connection::open(&db).expect("open db"); - let mode: String = conn - .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)) - .expect("wal mode"); - assert_eq!(mode.to_lowercase(), "wal"); - conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);") - .expect("create table"); - for _ in 0..64 { - conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]]) - .expect("insert"); - } - - let wal = home.join("onionwire.db-wal"); - let before = std::fs::metadata(&wal).expect("wal file").len(); - assert!(before > 0, "expected pending WAL frames, got {before}"); - - checkpoint_wal(home).expect("checkpoint"); - - let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); - assert_eq!(after, 0, "WAL not truncated ({before} bytes before)"); - - // The rows are still there — a checkpoint moves pages, it never drops - // committed data. - let n: i64 = conn - .query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0)) - .expect("count"); - assert_eq!(n, 64); - } - - /// A home directory with no store yet is not an error: `shutdown` and - /// `flush` are safe to call on a node whose db was never created (tests, - /// wiped installs). - #[test] - fn checkpoint_wal_is_a_no_op_without_a_database() { - let root = tempfile::tempdir().expect("tempdir"); - checkpoint_wal(root.path()).expect("no db, no error"); - } -} diff --git a/src/store.rs b/src/store.rs index a90666f..726e169 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1047,6 +1047,31 @@ impl Store { Ok(out) } + /// Fold the WAL into the main db file and truncate it. + /// + /// Runs on this store's own keyed connection: a second, unkeyed connection + /// cannot even read a SQLCipher store (`SQLITE_NOTADB`), so the checkpoint + /// has to happen here, not from `node.rs`. + /// + /// Best effort on purpose: WAL replay on open recovers everything committed, + /// so this is about leaving less to replay (and less on disk) if the process + /// is killed right after teardown — not about correctness. + pub fn checkpoint_wal(&self) -> Result<()> { + let (busy, log, checkpointed): (i64, i64, i64) = + self.conn + .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + })?; + if busy != 0 { + // Another connection is reading/writing: pages are still safe in the + // WAL, they just were not moved this time. + return Err(Error(format!( + "busy ({checkpointed}/{log} pages moved, another connection active)" + ))); + } + Ok(()) + } + /// Drop chat + payments history. Identity + friends stay. /// Not a forensic erase: SSD wear-leveling can keep copies. pub fn wipe_messages(&self) -> Result<()> { @@ -1058,7 +1083,7 @@ impl Store { self.conn.execute("DELETE FROM messages", [])?; self.conn.execute("DELETE FROM payments", [])?; self.conn.execute_batch("VACUUM")?; - self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?; + self.checkpoint_wal()?; Ok(()) } @@ -1372,6 +1397,33 @@ mod at_rest { use super::*; use zeroize::Zeroize; + /// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has + /// to run on the store's own keyed connection: a second, unkeyed one cannot + /// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently + /// never happened. + #[test] + fn checkpoint_wal_truncates_an_encrypted_store_wal() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open_at_with_passphrase(dir.path(), "checkpoint-pass").unwrap(); + let pk = [3u8; 32]; + store.upsert_friend(&pk, "peer.onion", None).unwrap(); + for _ in 0..64 { + store.append_message(&pk, "out", &[7u8; 512]).unwrap(); + } + + let wal = dir.path().join("onionwire.db-wal"); + let before = std::fs::metadata(&wal).expect("wal file").len(); + assert!(before > 0, "expected pending WAL frames, got {before}"); + + store.checkpoint_wal().expect("checkpoint"); + + let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + assert_eq!(after, 0, "WAL not truncated ({before} bytes before)"); + + // A checkpoint moves pages into the db; it never drops committed data. + assert_eq!(store.list_messages(&pk).unwrap().len(), 64); + } + #[test] fn store_data_key_is_a_zeroizing_wrapper_that_wipes() { let dir = tempfile::tempdir().unwrap(); diff --git a/tests/tor_lifecycle.rs b/tests/tor_lifecycle.rs index c74b081..6aad70e 100644 --- a/tests/tor_lifecycle.rs +++ b/tests/tor_lifecycle.rs @@ -10,7 +10,7 @@ //! //! The offline half of this contract — the Arti-status projection, the WAL //! checkpoint, and the SDK's typed error after shutdown — runs in the normal -//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`). +//! suite (`tests/hs.rs`, `src/store.rs`, `crates/onionwire-sdk/src/lib.rs`). use onionwire::node::{FlushOutcome, Node}; use onionwire::hs::TorState; @@ -52,10 +52,25 @@ async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() { "start returned Ok but tor_state() is {started_state:?}" ); + // Rows written by `start` (self row, current onion) are still in the WAL at + // this point: no checkpoint has run, and the connection that wrote them is + // still open. + let wal = home.join("onionwire.db-wal"); + let before = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + assert!( + before > 0, + "expected pending WAL frames before flush, got {before}" + ); + // A flush with nothing queued is a no-op that reports it, not an error. let drained: FlushOutcome = node.flush().await.expect("flush on a live node"); assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}"); + // `flush` promises a truncated WAL, and on an encrypted store that only + // works through the store's own keyed connection. + let left = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + assert_eq!(left, 0, "flush left {left} bytes of WAL to replay"); + node.shutdown().await.expect("shutdown"); assert_eq!( From e923e06891c3ea98086719a652225c38c5f1c13a Mon Sep 17 00:00:00 2001 From: apk-dev Date: Sat, 12 Sep 2026 16:34:40 -0400 Subject: [PATCH 2/5] feat(android): keep the onion published through Doze with a foreground service MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WireViewModel owned the single Wire node and called shutdown() from onCleared(), so a backgrounded node died with the UI. Node lifetime is now arbitrated by a pure policy (NodeLifetime) with two anchors — UI and keep-alive — and one process-wide owner (NodeHost) that is the only caller of flush()/shutdown() in the app. KeepAliveService holds the process in the foreground behind an ongoing notification from the "keep-alive" channel, started on unlock and stopped by Lock or the notification action, so peers can still reach the device while the screen is off. - foregroundServiceType="specialUse": dataSync is documented as a finite transfer (upload/download/backup) and this is an always-on node - POST_NOTIFICATIONS requested when the node becomes reachable; denial keeps the service running with no visible notice instead of failing - re-unlock with a node the service kept alive adopts it rather than reopening the store the live node still holds - 9 device-free unit tests for the start/stop/re-unlock state machine --- android/app/src/main/AndroidManifest.xml | 42 ++- .../siriusdevops/onionwire/MainActivity.kt | 28 +- .../siriusdevops/onionwire/WireViewModel.kt | 270 +++++++++++------- .../onionwire/keepalive/KeepAliveService.kt | 181 ++++++++++++ .../onionwire/keepalive/NodeHost.kt | 153 ++++++++++ .../onionwire/keepalive/NodeLifetime.kt | 99 +++++++ .../siriusdevops/onionwire/ui/RosterScreen.kt | 9 + .../siriusdevops/onionwire/ui/UnlockScreen.kt | 4 +- .../src/main/res/drawable/ic_stat_onion.xml | 17 ++ android/app/src/main/res/values/strings.xml | 16 ++ .../onionwire/keepalive/NodeLifetimeTest.kt | 130 +++++++++ 11 files changed, 838 insertions(+), 111 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAliveService.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeHost.kt create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeLifetime.kt create mode 100644 android/app/src/main/res/drawable/ic_stat_onion.xml create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/keepalive/NodeLifetimeTest.kt diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 5a6b1f3..8720d6f 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -4,10 +4,33 @@ + + + + + + + + + + + + diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index 8319e1b..562e25a 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -1,13 +1,18 @@ package com.siriusdevops.onionwire +import android.Manifest +import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity +import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier @@ -48,9 +53,27 @@ class MainActivity : ComponentActivity() { private fun AppRoot(vm: WireViewModel = viewModel()) { val phase by vm.phase.collectAsStateWithLifecycle() val unlock by vm.unlock.collectAsStateWithLifecycle() + val keepAliveNote by vm.keepAliveNote.collectAsStateWithLifecycle() + + // Asked in context: the notification is the keep-alive's only visible + // trace, so the prompt lands when the node becomes reachable rather than at + // first launch. Denial is not fatal — the service runs either way and the + // roster says the notice is hidden. + val askNotifications = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission(), + ) { vm.onNotificationPermissionChanged() } + + LaunchedEffect(phase) { + if (phase is Phase.Ready && + Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + !vm.notificationsAllowed() + ) { + askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS) + } + } when (val p = phase) { - is Phase.Ready -> ReadyGraph(vm, p) + is Phase.Ready -> ReadyGraph(vm, p, keepAliveNote) else -> UnlockScreen( phase = p, unlock = unlock, @@ -62,7 +85,7 @@ private fun AppRoot(vm: WireViewModel = viewModel()) { } @Composable -private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) { +private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: String?) { val nav = rememberNavController() val friends by vm.friends.collectAsStateWithLifecycle() val scope = rememberCoroutineScope() @@ -74,6 +97,7 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) { onion = ready.onion, sdkVersion = ready.sdkVersion, friends = friends, + keepAliveNote = keepAliveNote, onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") }, onShare = { nav.navigate("share") }, onPaste = { nav.navigate("paste") }, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 140c494..579de57 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -1,16 +1,17 @@ package com.siriusdevops.onionwire import android.app.Application +import androidx.core.app.NotificationManagerCompat import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.siriusdevops.onionwire.crypto.KeyBacking import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher import com.siriusdevops.onionwire.crypto.StoreSecret import com.siriusdevops.onionwire.crypto.StoredPassphraseStore -import kotlinx.coroutines.CoroutineScope +import com.siriusdevops.onionwire.keepalive.KeepAliveService +import com.siriusdevops.onionwire.keepalive.KeepAliveStatus +import com.siriusdevops.onionwire.keepalive.NodeHost import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -22,7 +23,6 @@ import uniffi.onionwire_sdk.InviteInfo import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite -import uniffi.onionwire_sdk.openWire import java.io.File sealed interface Phase { @@ -59,18 +59,13 @@ sealed interface Unlock { } /** - * Teardown work must outlive the ViewModel: `onCleared()` runs *after* - * `viewModelScope` is already cancelled, and stopping the node means draining - * the outbox and stopping Arti, not just dropping a reference. One process-wide - * scope is enough — there is one node per process. - */ -private val TEARDOWN = CoroutineScope(SupervisorJob() + Dispatchers.IO) - -/** - * Owns the single Wire node for the process. + * Owns the UI side of the process's single node. * - * The node lives in the ViewModel because a configuration change must not - * drop a published onion service and re-bootstrap Tor. + * The node itself lives in [NodeHost], not here, because it now has two + * possible owners: this ViewModel while the UI is up, and [KeepAliveService] + * while the screen is off. A configuration change still must not drop a + * published onion, and neither must the activity being destroyed — that part + * is unchanged. */ class WireViewModel(app: Application) : AndroidViewModel(app) { @@ -96,20 +91,28 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { private val _friends = MutableStateFlow>(emptyList()) val friends: StateFlow> = _friends.asStateFlow() - private var wire: Wire? = null - /** - * The in-flight teardown, if any. Unlocking again has to wait for it: the - * old node holds the sqlite file and Arti's state lock until `shutdown()` - * returns, and racing it makes the new node fail to open. + * One line of battery honesty for the roster: what is still running once + * the screen is off, or why it is not. Null while locked. */ - private var stopping: Job? = null + private val _keepAliveNote = MutableStateFlow(null) + val keepAliveNote: StateFlow = _keepAliveNote.asStateFlow() init { - // Probe on a background dispatcher: this touches the Keystore and does - // a full GCM decrypt. Doing it here means a killed Keystore key is - // reported on the lock screen instead of at the first tap. - refreshUnlockState() + // A node the foreground service kept alive is still open. Adopt it and + // go straight to the roster: showing an unlock screen for a store that + // is already open would be theatre, and unlocking again would race the + // live node for the sqlite file. + val existing = NodeHost.current() + if (existing != null) { + viewModelScope.launch { adopt(existing) } + } else { + refreshUnlockState() + } + + viewModelScope.launch { + NodeHost.keepAlive.collect { renderKeepAliveNote(it) } + } } /** @@ -162,44 +165,155 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } /** - * Stops the node and drops our handle. Nothing is sent after this. + * Explicit Lock: stops the node and the keep-alive with it. * - * Flush first — the outbox is the whole point of losing the process — then - * `shutdown()`, which stops the onion service, aborts the retry worker and - * checkpoints the sqlite WAL. Both calls are on [TEARDOWN] because this - * runs from an `onClick`. + * Order matters. The service goes first — a still-running keep-alive would + * re-anchor the node and leave a notification pointing at a dead onion — + * then the policy tears the node down, flush before `shutdown()` so the + * outbox survives. */ fun lock() { - val w = wire ?: return - wire = null + if (NodeHost.current() == null) return + KeepAliveService.stop(getApplication()) + NodeHost.lock() _friends.value = emptyList() _phase.value = Phase.Locked refreshUnlockState() - stopping = TEARDOWN.launch { stopNode(w) } } /** - * The node must not outlive the UI. Doze and the background-process killer - * skip this entirely (that is what the outbox is for), but a normal finish - * tears Tor down here instead of leaving Arti running behind a dead screen. + * The UI is going away: a normal finish, a task swipe, or the process being + * killed. This deliberately does **not** shut the node down — [NodeHost] + * decides between "flush and stay published" (a keep-alive is holding it) + * and "flush and stop" (nothing is). A ViewModel that shut down a node the + * foreground service owns is the bug this card exists to avoid. */ override fun onCleared() { - val w = wire - wire = null - if (w != null) stopping = TEARDOWN.launch { stopNode(w) } + NodeHost.onUiDetached() super.onCleared() } - private suspend fun stopNode(w: Wire) { - // Best effort, both steps: teardown runs on a process-scope job after - // the UI is gone, so there is nobody to show an error to and nothing - // useful to retry. `shutdown()` drains again with a shorter budget, so - // a flush that times out is not fatal. - runCatching { w.flush() } - // A second shutdown — `lock()` and then `onCleared()`, say — lands here - // too: the SDK reports it as a typed WireException.Stopped, never a - // panic, so swallowing it is correct. - runCatching { w.shutdown() } + /** Re-reads the notification state after the runtime prompt resolves. */ + fun onNotificationPermissionChanged() { + renderKeepAliveNote(NodeHost.keepAlive.value) + // Android does not retroactively post a foreground notification that was + // suppressed while POST_NOTIFICATIONS was denied — the service started, + // the user then granted, and the shade stayed empty. Re-announce, so the + // grant actually produces the one honest signal the user has. + if (NodeHost.keepAlive.value is KeepAliveStatus.On) { + viewModelScope.launch { + NodeHost.current()?.let { KeepAliveService.start(getApplication(), it.onion()) } + } + } + } + + /** Whether the keep-alive's notification can actually be posted. */ + fun notificationsAllowed(): Boolean = + NotificationManagerCompat.from(getApplication()).areNotificationsEnabled() + + private fun renderKeepAliveNote(status: KeepAliveStatus) { + val text = getApplication() + _keepAliveNote.value = when (status) { + // Not a null note: "off" is a real state the user should be able to + // read, right after the notification's Stop action. + KeepAliveStatus.Off -> text.getString(R.string.keep_alive_note_off) + + KeepAliveStatus.On -> text.getString( + if (notificationsAllowed()) { + R.string.keep_alive_note_on + } else { + // Denial is not fatal: the service runs either way and + // Android lists it in the Task Manager. Say that instead of + // pretending the notification is there. + R.string.keep_alive_note_hidden + }, + ) + + is KeepAliveStatus.Unavailable -> + text.getString(R.string.keep_alive_note_unavailable, status.reason) + } + } + + /** + * The one path that opens the SDK. + * + * [secret] is wiped in `finally`, including when the Keystore write or the + * SDK call throws. The SDK's UniFFI signature takes a `String`, so one + * immutable copy is unavoidable here — see PR #49 for the follow-up SDK + * signature this card cannot make itself. + */ + private fun openWith(secret: CharArray, storeAfterwards: Boolean) { + if (secret.isEmpty() || _phase.value is Phase.Opening) { + StoreSecret.wipe(secret) + return + } + val existing = NodeHost.current() + if (existing != null) { + // Already open, kept alive while the UI was gone: adopt, never + // re-open. The live node holds the sqlite file and Arti's state + // lock, so a second open would fail — or worse, half-succeed. + StoreSecret.wipe(secret) + viewModelScope.launch { adopt(existing) } + return + } + _phase.value = Phase.Opening + viewModelScope.launch { + try { + // The SDK open is dispatched to Dispatchers.IO inside NodeHost: + // cold start is minutes of Tor bootstrap, which the main thread + // does not survive. + val w = NodeHost.open(home, secret.concatToString()) + if (storeAfterwards) store(secret) + adopt(w) + startKeepAlive(w) + } catch (t: Throwable) { + _phase.value = Phase.Failed(t.message ?: t.toString()) + } finally { + StoreSecret.wipe(secret) + } + } + } + + /** + * Points the UI at a node that is already running. The SDK getters are + * `suspend`, hence the coroutine call sites. + */ + private suspend fun adopt(w: Wire) { + _phase.value = Phase.Ready( + fingerprint = w.fingerprint(), + onion = w.onion(), + sdkVersion = w.version(), + ) + runCatching { refreshFriends() } + } + + /** + * Starts the foreground keep-alive. Always reached from a user-visible + * unlock, so the API 31+ background-start restriction does not apply; if + * the system refuses anyway, [NodeHost] records why and the roster says so. + */ + private suspend fun startKeepAlive(w: Wire) { + if (NodeHost.keepAlive.value is KeepAliveStatus.On) return + KeepAliveService.start(getApplication(), w.onion()) + } + + private suspend fun store(secret: CharArray) { + val outcome: Result = withContext(Dispatchers.IO) { + try { + secrets.save(secret) + Result.success(secrets.backing()) + } catch (t: Throwable) { + Result.failure(t) + } + } + _unlock.value = outcome.fold( + onSuccess = { Unlock.OneTap(it) }, + onFailure = { + // Unlock succeeded, so this is not fatal — say so plainly + // instead of pretending the passphrase was stored. + Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.") + }, + ) } private fun refreshUnlockState() { @@ -222,66 +336,10 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } } - /** - * The one path that calls the SDK. - * - * [secret] is wiped in `finally`, including when the Keystore write or the - * SDK call throws. The SDK's UniFFI signature takes a `String`, so one - * immutable copy is unavoidable here — see the PR description for the - * follow-up SDK signature this card cannot make itself. - */ - private fun openWith(secret: CharArray, storeAfterwards: Boolean) { - if (secret.isEmpty() || _phase.value is Phase.Opening || wire != null) { - StoreSecret.wipe(secret) - return - } - _phase.value = Phase.Opening - viewModelScope.launch { - try { - // Any previous node must be fully stopped first: the old node - // holds the sqlite file and Arti's state lock until its teardown - // returns, and racing it makes this open fail. - stopping?.join() - val w = openWire(home.absolutePath, secret.concatToString()) - wire = w - if (storeAfterwards) store(secret) - _phase.value = Phase.Ready( - fingerprint = w.fingerprint(), - onion = w.onion(), - sdkVersion = w.version(), - ) - refreshFriends() - } catch (t: Throwable) { - _phase.value = Phase.Failed(t.message ?: t.toString()) - } finally { - StoreSecret.wipe(secret) - } - } - } - - private suspend fun store(secret: CharArray) { - val outcome: Result = withContext(Dispatchers.IO) { - try { - secrets.save(secret) - Result.success(secrets.backing()) - } catch (t: Throwable) { - Result.failure(t) - } - } - _unlock.value = outcome.fold( - onSuccess = { Unlock.OneTap(it) }, - onFailure = { - // Unlock succeeded, so this is not fatal — say so plainly - // instead of pretending the passphrase was stored. - Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.") - }, - ) - } - private fun unavailableNotice(reason: String): String = "The stored passphrase could not be read — $reason. Type it once to store it again." - private fun requireWire(): Wire = wire ?: error("locked") + private fun requireWire(): Wire = NodeHost.requireOpen() suspend fun refreshFriends() { _friends.value = requireWire().friends() diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAliveService.kt b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAliveService.kt new file mode 100644 index 0000000..51fabc8 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/KeepAliveService.kt @@ -0,0 +1,181 @@ +package com.siriusdevops.onionwire.keepalive + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import android.util.Log +import androidx.core.app.NotificationCompat +import com.siriusdevops.onionwire.MainActivity +import com.siriusdevops.onionwire.R + +/** + * Holds the process (and therefore the in-process Arti node) in the foreground + * so the onion stays published after the screen goes off. + * + * The service does *not* own the node — [NodeHost] does. This reports its + * anchor and lets the policy decide: starting the keep-alive keeps the node + * alive, and losing it (user tapped Stop, or the system killed us) shuts the + * node down only if nothing else is holding it. + * + * Returns `START_NOT_STICKY` deliberately. A sticky restart would bring the + * service back with no node behind it — the passphrase is not held in memory + * after unlock — and a notification claiming "OnionWire is reachable" over a + * dead onion is worse than no service at all. + */ +class KeepAliveService : Service() { + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.action == ACTION_STOP) { + // The user ended the keep-alive from the notification. `onDestroy()` + // reports the lost anchor: the node stops if nothing else holds it, + // and stays up while the app is still open in front of them (the UI + // anchor). The action is labelled "Stop keep-alive", not "Lock", so + // that is the behaviour it promises. + stopSelf() + return START_NOT_STICKY + } + + if (NodeHost.current() == null) { + // Nothing to keep alive. A notification here would be a lie. + stopSelf() + return START_NOT_STICKY + } + + if (!startInForeground(intent?.getStringExtra(EXTRA_ONION).orEmpty())) { + stopSelf() + return START_NOT_STICKY + } + + NodeHost.onKeepAliveStarted() + return START_NOT_STICKY + } + + override fun onDestroy() { + NodeHost.onKeepAliveStopped() + super.onDestroy() + } + + /** + * @return false when the system refused the foreground start, in which case + * the anchor was never taken and the node stays foreground-only. + */ + private fun startInForeground(onion: String): Boolean { + return try { + createChannel() + val notification = buildNotification(onion) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + startForeground( + NOTIFICATION_ID, + notification, + ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE, + ) + } else { + // API 26-33: the manifest-declared type is what the platform + // records; the three-arg overload only exists from 29. + startForeground(NOTIFICATION_ID, notification) + } + true + } catch (t: Throwable) { + // API 31+: a start from the background throws + // ForegroundServiceStartNotAllowedException. Degrade to "the node + // lives only while the app does" instead of taking the process + // down; the roster says so on screen. + Log.w(TAG, "foreground start refused; node stays foreground-only", t) + NodeHost.onKeepAliveRefused(t.message ?: t.toString()) + false + } + } + + private fun createChannel() { + val manager = getSystemService(NotificationManager::class.java) ?: return + val channel = NotificationChannel( + CHANNEL_ID, + getString(R.string.keep_alive_channel_name), + // LOW: present in the shade, never a sound or a heads-up. This is a + // status light, not an alert. + NotificationManager.IMPORTANCE_LOW, + ).apply { + description = getString(R.string.keep_alive_channel_description) + setShowBadge(false) + } + manager.createNotificationChannel(channel) + } + + private fun buildNotification(onion: String): Notification { + val open = PendingIntent.getActivity( + this, + 0, + Intent(this, MainActivity::class.java), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + val stop = PendingIntent.getService( + this, + 1, + Intent(this, KeepAliveService::class.java).setAction(ACTION_STOP), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + // Never the full v3 locator: a notification body is lock-screen public. + val short = onion.take(ONION_PREFIX) + val text = if (short.isEmpty()) { + getString(R.string.keep_alive_text) + } else { + getString(R.string.keep_alive_text_onion, short) + } + return NotificationCompat.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_stat_onion) + .setContentTitle(getString(R.string.keep_alive_title)) + .setContentText(text) + .setContentIntent(open) + .addAction(0, getString(R.string.keep_alive_stop), stop) + .setCategory(NotificationCompat.CATEGORY_SERVICE) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setShowWhen(false) + .build() + } + + companion object { + private const val TAG = "OnionWireKeepAlive" + + const val ACTION_STOP = "com.siriusdevops.onionwire.keepalive.STOP" + const val EXTRA_ONION = "onion" + + private const val CHANNEL_ID = "keep-alive" + private const val NOTIFICATION_ID = 1 + + /** Characters of the onion address shown, prefix only. */ + private const val ONION_PREFIX = 10 + + /** + * Brings up the keep-alive. Must be called while the app is visible — + * an unlock is, and that is the only caller — so the API 31+ + * background-start restriction does not apply. + */ + fun start(context: Context, onion: String) { + val intent = Intent(context, KeepAliveService::class.java) + .putExtra(EXTRA_ONION, onion) + try { + context.startForegroundService(intent) + } catch (t: Throwable) { + // Same refusal as in the service, just one call earlier. + Log.w(TAG, "startForegroundService refused", t) + NodeHost.onKeepAliveRefused(t.message ?: t.toString()) + } + } + + /** Ends the keep-alive; `onDestroy()` reports the lost anchor. */ + fun stop(context: Context) { + context.stopService(Intent(context, KeepAliveService::class.java)) + } + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeHost.kt b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeHost.kt new file mode 100644 index 0000000..3aa0504 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeHost.kt @@ -0,0 +1,153 @@ +package com.siriusdevops.onionwire.keepalive + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import uniffi.onionwire_sdk.Wire +import uniffi.onionwire_sdk.openWire +import java.io.File + +/** + * How visible the keep-alive currently is, for the one line of battery honesty + * the roster shows. + */ +sealed interface KeepAliveStatus { + /** No foreground service. The node lives only while the app does. */ + data object Off : KeepAliveStatus + + /** A foreground service is holding the node, notification and all. */ + data object On : KeepAliveStatus + + /** + * The system refused the foreground start (API 31+ background-start rules, + * an OEM battery policy). The node is still up, but it dies with the app. + */ + data class Unavailable(val reason: String) : KeepAliveStatus +} + +/** + * Process-wide owner of the single `Wire` node. + * + * Ownership rule: whoever opens the node hands the handle here, and **only this + * object ever calls `shutdown()` or `flush()` on it**. The ViewModel and + * [KeepAliveService] report lifecycle transitions; [NodeLifetime] decides + * whether the node survives, and this object executes that decision. + * + * That indirection is the point. `WireViewModel.onCleared()` used to shut the + * node down unconditionally, so a foreground service holding the same node + * would have been torn down by the first configuration change — or worse, the + * service would have kept a notification up for a node the UI had already + * killed. Neither side owns the node now; the policy does. + * + * Threading: every mutation runs on the main thread except the SDK call inside + * [open], which is dispatched to [Dispatchers.IO] and hops back. + */ +object NodeHost { + + /** + * Teardown must outlive the object graph that asked for it: `onCleared()` + * runs *after* `viewModelScope` is already cancelled, and stopping the node + * means draining the outbox and stopping Arti, not dropping a reference. + * One process-wide scope is enough — there is one node per process. + */ + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + private val lifetime = NodeLifetime() + + private var wire: Wire? = null + + /** + * The in-flight teardown, if any. Re-opening has to wait for it: the old + * node holds the sqlite file and Arti's state lock until `shutdown()` + * returns, and racing it makes the new node fail to open. + */ + private var stopping: Job? = null + + private val _keepAlive = MutableStateFlow(KeepAliveStatus.Off) + val keepAlive: StateFlow = _keepAlive.asStateFlow() + + /** The live node, or null when locked. */ + fun current(): Wire? = wire + + /** The live node, or a hard error. Callers are UI paths that require unlock. */ + fun requireOpen(): Wire = wire ?: error("locked") + + /** + * Opens the node and anchors it to the UI. + * + * Suspends inside Arti's bootstrap — minutes on a cold start — so this must + * never run on the main thread. Callers are `viewModelScope` coroutines. + */ + suspend fun open(home: File, passphrase: String): Wire { + stopping?.join() + val opened = withContext(Dispatchers.IO) { openWire(home.absolutePath, passphrase) } + wire = opened + _keepAlive.value = KeepAliveStatus.Off + lifetime.onOpened() + return opened + } + + /** The UI is going away: finish, task swipe, or process death. */ + fun onUiDetached(): NodeAction = apply(lifetime.onUnanchored(NodeAnchor.UI)) + + /** The keep-alive reached the foreground with its notification. */ + fun onKeepAliveStarted(): NodeAction { + _keepAlive.value = KeepAliveStatus.On + return apply(lifetime.onAnchored(NodeAnchor.KEEP_ALIVE)) + } + + /** The keep-alive stopped, or the system destroyed it. */ + fun onKeepAliveStopped(): NodeAction { + if (_keepAlive.value is KeepAliveStatus.On) _keepAlive.value = KeepAliveStatus.Off + return apply(lifetime.onUnanchored(NodeAnchor.KEEP_ALIVE)) + } + + /** + * `startForeground()` was refused. Nothing is anchoring the node at the OS + * level, so fail over to the honest pre-existing behaviour: the node lives + * as long as the app does, and the roster says why. + */ + fun onKeepAliveRefused(reason: String): NodeAction { + _keepAlive.value = KeepAliveStatus.Unavailable(reason) + return apply(lifetime.onUnanchored(NodeAnchor.KEEP_ALIVE)) + } + + /** + * Explicit Lock, from the UI or the notification's Stop action. The caller + * stops the keep-alive first — a service that is still running would + * re-anchor a node that no longer exists. + */ + fun lock(): NodeAction = apply(lifetime.onLocked()) + + private fun apply(action: NodeAction): NodeAction { + when (action) { + NodeAction.Keep -> Unit + NodeAction.Flush -> scope.launch { runCatching { wire?.flush() } } + NodeAction.Stop -> stopNode() + } + return action + } + + private fun stopNode() { + val dying = wire ?: return + wire = null + lifetime.onClosed() + // Best effort, both steps: teardown runs on a process-scope job after + // the UI is gone, so there is nobody to show an error to and nothing + // useful to retry. `shutdown()` drains again with a shorter budget, so + // a flush that times out is not fatal. + stopping = scope.launch { + runCatching { dying.flush() } + // A second shutdown — `lock()` and then `onCleared()`, say — lands + // here too: the SDK reports it as a typed WireException.Stopped, + // never a panic, so swallowing it is correct. + runCatching { dying.shutdown() } + } + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeLifetime.kt b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeLifetime.kt new file mode 100644 index 0000000..e195867 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/keepalive/NodeLifetime.kt @@ -0,0 +1,99 @@ +package com.siriusdevops.onionwire.keepalive + +/** + * Who currently requires the in-process Tor node to stay alive. + * + * [UI] is a live `WireViewModel`; [KEEP_ALIVE] is a running [KeepAliveService]. + * Both can be present at the same time — that is the interesting case: the + * screen can go away while the keep-alive stays up, and the node must survive + * it. This enum exists so "who owns the node" is a value, not a convention. + */ +enum class NodeAnchor { + UI, + KEEP_ALIVE, +} + +/** What the caller must do to the node after reporting a transition. */ +sealed interface NodeAction { + /** Nothing to do; the node's fate is unchanged. */ + data object Keep : NodeAction + + /** Drain the outbox, leave the node published. */ + data object Flush : NodeAction + + /** Drain the outbox, then `shutdown()`. The node is gone. */ + data object Stop : NodeAction +} + +/** + * Pure policy for the single node's lifetime: no Android, no coroutines, no + * SDK. The ViewModel and the foreground service both report transitions here + * and execute the returned [NodeAction]. + * + * The rule the whole card turns on: **the UI going away does not stop the node + * while a keep-alive anchor is held.** Before this, `WireViewModel.onCleared()` + * called `shutdown()` unconditionally, which is exactly the bug a foreground + * service would have walked into. + * + * Threading: state is mutated only from the main thread — [NodeHost] is the + * only caller, and it hops back to the main thread after the SDK's blocking + * open. There is no lock here on purpose. + */ +class NodeLifetime { + + private var open = false + private val anchors = LinkedHashSet() + + /** True between [onOpened] and [onClosed]/[onLocked]. */ + val isOpen: Boolean get() = open + + fun anchoredBy(anchor: NodeAnchor): Boolean = anchor in anchors + + /** + * The unlock path opened a node. The UI is by definition present — the user + * typed the passphrase into it. + */ + fun onOpened(): NodeAction { + open = true + anchors.add(NodeAnchor.UI) + return NodeAction.Keep + } + + /** Teardown finished; the node no longer exists. */ + fun onClosed(): NodeAction { + open = false + anchors.clear() + return NodeAction.Keep + } + + /** A keep-alive reached the foreground. */ + fun onAnchored(anchor: NodeAnchor): NodeAction { + anchors.add(anchor) + return NodeAction.Keep + } + + /** + * An anchor went away: the UI was destroyed, or the keep-alive stopped or + * was killed. Removing the anchor first means a repeat report (the service + * action and `onDestroy()` both fire) cannot double-count. + */ + fun onUnanchored(anchor: NodeAnchor): NodeAction { + anchors.remove(anchor) + if (!open) return NodeAction.Keep + // Flush rather than Keep when another anchor remains: the process may + // be killed at any moment once the screen is gone, and the outbox is + // the whole point of surviving that. + return if (anchors.isEmpty()) NodeAction.Stop else NodeAction.Flush + } + + /** + * The user pressed Lock. Every anchor is dropped: a keep-alive that outlived + * an explicit lock would leave a notification pointing at a dead onion. + */ + fun onLocked(): NodeAction { + val wasOpen = open + open = false + anchors.clear() + return if (wasOpen) NodeAction.Stop else NodeAction.Keep + } +} diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt index 2286d91..c4fbe42 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RosterScreen.kt @@ -40,6 +40,7 @@ fun RosterScreen( onion: String, sdkVersion: String, friends: List, + keepAliveNote: String?, onOpenChat: (FriendInfo) -> Unit, onShare: () -> Unit, onPaste: () -> Unit, @@ -82,6 +83,14 @@ fun RosterScreen( style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) + if (keepAliveNote != null) { + Spacer(Modifier.height(10.dp)) + Text( + keepAliveNote, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + } } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt index d762028..7adb6f8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/UnlockScreen.kt @@ -223,7 +223,9 @@ fun UnlockScreen( Spacer(Modifier.height(24.dp)) Text( - "INTERNET is the only permission this app requests.", + "Permissions: internet, plus a foreground service and its notification so " + + "the onion stays reachable while the screen is off. No camera, contacts " + + "or storage.", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/android/app/src/main/res/drawable/ic_stat_onion.xml b/android/app/src/main/res/drawable/ic_stat_onion.xml new file mode 100644 index 0000000..90aa302 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_stat_onion.xml @@ -0,0 +1,17 @@ + + + + + + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index bf2bc9c..33e0458 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1,4 +1,20 @@ OnionWire + + + Node keep-alive + Shown while OnionWire keeps your onion address reachable in the background. + OnionWire is reachable + Tor and the outbox are running so peers can deliver messages. + Tor and the outbox are running so peers can reach %1$s… + Stop keep-alive + Reachable only while this app is open. + Kept alive — Tor and the outbox run until you tap Lock. + Kept alive, but notifications are blocked, so the status notice is hidden. Android still lists the service in the Task Manager. + Not kept alive (%1$s). The node stops when the app does. diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/keepalive/NodeLifetimeTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/keepalive/NodeLifetimeTest.kt new file mode 100644 index 0000000..24f1cab --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/keepalive/NodeLifetimeTest.kt @@ -0,0 +1,130 @@ +package com.siriusdevops.onionwire.keepalive + +import com.siriusdevops.onionwire.keepalive.NodeAction.Flush +import com.siriusdevops.onionwire.keepalive.NodeAction.Keep +import com.siriusdevops.onionwire.keepalive.NodeAction.Stop +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The service-lifetime state machine, no device required: [NodeLifetime] is + * pure. Every case here is a transition the app actually produces — unlock, + * background, task swipe, notification Stop, explicit Lock, re-unlock. + */ +class NodeLifetimeTest { + + @Test + fun ui_detach_with_no_keep_alive_stops_the_node() { + val l = NodeLifetime() + l.onOpened() + + assertEquals(Stop, l.onUnanchored(NodeAnchor.UI)) + assertTrue(l.isOpen) // the caller still has to run flush+shutdown + } + + @Test + fun keep_alive_anchor_survives_ui_detach_and_only_flushes() { + val l = NodeLifetime() + l.onOpened() + l.onAnchored(NodeAnchor.KEEP_ALIVE) + + // Task swiped: the activity is gone, the service is not. + assertEquals(Flush, l.onUnanchored(NodeAnchor.UI)) + assertFalse(l.anchoredBy(NodeAnchor.UI)) + assertTrue(l.anchoredBy(NodeAnchor.KEEP_ALIVE)) + } + + @Test + fun losing_the_last_anchor_stops_the_node() { + val l = NodeLifetime() + l.onOpened() + l.onAnchored(NodeAnchor.KEEP_ALIVE) + l.onUnanchored(NodeAnchor.UI) + + // Notification Stop, or the system killing the service. + assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE)) + } + + @Test + fun service_stopping_while_the_ui_is_up_keeps_the_node() { + val l = NodeLifetime() + l.onOpened() + l.onAnchored(NodeAnchor.KEEP_ALIVE) + + assertEquals(Flush, l.onUnanchored(NodeAnchor.KEEP_ALIVE)) + assertTrue(l.anchoredBy(NodeAnchor.UI)) + assertTrue(l.isOpen) + } + + @Test + fun repeated_anchor_loss_is_idempotent() { + val l = NodeLifetime() + l.onOpened() + l.onAnchored(NodeAnchor.KEEP_ALIVE) + l.onUnanchored(NodeAnchor.UI) + + // The Stop action and onDestroy both report the same loss. + assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE)) + l.onClosed() + assertEquals(Keep, l.onUnanchored(NodeAnchor.KEEP_ALIVE)) + } + + @Test + fun lock_drops_every_anchor() { + val l = NodeLifetime() + l.onOpened() + l.onAnchored(NodeAnchor.KEEP_ALIVE) + + assertEquals(Stop, l.onLocked()) + assertFalse(l.isOpen) + assertFalse(l.anchoredBy(NodeAnchor.KEEP_ALIVE)) + assertFalse(l.anchoredBy(NodeAnchor.UI)) + l.onClosed() + } + + @Test + fun re_unlock_after_lock_starts_from_a_clean_slate() { + val l = NodeLifetime() + l.onOpened() + l.onAnchored(NodeAnchor.KEEP_ALIVE) + l.onLocked() + l.onClosed() + + // Second unlock: only the UI anchors, so backgrounding really stops. + assertEquals(Keep, l.onOpened()) + assertFalse(l.anchoredBy(NodeAnchor.KEEP_ALIVE)) + assertEquals(Stop, l.onUnanchored(NodeAnchor.UI)) + } + + @Test + fun re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it() { + // Process relaunch with the service still up: the ViewModel adopts the + // live node and never calls onOpened(), so the KEEP_ALIVE anchor (and + // the node) is untouched by the new UI attaching. + val l = NodeLifetime() + l.onOpened() + l.onAnchored(NodeAnchor.KEEP_ALIVE) + l.onUnanchored(NodeAnchor.UI) + + assertTrue(l.isOpen) + assertTrue(l.anchoredBy(NodeAnchor.KEEP_ALIVE)) + assertFalse(l.anchoredBy(NodeAnchor.UI)) + + // The adopted UI leaves again: still flush, still alive. + assertEquals(Flush, l.onUnanchored(NodeAnchor.UI)) + assertTrue(l.isOpen) + assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE)) + } + + @Test + fun transitions_on_a_closed_node_do_nothing() { + val l = NodeLifetime() + + assertEquals(Keep, l.onUnanchored(NodeAnchor.UI)) + assertEquals(Keep, l.onUnanchored(NodeAnchor.KEEP_ALIVE)) + assertEquals(Keep, l.onLocked()) + assertEquals(Keep, l.onAnchored(NodeAnchor.KEEP_ALIVE)) // service up, still locked + } +} From d256d3bb8ead4516f833d463a964069abe9da598 Mon Sep 17 00:00:00 2001 From: t Date: Sat, 12 Sep 2026 16:00:12 -0400 Subject: [PATCH 3/5] docs: describe the SQLCipher store, not the pre-#43 design The v0.2 banner and the "Seized laptop" section still claimed only chat bodies were encrypted, that `self.identity_sk` and the roster were plaintext, and that "sqlcipher is out of v1". That has been false since #43. - README banner: whole store is encrypted at rest with SQLCipher, with the row-bound AEAD layer kept on top. - "Seized laptop": whole-file SQLCipher (Argon2id key over the 16-byte `store_salt`, raw `PRAGMA key`), identity/friends/locators inside the encrypted file, fail-closed unlock and `store_salt`-missing refusal, and the in-place v0.2.1 upgrade. Kept the honest caveats: no defense against a live compromise or a known passphrase, `/wipe` is not a forensic erase (SSD wear-levelling), and THREAT_MODEL.md stays the reference. - "Not in v1": drop `sqlcipher` (shipped in #43). - docs/SECURITY_AUDIT.md "Still true" bullet repeated the same plaintext claim; restated it as the residual risk that actually remains. No code change. Evidence: cargo test --test store (21 passed, incl. whole_store_file_is_encrypted_at_rest) and cargo test --lib -- store:: (6 passed, incl. the plaintext->SQLCipher upgrade and the wrong-passphrase no-op). Card: t_f2fc5190 --- README.md | 13 +++++-------- docs/SECURITY_AUDIT.md | 2 +- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 82aeb2c..5ae0162 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti). No hosted server. Identity is a public key; the onion is only a locator. -**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. Chat bodies are encrypted at rest; identity keys in sqlite are still plaintext. +**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top. You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion. @@ -222,14 +222,11 @@ If you set `ONIONWIRE_HOME`, delete that directory instead. ## Seized laptop -Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD bound to `friend_id`, `dir`, and row id, wrapped by a passphrase-derived Argon2id key. A disk grep of `onionwire.db` must not yield the message log. Empty-AAD v0.2 blobs are rewrapped once on unlock. +The whole sqlite file is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). A 32-byte key is derived from the store passphrase with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600, in `ONIONWIRE_HOME`) and handed to SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) as the first statement after open. The file header, schema, `self.identity_sk`, friend public keys, locators, profiles and payment rows are all ciphertext on disk, so a disk grep of `onionwire.db` must not yield the message log, your identity key or your roster. A wrong or empty passphrase fails closed before any write; an encrypted store whose `store_salt` is missing refuses to open instead of guessing. v0.2.1 plaintext installs upgrade in place on the first open with the right passphrase; a wrong one leaves the plaintext file untouched. -Still plaintext on disk (unless you add OS/FDE): +Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`, plus a random 32-byte data key in `store_meta` wrapped with Argon2id from the same passphrase. Whole-file encryption does not stop someone who can write the file from moving one row's ciphertext into another row; the row-bound AAD does, and it stays. Empty-AAD v0.2 blobs are rewrapped once on unlock. -- your identity secret key (`self.identity_sk`) -- friend public keys and current locators - -The message key is **not** wrapped with `identity_sk` (that key is in the same file). sqlcipher is out of v1. `/wipe` deletes chat and payments history; it is not a forensic erase. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person. +At-rest encryption is not a defense against a live compromise: while OnionWire runs, the passphrase, the db key and decrypted rows are in process memory, and SQLCipher's page cache holds decrypted pages. It also does not stop an attacker who has your passphrase. `/wipe` deletes chat and payments history; it is not a forensic erase — SSD wear-levelling can keep copies. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person. Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md). @@ -316,7 +313,7 @@ Do not run `cargo publish`; `publish = false`. CI needs the repo secret ## Not in v1 -Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, sqlcipher, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md). +Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md). ## License diff --git a/docs/SECURITY_AUDIT.md b/docs/SECURITY_AUDIT.md index f45747b..3c2322b 100644 --- a/docs/SECURITY_AUDIT.md +++ b/docs/SECURITY_AUDIT.md @@ -24,7 +24,7 @@ Original pass: rust-dev, no live hidden service / live wallet. Ignored tests ## Still true / not a “finding we forgot” -- Identity secret key and roster (pubkeys + locators) are **plaintext** in sqlite. Chat bodies are not. Seized laptop without FDE yields who you are and who you talk to. +- At rest the whole store is SQLCipher (Argon2id key over a 16-byte `store_salt`), so the identity secret key, roster (pubkeys + locators) and chat bodies are ciphertext on disk; chat bodies add a row-bound AEAD layer on top. That is not a defense against a live compromise or an attacker who has the passphrase — see [THREAT_MODEL.md](THREAT_MODEL.md). - Arti onion services are experimental. Fail closed; no C-tor fallback. - No public third-party audit, no `cargo-audit` gate in CI as of the original pass. - Invite decode still accepts the legacy concat signature (compatibility). From 381f4247339be5d1e26ee7bf2c8f08213f085497 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 12 Sep 2026 18:16:21 -0400 Subject: [PATCH 4/5] fix(sdk): surface Sent/Queued on send(), and build the SDK in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Node::send() became Result in the local-outbox work, which broke crates/onionwire-sdk — and nothing noticed, because the SDK is a separate cargo workspace that root CI never compiles. - Wire::send() returns WResult (Sent | Queued) - ChatMessage.delivery for outgoing rows - New sdk job in ci.yml (own target volume; rustls workspace) - Refresh SDK Cargo.lock + README (SQLCipher / outbox facts) Rebased onto main after #50/#54: no src/node.rs changes (WAL checkpoint lives in Store now). README at-rest claims kept from #55. --- .forgejo/workflows/ci.yml | 46 +++++++++++ README.md | 2 +- crates/onionwire-sdk/Cargo.lock | 25 ++++++ crates/onionwire-sdk/README.md | 20 +++-- crates/onionwire-sdk/src/lib.rs | 141 +++++++++++++++++++++++++++----- 5 files changed, 207 insertions(+), 27 deletions(-) diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 4c7b8aa..d922dfe 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -39,6 +39,11 @@ env: CARGO_REGISTRY_VOLUME: onionwire-cargo-registry CARGO_TARGET_VOLUME: onionwire-target-ci BUILD_CONTAINER: onionwire-ci-${{ github.run_id }} + # The SDK job gets its own target volume: it resolves the root crate with + # `rustls` instead of `native-tls`, so sharing a target dir would thrash both + # jobs' feature-unified artifacts. + SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk + SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }} jobs: test: @@ -73,3 +78,44 @@ jobs: tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \ | docker start -a -i "$BUILD_CONTAINER" docker rm -f "$BUILD_CONTAINER" > /dev/null + + # `crates/onionwire-sdk` is a SEPARATE cargo workspace: its own Cargo.lock and + # a path dependency on the root crate, resolved with `rustls` instead of + # `native-tls`. The `test` job above therefore never compiles it, so a + # root-crate signature change (`Node::send` gaining the outbox result, the + # SQLCipher passphrase entry points) breaks the Android SDK — and the tagged + # release AAR, since android-release.yml only builds on `v*.*.*` — while both + # the root suites and local `cargo test` stay green. Build it here. + sdk: + runs-on: docker + timeout-minutes: 120 + steps: + - name: Checkout + uses: https://code.forgejo.org/actions/checkout@v4 + + - name: cargo test + clippy for crates/onionwire-sdk on aarch64 + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + echo "workspace: $GITHUB_WORKSPACE" + docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null + docker volume create "$SDK_CARGO_TARGET_VOLUME" > /dev/null + docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null 2>&1 || true + docker create --name "$SDK_BUILD_CONTAINER" -i \ + -e CARGO_TARGET_DIR=/target \ + -e CARGO_BUILD_JOBS=2 \ + -e CARGO_TERM_COLOR=never \ + -v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \ + -v "$SDK_CARGO_TARGET_VOLUME":/target \ + -w /src \ + "$RUST_IMAGE" \ + sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src/crates/onionwire-sdk \ + && apt-get update \ + && apt-get install -y --no-install-recommends pkg-config libssl-dev \ + && rustup component add clippy \ + && cargo test --locked \ + && cargo clippy --locked --all-targets -- -D warnings' + tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \ + --exclude=./crates/onionwire-sdk/target . \ + | docker start -a -i "$SDK_BUILD_CONTAINER" + docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null diff --git a/README.md b/README.md index 5ae0162..4f0458f 100644 --- a/README.md +++ b/README.md @@ -286,7 +286,7 @@ FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z Workflows (Forgejo Actions, `.forgejo/workflows/`): -- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label. +- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs on the Pi runner (`docker` label), serialized by `onionwire-ci-pi`. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk` (separate cargo workspace — own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls` — so a root signature change cannot silently break the Android SDK). Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. - [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. Scripts: diff --git a/crates/onionwire-sdk/Cargo.lock b/crates/onionwire-sdk/Cargo.lock index 0422aac..62079af 100644 --- a/crates/onionwire-sdk/Cargo.lock +++ b/crates/onionwire-sdk/Cargo.lock @@ -2443,6 +2443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" dependencies = [ "cc", + "openssl-sys", "pkg-config", "vcpkg", ] @@ -2774,6 +2775,7 @@ dependencies = [ "rusqlite", "safelog", "serde_json", + "sha2", "sha3 0.10.9", "snow", "tokio", @@ -2781,6 +2783,7 @@ dependencies = [ "tor-hsservice", "tor-rtcompat", "x25519-dalek", + "zeroize", ] [[package]] @@ -2801,6 +2804,28 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "openssl-src" +version = "300.6.1+3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "openssl-src", + "pkg-config", + "vcpkg", +] + [[package]] name = "option-ext" version = "0.2.0" diff --git a/crates/onionwire-sdk/README.md b/crates/onionwire-sdk/README.md index 36e25a5..9072542 100644 --- a/crates/onionwire-sdk/README.md +++ b/crates/onionwire-sdk/README.md @@ -18,8 +18,8 @@ onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe. | Onion | A **locator**, not an identity. It rotates. | | Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` | | Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. | -| Fail closed | Peer onion down → the send fails. No outbox, no spool in v1. | -| At rest | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. | +| Chat send | Unreachable peer onion → the message goes to the **local outbox** and is retried with backoff. `send()` returns `SendState.Sent` or `SendState.Queued`. File transfer and payments stay fail-closed. | +| At rest | The whole sqlite file is SQLCipher (key = Argon2id of the store passphrase), and chat bodies carry a second per-row ChaCha20-Poly1305 layer with row-bound AAD. Identity keys live in that same encrypted file. | ### Invite string @@ -66,8 +66,10 @@ Requirements: ## Kotlin surface -Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes, -and a send retries the peer for up to 3 minutes before failing. +Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes. +A send that cannot reach the peer comes back immediately as `QUEUED` (it is not +a long retry inside the call): the message is stored locally and a background +worker in the core keeps retrying it. ```kotlin import uniffi.onionwire_sdk.* @@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted) // 4. Roster and chat. val roster: List = wire.friends() wire.setPetname(friend.pubkeyHex, "ada") -wire.send(friend.pubkeyHex, "hello wire") +when (wire.send(friend.pubkeyHex, "hello wire")) { + SendState.SENT -> { /* the peer's onion took the frame */ } + SendState.QUEUED -> { /* unreachable: stored in the local outbox and + retried in the background. Show it as pending — + it is local-only until a circuit takes it. */ } +} val msgs: List = wire.messages(friend.pubkeyHex) +// msgs[i].direction == "out" -> msgs[i].delivery is "sent" | "queued" | +// "sending" | "failed: "; null for incoming messages. Render the +// queued and failed states distinctly from sent. // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds // the SDK owns the typed confirmation. diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 90e5b55..5657948 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -11,7 +11,10 @@ //! 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. Identity keys in sqlite are not. +//! * 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. //! //! Lifecycle: a node is started by [`open_wire`] and stopped by //! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable @@ -27,7 +30,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use onionwire::hs::TorState as CoreTorState; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; -use onionwire::qr; +use onionwire::outbox::OutboxStatus;use onionwire::qr; uniffi::setup_scaffolding!(); @@ -98,11 +101,34 @@ pub struct FriendInfo { 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)] @@ -332,34 +358,44 @@ impl Wire { .map_err(WireError::new) } - /// Send one message. Returns once the outcome is known: delivered now, or - /// queued for retry because the peer's onion is unreachable. A protocol - /// error (bad signature, bad frame) still fails immediately and is never - /// queued. Use [`flush`](Self::flush) to retry the queue on demand. - pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> { + /// 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)?; - self.node()? + let status = self + .node()? .send(&pk, body.as_bytes()) .await .map_err(WireError::new)?; - Ok(()) - } + Ok(send_state(status)) } /// Chat history for a friend, oldest first. Bodies are decrypted here; - /// they are stored encrypted at rest. + /// 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 - .node()? - .list_messages(&pk) - .map_err(WireError::new)?; - Ok(rows - .into_iter() - .map(|m| ChatMessage { + let rows = self.node()?.list_messages(&pk).map_err(WireError::new)?; + let mut out = Vec::with_capacity(rows.len()); + for m in rows { + let status = self + .node()? + .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, - body: String::from_utf8_lossy(&m.plaintext).into_owned(), - }) - .collect()) + }); + } + Ok(out) } /// Delete every message body. Identity and friends survive. @@ -415,6 +451,30 @@ fn unhex(s: &str) -> WResult> { .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 { //! No Tor here on purpose: these exercise the *lifecycle* contract of the @@ -422,6 +482,7 @@ mod tests { //! node is exactly the state `shutdown()` leaves behind. use super::*; + use onionwire::outbox::OutboxStatus; fn stopped_wire() -> Wire { Wire { @@ -482,4 +543,42 @@ mod tests { ); assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped); } + +#[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") + ); + } } + From 92d921e7599e22c663f800d44fdb7a2f4e65f937 Mon Sep 17 00:00:00 2001 From: Hermes apk-dev Date: Sat, 12 Sep 2026 15:47:14 -0400 Subject: [PATCH 5/5] fix(android): surface the outbox send state instead of denying it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SDK has returned `SendState` and a per-row `ChatMessage.delivery` since the local outbox landed, but the app still said "there is no outbox in v1" and threw the state away. - `WireViewModel.send()` returns `SendState`; `ChatScreen` no longer discards it. A `QUEUED` send raises a "local-only until the retry worker gets a circuit through" hint instead of pretending success. - Outgoing rows render the TUI's delivery markers from `ChatMessage.delivery` (`✓` / `◷ queued` / `» sending` / `✗ failed: `), plus the TUI's `{n} queued` footer while the outbox still owns rows. Incoming rows stay unmarked; an unreadable state renders no marker rather than a tick. - The empty-chat copy describes the outbox (8 attempts, backoff capped at 30 min, local-only until it lands) instead of denying it exists. - New pure `Delivery.kt` so the vocabulary is unit-testable without a device. Verified: `./gradlew :app:assembleDebug :app:testDebugUnitTest` → BUILD SUCCESSFUL, 15 tests / 0 failures (10 new), APK contains the new copy and no longer the "There is no outbox" string. Stacked on the SDK fix (PR #51). --- .../siriusdevops/onionwire/WireViewModel.kt | 11 +- .../siriusdevops/onionwire/ui/ChatScreen.kt | 116 +++++++++++++++--- .../com/siriusdevops/onionwire/ui/Delivery.kt | 78 ++++++++++++ .../onionwire/ui/DeliveryMarkerTest.kt | 85 +++++++++++++ 4 files changed, 271 insertions(+), 19 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt create mode 100644 android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 579de57..6b72d75 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -21,6 +21,7 @@ import uniffi.onionwire_sdk.ChatMessage import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.InviteInfo import uniffi.onionwire_sdk.RotateOutcome +import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File @@ -361,7 +362,15 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun messages(pubkeyHex: String): List = requireWire().messages(pubkeyHex) - suspend fun send(pubkeyHex: String, body: String) = + /** + * Hands the body to the node and reports what happened to it. + * + * `SENT` means the peer's onion took the frame during this call. `QUEUED` + * means it did not: the message is in the local outbox, local-only until + * the retry worker gets a circuit through. The caller must not render + * `QUEUED` as delivered. + */ + suspend fun send(pubkeyHex: String, body: String): SendState = requireWire().send(pubkeyHex, body) suspend fun wipeMessages() { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt index fbfa709..9bffca7 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/ChatScreen.kt @@ -37,6 +37,12 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay import uniffi.onionwire_sdk.ChatMessage +import uniffi.onionwire_sdk.SendState + +/** Shown after a `Queued` send — the TUI's composer keeps `{n} queued`. */ +private const val QUEUED_HINT = + "Queued: their onion is unreachable. The message is local-only in this " + + "device's outbox until the retry worker gets a circuit through." @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -45,13 +51,14 @@ fun ChatScreen( fingerprint: String, onion: String, loadMessages: suspend () -> List, - onSend: suspend (String) -> Unit, + onSend: suspend (String) -> SendState, onBack: () -> Unit, ) { var messages by remember { mutableStateOf?>(null) } var draft by remember { mutableStateOf("") } var pending by remember { mutableStateOf(null) } var error by remember { mutableStateOf(null) } + var hint by remember { mutableStateOf(null) } val listState = rememberLazyListState() // Poll: the node appends inbound messages in the background; there is no @@ -65,16 +72,32 @@ fun ChatScreen( } } - // Fail-closed send. `send` retries the peer's onion for up to 3 minutes and - // then errors — nothing is spooled, so a failure is a real failure. + // Fail closed — but not fail lost. `send` returns `Queued` when the peer's + // onion is unreachable: the body is in this device's local outbox and the + // retry worker keeps trying. It only surfaces as a hard error when the + // node itself refuses the write. LaunchedEffect(pending) { val body = pending ?: return@LaunchedEffect error = null + hint = null runCatching { onSend(body) } + .onSuccess { state -> + // Never dress a queued send up as delivered. + hint = if (state == SendState.QUEUED) QUEUED_HINT else null + } .onFailure { error = it.message ?: it.toString() } pending = null } + // The hint is a toast, not a log line: the row marker and the `N queued` + // footer are what stay on screen. + LaunchedEffect(hint) { + if (hint != null) { + delay(6_000) + hint = null + } + } + LaunchedEffect(messages?.size) { val n = messages?.size ?: 0 if (n > 0) listState.animateScrollToItem(n - 1) @@ -127,8 +150,13 @@ fun ChatScreen( Text("No messages", style = MaterialTheme.typography.titleSmall) Spacer(Modifier.height(6.dp)) Text( - "Sends fail closed: if their onion is down the message is " + - "not spooled anywhere. There is no outbox in v1.", + "Sends fail closed — nothing goes to a third party. If their " + + "onion is unreachable the message is queued in this " + + "device's outbox instead of being dropped: it stays " + + "local-only until the retry worker gets a circuit " + + "through (8 attempts, backoff capped at 30 min), then it " + + "lands. \u2713 means delivered, \u25f7 queued, " + + "\u2717 failed.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -149,25 +177,77 @@ fun ChatScreen( horizontalArrangement = if (mine) Arrangement.End else Arrangement.Start, ) { - Text( - m.body, - style = MaterialTheme.typography.bodyMedium, - color = if (mine) MaterialTheme.colorScheme.onPrimary - else MaterialTheme.colorScheme.onSurface, - modifier = Modifier - .background( - if (mine) MaterialTheme.colorScheme.primary - else MaterialTheme.colorScheme.surfaceVariant, - RoundedCornerShape(10.dp), - ) - .padding(horizontal = 10.dp, vertical = 8.dp), - ) + Column( + horizontalAlignment = + if (mine) Alignment.End else Alignment.Start, + ) { + Text( + m.body, + style = MaterialTheme.typography.bodyMedium, + color = if (mine) MaterialTheme.colorScheme.onPrimary + else MaterialTheme.colorScheme.onSurface, + modifier = Modifier + .background( + if (mine) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.surfaceVariant, + RoundedCornerShape(10.dp), + ) + .padding(horizontal = 10.dp, vertical = 8.dp), + ) + // Outgoing rows only: the SDK reports `null` for + // inbound, and an outgoing row with no outbox + // entry reads "sent". + if (mine) { + deliveryMarker(m.delivery)?.let { marker -> + Text( + marker.text, + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = when (marker.tone) { + DeliveryTone.SENT -> + MaterialTheme.colorScheme.onSurfaceVariant + + DeliveryTone.PENDING -> + MaterialTheme.colorScheme.tertiary + + DeliveryTone.FAILED -> + MaterialTheme.colorScheme.error + }, + modifier = Modifier.padding( + top = 2.dp, + end = 2.dp, + ), + ) + } + } + } } } } } } + // TUI footer: `{n} queued` while the outbox still owns rows. + val queued = list?.count { it.direction == "out" && isOutboxPending(it.delivery) } ?: 0 + if (queued > 0) { + Text( + "$queued queued", + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + + hint?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + error?.let { Text( it, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt new file mode 100644 index 0000000..a26766d --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Delivery.kt @@ -0,0 +1,78 @@ +package com.siriusdevops.onionwire.ui + +/** + * Per-row delivery markers for outgoing chat messages. + * + * The vocabulary is the TUI's (`docs/TUI.md` → "Delivery state (outbox)"), so + * both clients read the same: + * + * ``` + * ✓ delivered — the peer's onion took the frame + * ◷ queued in this device's local outbox, waiting for a circuit + * » sending the retry worker has it in flight + * ✗ failed: … terminally failed (8 attempts, backoff capped at 30 min) + * ``` + * + * The string comes from `ChatMessage.delivery` and is produced by the store's + * own outbox status — `"sent"` / `"queued"` / `"sending"` / + * `"failed: "` for outgoing rows, `null` for incoming ones. An outgoing + * row with no outbox row was accepted on the first attempt and reads `"sent"`. + * + * Nothing here guesses: a delivery string this build does not recognise renders + * no marker rather than a tick, because a missing marker never claims delivery + * while a wrong tick does. + */ + +/** Which colour the marker is drawn in. */ +internal enum class DeliveryTone { + /** Delivered to the peer's onion. */ + SENT, + + /** Still local-only: queued, or being retried right now. */ + PENDING, + + /** Out of attempts — the message never left this device. */ + FAILED, +} + +internal data class DeliveryMarker(val text: String, val tone: DeliveryTone) + +/** + * Longest `failed: ` tail we render before eliding. The TUI caps the + * same reason at 24 cells for its 80-column row; a phone bubble wraps, so this + * only exists to stop a pathological Tor error from filling the screen. + */ +private const val MAX_REASON_CHARS = 48 + +/** Marker for one outgoing row, or `null` when there is nothing to say. */ +internal fun deliveryMarker(delivery: String?): DeliveryMarker? { + val state = delivery?.trim().orEmpty() + if (state.isEmpty()) return null + return when { + state == "sent" -> DeliveryMarker("\u2713", DeliveryTone.SENT) + state == "queued" -> DeliveryMarker("\u25f7 queued", DeliveryTone.PENDING) + state == "sending" -> DeliveryMarker("\u00bb sending", DeliveryTone.PENDING) + state.startsWith("failed") -> { + val reason = shortReason(state.substringAfter(':', "").trim()) + DeliveryMarker( + if (reason.isEmpty()) "\u2717 failed" else "\u2717 failed: $reason", + DeliveryTone.FAILED, + ) + } + // Unknown state: never render a tick for something we cannot read. + else -> null + } +} + +/** True while the outbox still owns the row — the TUI's `{n} queued` footer. */ +internal fun isOutboxPending(delivery: String?): Boolean { + val state = delivery?.trim().orEmpty() + return state == "queued" || state == "sending" +} + +private fun shortReason(reason: String): String = + if (reason.length <= MAX_REASON_CHARS) { + reason + } else { + reason.take(MAX_REASON_CHARS - 1).trimEnd() + "\u2026" + } diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt new file mode 100644 index 0000000..6340190 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/DeliveryMarkerTest.kt @@ -0,0 +1,85 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The delivery vocabulary is shared with the TUI (`docs/TUI.md` → "Delivery + * state (outbox)"). These strings are the SDK's contract + * (`crates/onionwire-sdk/src/lib.rs`), so a drift here is a client that lies + * about a message having landed. + */ +class DeliveryMarkerTest { + + @Test + fun delivered_row_gets_a_tick() { + val m = deliveryMarker("sent") + assertEquals(DeliveryMarker("\u2713", DeliveryTone.SENT), m) + } + + @Test + fun queued_row_says_queued_not_delivered() { + val m = deliveryMarker("queued") + assertEquals(DeliveryMarker("\u25f7 queued", DeliveryTone.PENDING), m) + } + + @Test + fun sending_row_is_pending() { + val m = deliveryMarker("sending") + assertEquals(DeliveryMarker("\u00bb sending", DeliveryTone.PENDING), m) + } + + @Test + fun failed_row_carries_the_reason() { + val m = deliveryMarker("failed: connection timed out") + assertEquals(DeliveryMarker("\u2717 failed: connection timed out", DeliveryTone.FAILED), m) + } + + @Test + fun failed_row_without_a_reason_still_reads_failed() { + assertEquals( + DeliveryMarker("\u2717 failed", DeliveryTone.FAILED), + deliveryMarker("failed"), + ) + } + + @Test + fun a_long_reason_is_elided() { + val m = deliveryMarker("failed: " + "x".repeat(200)) + val text = m?.text.orEmpty() + assertTrue(text.startsWith("\u2717 failed: xxx")) + assertTrue(text.endsWith("\u2026")) + assertTrue("marker grew to ${text.length} chars", text.length <= 48 + "\u2717 failed: ".length) + } + + @Test + fun incoming_row_has_no_marker() { + assertNull(deliveryMarker(null)) + assertNull(deliveryMarker("")) + assertNull(deliveryMarker(" ")) + } + + @Test + fun unknown_state_never_claims_delivery() { + // Fail-safe: an unreadable state renders nothing rather than a tick. + assertNull(deliveryMarker("scheduled")) + assertNull(deliveryMarker("SENT")) + } + + @Test + fun surrounding_whitespace_is_tolerated() { + assertEquals(DeliveryTone.SENT, deliveryMarker(" sent ")?.tone) + } + + @Test + fun pending_counts_only_queued_and_sending() { + assertTrue(isOutboxPending("queued")) + assertTrue(isOutboxPending("sending")) + assertFalse(isOutboxPending("sent")) + assertFalse(isOutboxPending("failed: no route")) + assertFalse(isOutboxPending(null)) + } +}