From cf0a517cd20169c1bce952a420500880893680a2 Mon Sep 17 00:00:00 2001 From: Lance Walters Date: Sun, 13 Sep 2026 23:25:25 -0400 Subject: [PATCH 1/8] wallet: create/import in-app (no key paste on create) + opt-in spend / wallet create generates a wallet on the RPC and shows the 25-word seed once for backup; /wallet import is the only path that takes an existing seed, and it is collected on a dedicated screen so it never reaches the composer line or chat history. Threat model now states the real policy: payments are opt-in, default is no spend key, spend is a local authority at create/restore, and the chain source is the user's choice (spawned local monerod or a daemon address they supply). WALLET.md and README follow. Tests: canned-RPC create/restore, slash parse, help overlay. --- README.md | 11 +- .../siriusdevops/onionwire/WireViewModel.kt | 12 + .../siriusdevops/onionwire/ui/WalletScreen.kt | 167 +++++++++++- crates/onionwire-sdk/src/lib.rs | 24 ++ docs/THREAT_MODEL.md | 87 +++++-- docs/WALLET.md | 58 ++++- src/node.rs | 23 ++ src/tui.rs | 241 +++++++++++++++++- src/wallet.rs | 65 +++++ tests/pay.rs | 3 + tests/tui_chrome.rs | 3 + tests/wallet.rs | 106 ++++++++ 12 files changed, 755 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index e74628f..7c86293 100644 --- a/README.md +++ b/README.md @@ -185,9 +185,14 @@ resume, no images in the TUI. `/profile` edits your friend-visible display name, bio, and optional Monero address (64 / 512 byte limits, no images). Enter saves and one-shot sends a signed `prf` frame to the selected friend. `F5` or `/who` shows their last signed profile. There is no directory: unknown pubkeys are ignored. -## Monero sidecar +## Monero (opt-in) -OnionWire is not a wallet. Optional JSON-RPC to a user-hosted `monero-wallet-rpc`. The wallet **must** use `--rpc-login`; OnionWire refuses an open RPC (HTTP 200 without a Digest challenge) and refuses URLs with no credentials. +Chat does not need a wallet. Spend is opt-in at wallet create/restore; default +is no spend key on the device. Optional JSON-RPC to `monero-wallet-rpc` on +loopback (you run it, or the app spawns it). Chain source is your choice: a +spawned local `monerod`, or a daemon address you supply. The wallet **must** +use `--rpc-login`; OnionWire refuses an open RPC (HTTP 200 without a Digest +challenge) and refuses URLs with no credentials. ```bash # monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret @@ -206,6 +211,8 @@ locally before any RPC dial — `/pay` and receipt verification keep working. Details: [docs/WALLET.md](docs/WALLET.md). - `/pay [memo]` — invoice (we want to receive). Uses a wallet subaddress if RPC is up, else the profile `xmr_addr`. +- `/wallet create` — generate a new spend-capable wallet (no key paste; seed shown once). Needs `--wallet-dir` on the RPC. +- `/wallet import` — restore from an existing 25-word seed (the only path that takes a secret). - `/tip [memo]` — pay the selected friend’s profile address, then send a signed `rcp` (disabled under `ONIONWIRE_WALLET_NO_SPEND`). Incoming receipts stay unverified until RPC `get_transfers` matches. ## Backup / restore 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 b25a0c0..dfe66e0 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -428,4 +428,16 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result = runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) } + + suspend fun createWallet(password: String): Result = + runCatching { requireWire().createWallet(password) } + + suspend fun importWallet(password: String, seed: String): Result = + runCatching { requireWire().importWallet(password, seed) } + + fun spendAuthorityWarning(): String = runCatching { + requireWire().spendAuthorityWarning() + }.getOrElse { + "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed." + } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index a4d3776..0e5d8e8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -47,11 +47,13 @@ import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.qrcode.QRCodeWriter import com.siriusdevops.onionwire.WireViewModel +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.TransferRow private enum class PayKind { Invoice, Tip } +private enum class SetupKind { Create, Import } @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -67,6 +69,8 @@ fun WalletScreen( var transfers by remember { mutableStateOf>(emptyList()) } var error by remember { mutableStateOf(null) } var composer by remember { mutableStateOf(null) } + var setup by remember { mutableStateOf(null) } + var backupSeed by remember { mutableStateOf(null) } suspend fun reload() { runCatching { balance = vm.walletBalance() } @@ -183,6 +187,7 @@ fun WalletScreen( } val kind = composer + val setupKind = setup if (kind != null) { PayComposer( kind = kind, @@ -205,24 +210,72 @@ fun WalletScreen( } }, ) + } else if (setupKind != null) { + WalletSetupCard( + kind = setupKind, + warning = vm.spendAuthorityWarning(), + onCancel = { setup = null }, + onCreated = { seed -> + setup = null + backupSeed = seed + scope.launch { reload() } + }, + onImported = { + setup = null + scope.launch { reload() } + }, + onError = { error = it }, + create = { pw -> vm.createWallet(pw) }, + importWallet = { pw, seed -> vm.importWallet(pw, seed) }, + scope = scope, + ) } else { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(12.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedButton( - onClick = { composer = PayKind.Invoice }, - modifier = Modifier.weight(1f), - ) { Text("Invoice") } - OutlinedButton( - onClick = { composer = PayKind.Tip }, - modifier = Modifier.weight(1f), - ) { Text("Tip") } + Column(Modifier.fillMaxWidth().padding(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton( + onClick = { composer = PayKind.Invoice }, + modifier = Modifier.weight(1f), + ) { Text("Invoice") } + OutlinedButton( + onClick = { composer = PayKind.Tip }, + modifier = Modifier.weight(1f), + ) { Text("Tip") } + } + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton( + onClick = { setup = SetupKind.Create }, + modifier = Modifier.weight(1f), + ) { Text("Create") } + OutlinedButton( + onClick = { setup = SetupKind.Import }, + modifier = Modifier.weight(1f), + ) { Text("Import") } + } } } + backupSeed?.let { seed -> + Text( + "write this seed down once. anyone with it can spend.", + style = MaterialTheme.typography.labelSmall, + modifier = Modifier.padding(horizontal = 12.dp), + ) + Text( + seed, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + TextButton(onClick = { backupSeed = null }) { Text("I wrote it down") } + } + error?.let { Text( it, @@ -347,6 +400,92 @@ private fun PayComposer( } } +@Composable +private fun WalletSetupCard( + kind: SetupKind, + warning: String, + onCancel: () -> Unit, + onCreated: (String) -> Unit, + onImported: () -> Unit, + onError: (String) -> Unit, + create: suspend (String) -> Result, + importWallet: suspend (String, String) -> Result, + scope: CoroutineScope, +) { + var accepted by remember { mutableStateOf(kind != SetupKind.Create) } + var password by remember { mutableStateOf("") } + var seed by remember { mutableStateOf("") } + val ready = password.isNotEmpty() && (kind == SetupKind.Create || seed.isNotBlank()) + + Card( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text( + if (kind == SetupKind.Create) "Create wallet" else "Import wallet", + style = MaterialTheme.typography.titleSmall, + ) + Spacer(Modifier.height(8.dp)) + if (kind == SetupKind.Create && !accepted) { + Text(warning, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text("Cancel") } + Button(onClick = { accepted = true }) { Text("I accept spend authority") } + } + return@Column + } + if (kind == SetupKind.Import) { + Text( + "Paste the 25-word seed. Create does not need a key.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = seed, + onValueChange = { seed = it }, + label = { Text("seed") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + } + OutlinedTextField( + value = password, + onValueChange = { password = it }, + singleLine = true, + label = { Text("wallet passphrase") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text("Cancel") } + Button( + onClick = { + scope.launch { + when (kind) { + SetupKind.Create -> create(password).fold( + onSuccess = onCreated, + onFailure = { onError(it.message ?: it.toString()) }, + ) + SetupKind.Import -> importWallet(password, seed.trim()).fold( + onSuccess = { onImported() }, + onFailure = { onError(it.message ?: it.toString()) }, + ) + } + } + }, + enabled = ready, + ) { Text(if (kind == SetupKind.Create) "Create" else "Import") } + } + } + } +} + /** Generate a QR bitmap for the given URI string. Returns null on encode failure. */ internal fun generateQrBitmap(uri: String): Bitmap? { return try { diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index df25c28..136b815 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -575,6 +575,30 @@ impl Wire { .await .map_err(WireError::new) } + + /// Create a new spend-capable wallet. Returns the 25-word seed once so the + /// UI can show a backup screen. The user does not paste a key on this path. + /// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC. + pub async fn create_wallet(&self, password: String) -> WResult { + self.node()? + .wallet_create(&password) + .await + .map_err(WireError::new) + } + + /// Import a wallet from an existing 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { + self.node()? + .wallet_restore(&password, &seed) + .await + .map_err(WireError::new) + } + + /// Spend-authority warning shown before create. Not a tooltip. + pub fn spend_authority_warning(&self) -> String { + onionwire::wallet::SPEND_AUTHORITY_WARNING.to_string() + } } fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome { diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 48daf63..006ee1f 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -69,21 +69,61 @@ The queue is bounded in scope: chat only. File transfer and `rcp` frames are one A signed `prf` frame is shown to people who already have a session with you. Apply only for existing friends. There is still no name lookup, DHT, or public profile server. Anyone who already has a Noise session can see the profile you send them; that is not confidentiality against that friend. -## Monero sidecar is not a wallet +## Payments are opt-in; spend is a local authority -OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy. +Chat does not need a wallet. Payment frames (`inv`, `rcp`, `tip`) are signed +claims over Noise: a signature proves which friend sent the claim, not that +money moved. `verified=1` only after a conjunctive match — one `get_transfers` +row with the same non-empty `txid`, `amount`, and `address`. RPC down, error, or +no exact row → stay `verified=0`. Subaddress reuse is the user’s wallet policy. -Run it **view-only** (recommended). `/pay` and receipt verification need only -`create_address`/`get_transfers`, which a wallet without a spend key serves -fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC -dial, and a view-only wallet is detected over RPC (`query_key` -`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says -so plainly instead of failing with a raw wallet error. The trade-off is -explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local -spend authority — any process that can read the RPC credentials can move the -balance, and `/tip` gives a chat peer a supported way to ask for a transfer. -Loopback binding is not an authorization boundary. Full setup, view-only wallet -creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md). +**Default: no spend.** No seed and no spend key on the device. Receive can use +the profile `xmr_addr`, or a view-only wallet (`create_address` / +`get_transfers` only). `/tip` is off (`ONIONWIRE_WALLET_NO_SPEND`, or a +watch-only wallet detected over RPC via `query_key spend_key` → `-29`). + +**Spend is opt-in**, at wallet create or restore, not a hidden default. A +seed-backed spend-capable wallet makes OnionWire a **local spend authority** +for that file: anyone with the wallet passphrase or the wallet-RPC credentials +can move the balance, and `/tip` is a supported way for a chat peer to get paid. +The spend-authority warning is unavoidable at that create/restore step. Loopback +binding is not an authorization boundary. Back up the seed; do not leave a +spend-capable wallet on a device you do not trust; a separate hot wallet with a +small balance is the sane spend shape, not savings. + +The app talks to `monero-wallet-rpc` over **loopback HTTP Digest** only +(`--rpc-login` required; open RPC refused). That process may be one the user +already runs, or one the app spawns. Wallet RPC is never dialed over clearnet or +over `.onion` — a remote wallet RPC would move spend authority off the box +through a channel the messenger’s `--password` gate does not cover. + +### Chain source is the user’s choice + +Scan, receipt verification, and spend need a Monero daemon. The user picks one; +the app does not pick a public remote node for them. + +1. **Spawn a local `monerod`** (pruned is the on-device target). Chain traffic + stays on the device. The user accepts disk (tens of GB for a pruned mainnet + node), first-sync time, and — on Android — process kills: the daemon is not + always running. A pruned node is not an archive. Seed restore of deep history + can degrade; once the wallet has scanned, its own cache is the history. + Unsynced or not running is an honest “not ready” / unverified state, not a + fake success. + +2. **A daemon address they supply.** The wallet child points `--daemon-address` + at that host. Trust follows the address: + - **Loopback** — same privacy as (1); the user owns `monerod`. + - **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener + the app provides for the wallet child (not the messenger’s Arti + `connect()`, and not a C-tor fallback for chat). Tor hides the transport. + The daemon operator still sees the wallet’s addresses during sync. The + host is the trust boundary. + - **Clearnet** — only if the user typed it. Not a default, not implied. + The ISP sees Monero-node traffic; the daemon operator sees addresses. Show + that trust shift before using the address. + +Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs +spend, and RPC credentials: [WALLET.md](WALLET.md). ## Backup file is the identity @@ -96,12 +136,23 @@ Incoming rendezvous accepts are token-bucket limited (30/60s, burst 10). Excess ## Network (UDP / clearnet) The application does not open UDP sockets and does not resolve friends via -system DNS. Peer dials are Arti `connect((onion, 80))` only. The one -intentional clearnet socket is optional `monero-wallet-rpc` on **loopback TCP** -(numeric loopback preferred; `localhost` still does `getaddrinfo`). +system DNS. Peer dials are Arti `connect((onion, 80))` only. -Do not add STUN/ICE/WebRTC, a DHT, SOCKS/C-tor fallback, or “direct TCP when -the onion is slow.” Those are the Tox-over-Tor leak class. +Wallet **RPC** (HTTP Digest to `monero-wallet-rpc`) is loopback TCP only +(numeric `127.0.0.1` / `::1` preferred; `localhost` still does `getaddrinfo`). +That socket is the app talking to the wallet process, not to the chain. + +**Chain** traffic is the wallet child’s connection to a Monero daemon. It is +off unless the user opted into a wallet and chose a chain source: spawned local +`monerod` (loopback), or a daemon address they entered. A `.onion` daemon is +reached through a localhost SOCKS5 proxy used only by that wallet child. A +clearnet daemon address is an explicit user choice — a clearnet socket they +asked for — not the messenger path and not a hidden default. + +Do not add STUN/ICE/WebRTC, a DHT, SOCKS/C-tor fallback for **peer dials**, or +“direct TCP when the onion is slow.” Those are the Tox-over-Tor leak class. A +SOCKS listener used only by the wallet child to reach a user-chosen `.onion` +daemon is not that class. ## Peer text is untrusted display data diff --git a/docs/WALLET.md b/docs/WALLET.md index 7da17bc..9975bc7 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -1,14 +1,23 @@ # OnionWire + monero-wallet-rpc -OnionWire is not a wallet. It never holds a seed, a spend key, or a view key. -It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on -loopback, only to: +Chat does not require a wallet. A wallet is opt-in. + +**Default: no spend.** No seed and no spend key on the device. Receive uses the +profile `xmr_addr`, or a view-only wallet for invoices (`create_address`) and +receipt checks (`get_transfers`). `/tip` is off. + +**Spend is opt-in** at wallet create or restore (seed-backed). That makes +OnionWire a local spend authority for that wallet file — see the spend-authority +warning below. The threat-model write-up is [THREAT_MODEL.md](THREAT_MODEL.md). + +The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, whether +that process is one you already run or one the app spawns: - hand out a receive subaddress for `/pay` invoices (`create_address`), - read incoming transfers to verify a peer's receipt (`get_transfers`), -- and — only if you let it — spend for `/tip` (`transfer`). +- and — only if you opted into spend — `/tip` (`transfer`). -**Run it view-only, and switch `/tip` off explicitly.** Everything else in this +**Prefer view-only until you actually want `/tip`.** Everything else in this document explains why, and what breaks when you do. ## Env vars @@ -21,6 +30,20 @@ document explains why, and what breaks when you do. `README.md` carries the operator summary; this file is the long form. +## Create vs import + +Create does **not** take a private key. `/wallet create` (TUI: F6 then `c`) asks +the RPC to generate a new spend-capable wallet (`create_wallet`), then shows the +seed **once** for backup (`query_key mnemonic`). Type `SPEND` to accept the +spend-authority warning, set a passphrase, write the seed down, type `SEEN`. + +Import is the only path that takes an existing secret: `/wallet import` (F6 then +`i`) pastes the 25-word seed into `restore_deterministic_wallet`. Do not put the +seed on the composer line — it would sit in chat history. + +The RPC must be started with `--wallet-dir` (not only `--wallet-file`) or create +and import fail. The in-app filename is `onionwire`. + ## Recommended topology ``` @@ -34,9 +57,26 @@ document explains why, and what breaks when you do. └──────────────────────────────────────────────────────────────┘ ``` -Loopback is the only address OnionWire will dial. `.onion` RPC URLs are -rejected: there is no Arti dial for the wallet, and a remote wallet would move -your key material off the box. +Loopback is the only address OnionWire will dial for **wallet RPC**. `.onion` +wallet-RPC URLs are rejected: there is no Arti dial for the wallet process, and +a remote wallet RPC would move spend authority off the box. + +## Chain source + +The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire +does not pick a public remote node for you. + +1. **Spawn a local `monerod`** (pruned on-device). Chain traffic stays on the + box. You accept disk, first sync, and (on Android) the daemon not always + running. +2. **A daemon address you supply** — `--daemon-address` on the wallet child. + Loopback if you already run `monerod`. `.onion` if you want chain traffic + over Tor (wallet child `--proxy` to a localhost SOCKS listener; the daemon + operator still sees addresses). Clearnet only if you type it — ISP sees + Monero-node traffic; not a default. + +Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable +→ receipts stay unverified and spend is refused. That is the honest state. ## Create a view-only wallet @@ -88,7 +128,7 @@ Restore the wallet from a height *at or before* its first incoming transaction | Receipt verification (`get_transfers`) | works | works | | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | -| OnionWire learns your spend key | never | never (it stays in the wallet) | +| OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) | With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is contacted, with: diff --git a/src/node.rs b/src/node.rs index ee21275..5ca5bbe 100644 --- a/src/node.rs +++ b/src/node.rs @@ -684,6 +684,29 @@ impl Node { Ok(rows.into_iter().take(cap).collect()) } + /// Create a new spend-capable wallet. Returns the seed once for backup. + /// The user never pastes a key on this path. + pub async fn wallet_create(&self, password: &str) -> Result { + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); + } + self.wallet + .create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) + .await + .map_err(|e| e.to_string()) + } + + /// Import a wallet from an existing 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); + } + self.wallet + .restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) + .await + .map_err(|e| e.to_string()) + } async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { self.ensure_running()?; diff --git a/src/tui.rs b/src/tui.rs index e149d9a..8622ca5 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -454,9 +454,12 @@ OnionWire keys\n\ F3 paste invite\n\ F4 rotate onion locator\n\ F5 selected friend's profile (/who)\n\ + F6 wallet (receive QR, create/import)\n\ /profile edit name, bio, Monero address\n\ /pay [memo] invoice to receive\n\ /tip [memo] pay selected friend\n\ + /wallet create new spend wallet (seed shown once)\n\ + /wallet import restore from existing seed\n\ /file /path send file to selected friend (1 MiB)\n\ /backup /path encrypted identity export\n\ /restore /path overwrite self keys\n\ @@ -562,6 +565,8 @@ pub enum SlashCmd { Backup { path: String }, Restore { path: String }, File { path: String }, + WalletCreate, + WalletImport, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -710,6 +715,11 @@ pub fn parse_cmd(raw: &str) -> Option { { return parse_path_cmd(rest).map(|path| SlashCmd::File { path }); } + match s { + "/wallet create" => return Some(SlashCmd::WalletCreate), + "/wallet import" => return Some(SlashCmd::WalletImport), + _ => {} + } None } @@ -1118,11 +1128,20 @@ enum Screen { transfers: Vec, qr_modal: Option, }, + WalletSetup(WalletSetup), Quit { prompt: QuitPrompt, }, } +enum WalletSetup { + CreateWarn { typed: String }, + CreatePass { entry: PassphraseEntry }, + CreateSeed { seed: Zeroizing, typed: String }, + ImportSeed { buf: Zeroizing }, + ImportPass { seed: Zeroizing, entry: PassphraseEntry }, +} + impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; @@ -1276,6 +1295,18 @@ impl App { self.composer.clear(); file_cmd = Some(path); } + Some(ComposerAction::Cmd(SlashCmd::WalletCreate)) => { + self.composer.clear(); + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + Some(ComposerAction::Cmd(SlashCmd::WalletImport)) => { + self.composer.clear(); + self.screen = Screen::WalletSetup(WalletSetup::ImportSeed { + buf: Zeroizing::new(String::new()), + }); + } Some(ComposerAction::Send(text)) => { self.composer.clear(); chat_send = Some(text); @@ -1394,8 +1425,19 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + KeyCode::Char('c') => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + KeyCode::Char('i') => { + self.screen = Screen::WalletSetup(WalletSetup::ImportSeed { + buf: Zeroizing::new(String::new()), + }); + } _ => {} }, + Screen::WalletSetup(_) => self.handle_wallet_setup(key)?, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1663,6 +1705,151 @@ impl App { }); } + fn handle_wallet_setup(&mut self, key: KeyEvent) -> Result<(), String> { + let Screen::WalletSetup(setup) = &mut self.screen else { + return Ok(()); + }; + if key.code == KeyCode::Esc { + match setup { + WalletSetup::CreatePass { entry } | WalletSetup::ImportPass { entry, .. } => { + entry.close(); + } + WalletSetup::CreateSeed { seed, .. } => seed.zeroize(), + WalletSetup::ImportSeed { buf } => buf.zeroize(), + WalletSetup::CreateWarn { .. } => {} + } + self.screen = Screen::Main; + return Ok(()); + } + match setup { + WalletSetup::CreateWarn { typed } => match key.code { + KeyCode::Char(c) if c.is_ascii_alphabetic() => { + typed.push(c); + if typed.eq_ignore_ascii_case("SPEND") { + self.screen = Screen::WalletSetup(WalletSetup::CreatePass { + entry: PassphraseEntry::new(), + }); + } + } + KeyCode::Backspace => { + typed.pop(); + } + _ => {} + }, + WalletSetup::CreatePass { entry } => match key.code { + KeyCode::Backspace => entry.backspace(), + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + entry.push(c); + } + KeyCode::Enter => { + let first = entry.take_first(); + let pass = entry.take_buf(); + if let Some(first) = first { + if first.as_str() != pass.as_str() { + entry.close(); + self.alert = Some("passphrases do not match".into()); + self.screen = Screen::Main; + return Ok(()); + } + match self.rt.block_on(self.node.wallet_create(pass.as_str())) { + Ok(seed) => { + self.screen = Screen::WalletSetup(WalletSetup::CreateSeed { + seed: Zeroizing::new(seed), + typed: String::new(), + }); + } + Err(e) => { + self.alert = Some(e); + self.screen = Screen::Main; + } + } + } else { + self.screen = Screen::WalletSetup(WalletSetup::CreatePass { + entry: PassphraseEntry::with_first(pass.as_str()), + }); + } + } + _ => {} + }, + WalletSetup::CreateSeed { typed, seed } => match key.code { + KeyCode::Char(c) if c.is_ascii_alphabetic() => { + typed.push(c); + if typed.eq_ignore_ascii_case("SEEN") { + seed.zeroize(); + self.status_note = Some("wallet created — seed shown once".into()); + return self.open_wallet(); + } + } + KeyCode::Backspace => { + typed.pop(); + } + _ => {} + }, + WalletSetup::ImportSeed { buf } => match key.code { + KeyCode::Backspace => { + buf.pop(); + } + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + buf.push(c); + } + KeyCode::Enter => { + let seed = std::mem::replace(buf, Zeroizing::new(String::new())); + if seed.trim().is_empty() { + self.alert = Some("seed required to import a wallet".into()); + self.screen = Screen::Main; + return Ok(()); + } + self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + seed, + entry: PassphraseEntry::new(), + }); + } + _ => {} + }, + WalletSetup::ImportPass { entry, seed } => match key.code { + KeyCode::Backspace => entry.backspace(), + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + entry.push(c); + } + KeyCode::Enter => { + let first = entry.take_first(); + let pass = entry.take_buf(); + if let Some(first) = first { + if first.as_str() != pass.as_str() { + entry.close(); + seed.zeroize(); + self.alert = Some("passphrases do not match".into()); + self.screen = Screen::Main; + return Ok(()); + } + let result = self + .rt + .block_on(self.node.wallet_restore(pass.as_str(), seed.as_str())); + seed.zeroize(); + match result { + Ok(()) => { + self.status_note = Some("wallet imported".into()); + return self.open_wallet(); + } + Err(e) => { + self.alert = Some(e); + self.screen = Screen::Main; + } + } + } else { + let seed = std::mem::replace(seed, Zeroizing::new(String::new())); + self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + seed, + entry: PassphraseEntry::with_first(pass.as_str()), + }); + } + } + _ => {} + }, + } + Ok(()) + } + fn submit_paste(&mut self, raw: &str) -> Result<(), String> { match qr::decode(raw.trim()) { Err(e) => { @@ -1835,6 +2022,7 @@ impl App { Screen::Wallet { receive_addr, balance, transfers, qr_modal } => { draw_wallet(f, receive_addr, balance, transfers, qr_modal.as_ref()) } + Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -2152,7 +2340,13 @@ match screen { BackupKind::Restore => "type RESTORE Esc cancel ? help", }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", - Screen::Wallet { .. } => "r toggle qr Esc back ? help", + Screen::Wallet { .. } => "c create i import r qr Esc back ? help", + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", + Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { + "Enter submit Esc cancel ? help" + } + Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", + Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -2489,7 +2683,7 @@ recent transfers lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::(), xmr)); } } - let help = "r toggle qr Esc back"; + let help = "c create i import r toggle qr Esc back"; lines.push("".into()); f.render_widget( Paragraph::new(lines.join("\n")) @@ -2502,6 +2696,49 @@ recent transfers f.render_widget(Paragraph::new(help).style(style_dim()), cols[3]); } +fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) { + let (title, body) = match setup { + WalletSetup::CreateWarn { typed } => ( + "create spend wallet", + format!( + "{}\n\nType SPEND to confirm Esc to cancel\n{typed}", + wallet::SPEND_AUTHORITY_WARNING + ), + ), + WalletSetup::CreatePass { entry } => ( + "wallet passphrase", + if entry.first().is_some() { + "re-type passphrase\n\nEnter submits Esc cancels".into() + } else { + "set a passphrase for the wallet file\n\nEnter continues Esc cancels".into() + }, + ), + WalletSetup::CreateSeed { seed, typed } => ( + "write down this seed", + format!( + "{}\n\nthis is shown once. anyone with it can spend.\nType SEEN when you have written it down\n{typed}", + seed.as_str() + ), + ), + WalletSetup::ImportSeed { buf } => ( + "import wallet", + format!( + "paste the 25-word seed. this is the only path that takes an existing key.\n\n{}\n\nEnter continues Esc cancels", + buf.as_str() + ), + ), + WalletSetup::ImportPass { entry, .. } => ( + "wallet passphrase", + if entry.first().is_some() { + "re-type passphrase\n\nEnter submits Esc cancels".into() + } else { + "passphrase for the imported wallet file\n\nEnter continues Esc cancels".into() + }, + ), + }; + draw_text_overlay(f, title, &body); +} + fn io_err(e: io::Error) -> String { e.to_string() } diff --git a/src/wallet.rs b/src/wallet.rs index cf255a0..61234cc 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -61,6 +61,12 @@ pub struct TransferRow { pub address: String, } +/// Wallet file name used for in-app create/import (`--wallet-dir` on the RPC). +pub const DEFAULT_WALLET_FILENAME: &str = "onionwire"; + +/// Shown before a spend-capable create. Not a tooltip — the user must confirm. +pub const SPEND_AUTHORITY_WARNING: &str = "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed. do not leave it on a box you do not trust."; + const RPC_TIMEOUT: Duration = Duration::from_secs(5); impl Wallet { @@ -215,6 +221,65 @@ impl Wallet { json_str(&v, "balance") } + /// Create a new spend-capable wallet on the RPC (`create_wallet`). The + /// user does not paste a key — the daemon generates the seed. Returns that + /// seed once (from `query_key mnemonic`) so the UI can show a backup + /// screen. Needs `--wallet-dir` on the RPC. + pub async fn create_wallet(&self, filename: &str, password: &str) -> Result { + let filename = filename.trim(); + if filename.is_empty() { + return Err(Error("wallet filename required".into())); + } + if password.is_empty() { + return Err(Error("wallet passphrase required".into())); + } + self.rpc( + "create_wallet", + serde_json::json!({ + "filename": filename, + "password": password, + "language": "English" + }), + ) + .await?; + let v = self + .rpc("query_key", serde_json::json!({"key_type": "mnemonic"})) + .await + .map_err(|e| { + Error(format!( + "wallet created but seed backup unavailable: {e}" + )) + })?; + json_str(&v, "key") + } + + /// Import an existing wallet from its 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { + let filename = filename.trim(); + if filename.is_empty() { + return Err(Error("wallet filename required".into())); + } + if password.is_empty() { + return Err(Error("wallet passphrase required".into())); + } + let seed = seed.trim(); + if seed.is_empty() { + return Err(Error("seed required to import a wallet".into())); + } + self.rpc( + "restore_deterministic_wallet", + serde_json::json!({ + "filename": filename, + "password": password, + "seed": seed, + "language": "English" + }), + ) + .await?; + Ok(()) + } + async fn rpc(&self, method: &str, params: serde_json::Value) -> Result { let ep = self .endpoint diff --git a/tests/pay.rs b/tests/pay.rs index c2ab11c..1dc600b 100644 --- a/tests/pay.rs +++ b/tests/pay.rs @@ -206,6 +206,9 @@ fn slash_pay_tip_and_wipe_still_parse() { assert_eq!(parse_cmd("/wipe"), Some(SlashCmd::Wipe(WipeKind::Messages))); assert_eq!(parse_slash("/wipe-all"), Some(WipeKind::All)); assert_eq!(parse_slash("/pay 0.12"), None); + assert_eq!(parse_cmd("/wallet create"), Some(SlashCmd::WalletCreate)); + assert_eq!(parse_cmd("/wallet import"), Some(SlashCmd::WalletImport)); + assert_eq!(parse_cmd("/wallet"), None); } #[test] diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index a0ada29..1eacccf 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -45,10 +45,13 @@ fn help_overlay_lists_core_bindings() { "F3", "F4", "F5", + "F6", "send chat", "/profile", "/pay", "/tip", + "/wallet create", + "/wallet import", "/file", "/backup", "/restore", diff --git a/tests/wallet.rs b/tests/wallet.rs index 1d4a451..10fb7a1 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -429,6 +429,112 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() { assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}"); } +/// Create generates a spend-capable wallet on the RPC; the user never pastes a key. +/// Seed is read back once via `query_key mnemonic` for the backup screen. +#[tokio::test] +async fn create_wallet_does_not_send_a_seed_and_returns_mnemonic() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "create_wallet" => rpc_result(r#"{}"#), + "query_key" => rpc_result(r#"{"key":"lumber tacit lemon ivory risk"}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + let seed = recording_wallet(port) + .create_wallet("onionwire", "hunter2") + .await + .expect("create_wallet"); + assert_eq!(seed, "lumber tacit lemon ivory risk"); + let seen = log.lock().expect("log").clone(); + let create = seen + .iter() + .find(|r| r.contains(r#""method":"create_wallet""#)) + .expect("create_wallet RPC"); + assert!( + !create.contains("lumber") && !create.contains("seed"), + "create must not take a seed: {create}" + ); + assert!( + create.contains(r#""filename":"onionwire""#), + "filename missing: {create}" + ); + assert!( + seen.iter().any(|r| r.contains(r#""method":"query_key""#) + && r.contains("mnemonic")), + "must read mnemonic after create: {seen:?}" + ); +} + +#[test] +fn create_wallet_empty_filename_or_password_is_local_error() { + let w = Wallet::from_url("http://ow:secret@127.0.0.1:18083").unwrap(); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let err = rt + .block_on(w.create_wallet("", "pw")) + .unwrap_err() + .to_string(); + assert!(err.contains("filename"), "got {err}"); + let err = rt + .block_on(w.create_wallet("onionwire", "")) + .unwrap_err() + .to_string(); + assert!( + err.to_ascii_lowercase().contains("password") + || err.to_ascii_lowercase().contains("passphrase"), + "got {err}" + ); +} + +/// Import is the only path that takes an existing secret (the 25-word seed). +#[tokio::test] +async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "restore_deterministic_wallet" => rpc_result(r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + recording_wallet(port) + .restore_wallet("onionwire", "hunter2", "lumber tacit lemon ivory risk") + .await + .expect("restore_wallet"); + let seen = log.lock().expect("log").clone(); + let restore = seen + .iter() + .find(|r| r.contains(r#""method":"restore_deterministic_wallet""#)) + .expect("restore RPC"); + assert!( + restore.contains("lumber tacit lemon ivory risk"), + "seed missing: {restore}" + ); +} + +#[test] +fn restore_wallet_empty_seed_is_local_error() { + let w = Wallet::from_url("http://ow:secret@127.0.0.1:18083").unwrap(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.restore_wallet("onionwire", "pw", " ")) + .unwrap_err() + .to_string(); + assert!(err.to_ascii_lowercase().contains("seed"), "got {err}"); +} + /// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused. #[tokio::test] async fn open_rpc_without_digest_challenge_is_still_refused() { From 08381c47be91f7b1b9ceea5c155c12b6e4a8839e Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 14 Sep 2026 00:26:14 -0400 Subject: [PATCH 2/8] android: keep the chat composer above the keyboard (ime insets) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit enableEdgeToEdge() sets decorFitsSystemWindows=false, so on API 30+ the framework no longer resizes the window for the soft keyboard. The manifest's android:windowSoftInputMode="adjustResize" therefore has nothing to resize and the IME arrives as an unconsumed window inset; Scaffold's contentWindowInsets covers systemBars only. Result: the composer row, its Send button and the typed body were drawn underneath the keyboard and only reachable by dismissing it. - ui/Insets.kt (new): screenContentInsets() applies systemBars ∪ ime once, at the screen's content root. union is per-side max, so the keyboard and the navigation bar are never summed; the Top side is excluded because a Scaffold's pad.top is already the app bar's measured height (the app bar carries its own status-bar inset). @Composable because WindowInsets.ime is a composable read. - ChatScreen: Scaffold(contentWindowInsets = 0) plus the root consuming the inset; the body region holds weight(1f) in every branch (loading and empty included) so the composer can never be squeezed off the bottom; Send is always drawn instead of being swapped for a spinner (no layout jump under the thumb); the field sets ImeAction.Send so the keyboard's own action key sends; focus returns to the field after a send; testTag on the composer/input/send. - InviteScreens (both screens) and RotateScreen: same inset handoff, so the Verify / Approve / confirm buttons under a text field stay reachable by scrolling. - UnlockScreen: safeDrawingPadding(). It had no system-bar insets at all (title drawn under the status bar) and its Open button sat under the keyboard while a passphrase was being typed. Verified on emulator-5554 (ow35, x86_64, API 35) with the debug build whose sources are byte-identical to this commit: element keyboard closed keyboard open composer y=2232 y=1380 Send button y=2253 y=1433 keyboard top - y≈1500 mInputShown=true while the draft text was visible; the message sent both via the Send button and via the keyboard's action key (paper-plane = ImeAction.Send), each landing with the ✓✓ delivery marker. :app:testDebugUnitTest green. Note: no CI job covers this — ci.yml's path allowlist is src/**, crates/**, tests/**, Cargo.*, so an android-only change runs nothing, and android-release.yml only fires on v*.*.* tags. --- .../siriusdevops/onionwire/ui/ChatScreen.kt | 99 +++++++++++++++---- .../com/siriusdevops/onionwire/ui/Insets.kt | 45 +++++++++ .../onionwire/ui/InviteScreens.kt | 22 ++++- .../siriusdevops/onionwire/ui/RotateScreen.kt | 11 ++- .../siriusdevops/onionwire/ui/UnlockScreen.kt | 5 + 5 files changed, 161 insertions(+), 21 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt 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 b45038c..42ba37c 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 @@ -2,10 +2,12 @@ package com.siriusdevops.onionwire.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -15,11 +17,16 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold @@ -34,10 +41,14 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay import uniffi.onionwire_sdk.ChatMessage @@ -73,6 +84,18 @@ fun ChatScreen( var notice by remember { mutableStateOf(null) } val listState = rememberLazyListState() + // The composer is the only place a message can be sent from, so after a + // send the keyboard is left up and the caret goes back into the field — + // the next message is one keystroke away instead of a re-tap. + val inputFocus = remember { FocusRequester() } + val send: () -> Unit = { + if (draft.isNotBlank() && pending == null) { + pending = draft + draft = "" + inputFocus.requestFocus() + } + } + // Poll: the node appends inbound messages in the background and the retry // worker moves queued rows along; there is no push channel into the UI in // v1, so the delivery markers refresh on the same cadence as the bodies. @@ -139,8 +162,17 @@ fun ChatScreen( ), ) }, + // The top bar carries its own status-bar inset; the content root applies + // systemBars + IME once (see `screenContentInsets`) so the navigation + // bar is not counted twice while the keyboard is up. + contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { pad -> - Column(Modifier.padding(pad).fillMaxSize()) { + Column( + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets(), + ) { Text( "onion: $onion", style = MaterialTheme.typography.labelSmall, @@ -152,14 +184,21 @@ fun ChatScreen( val list = messages when { list == null -> { - Spacer(Modifier.height(16.dp)) - CircularProgressIndicator(Modifier.padding(16.dp)) + // The body region always claims the leftover height, so the + // composer below it can never be pushed off the bottom — + // least of all by the keyboard. + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { + CircularProgressIndicator(Modifier.padding(16.dp)) + } } list.isEmpty() -> { Column( - Modifier.fillMaxWidth().padding(24.dp), - verticalArrangement = Arrangement.Center, + Modifier + .weight(1f) + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(24.dp), ) { Text("No messages", style = MaterialTheme.typography.titleSmall) Spacer(Modifier.height(6.dp)) @@ -274,28 +313,52 @@ fun ChatScreen( ) } + // The composer sticks to the bottom of the window: `screenContentInsets` + // already lifted it above the keyboard, and its row is never allowed + // to be squeezed out by the messages above it (they hold the weight). Row( - Modifier.fillMaxWidth().padding(8.dp), - verticalAlignment = Alignment.CenterVertically, + Modifier + .fillMaxWidth() + .padding(8.dp) + .testTag("chat-composer"), + verticalAlignment = Alignment.Bottom, ) { OutlinedTextField( value = draft, onValueChange = { draft = it }, - modifier = Modifier.weight(1f), + modifier = Modifier + .weight(1f) + .focusRequester(inputFocus) + .testTag("chat-input"), maxLines = 4, label = { Text("message") }, + // The IME gets its own send affordance: on a phone in + // landscape, or with the keyboard covering the button, the + // action key is the shortest path to sending. + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.Sentences, + imeAction = ImeAction.Send, + ), + keyboardActions = KeyboardActions(onSend = { send() }), ) Spacer(Modifier.width(8.dp)) - if (pending != null) { - CircularProgressIndicator() - } else { - Button( - enabled = draft.isNotBlank(), - onClick = { - pending = draft - draft = "" - }, - ) { Text("Send") } + // Always drawn, never swapped out for a spinner: a button that + // changes size under the thumb — or disappears — is how "I hit + // send and nothing happened" gets reported. + Button( + enabled = draft.isNotBlank() && pending == null, + onClick = send, + modifier = Modifier.testTag("chat-send"), + ) { + if (pending != null) { + CircularProgressIndicator( + modifier = Modifier.size(14.dp), + strokeWidth = 2.dp, + color = LocalContentColor.current, + ) + Spacer(Modifier.width(6.dp)) + } + Text("Send") } } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt new file mode 100644 index 0000000..fd7802d --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt @@ -0,0 +1,45 @@ +package com.siriusdevops.onionwire.ui + +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier + +/** + * The bottom + horizontal window insets one screen's content root must apply + * itself. + * + * `MainActivity` calls `enableEdgeToEdge()`, which means + * `setDecorFitsSystemWindows(window, false)`. On API 30+ that stops the + * framework from resizing the window for the soft keyboard: the manifest's + * `android:windowSoftInputMode="adjustResize"` has nothing left to resize, and + * the IME arrives as a *window inset* instead. `Scaffold`'s + * `contentWindowInsets` only covers `systemBars`, so anything anchored to the + * bottom of the window — the chat composer, a submit button under a text field + * — ends up drawn behind the keyboard, reachable only by dismissing it. + * + * The IME's bottom inset already covers the navigation bar, so the two are + * unioned (per-side `max`), never summed: keyboard height while typing, + * navigation-bar height otherwise, and no double padding in between. + * + * The `Top` side is deliberately excluded — a `Scaffold`'s `pad.top` is the app + * bar's own measured height, and the app bar carries its own status-bar inset + * (`TopAppBarDefaults.windowInsets`). + * + * Pair every use with `Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0))` + * so the same inset is not applied twice. + * + * `@Composable` because `WindowInsets.systemBars` / `WindowInsets.ime` are + * composable reads — call it from a composable (every call site is one). + */ +@Composable +fun Modifier.screenContentInsets(): Modifier = + windowInsetsPadding( + WindowInsets.systemBars.union(WindowInsets.ime) + .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom), + ) \ No newline at end of file diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt index 31da473..b084b27 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt @@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -62,9 +63,17 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { ), ) }, + // The root applies systemBars + IME itself (see `screenContentInsets`), + // so Scaffold must not also pad for the navigation bar. + contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { pad -> Column( - Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()) + .padding(16.dp), ) { Text( "Hand this to one person, over a channel you already trust. " + @@ -149,9 +158,18 @@ fun PasteInviteScreen( ), ) }, + // Same inset handoff as the chat composer: with the keyboard up, the + // Verify / Approve buttons under the invite field must still be + // reachable by scrolling, not by dismissing the keyboard. + contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { pad -> Column( - Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()) + .padding(16.dp), ) { OutlinedTextField( value = raw, diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt index e8b4cc1..b1f99b5 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/RotateScreen.kt @@ -4,6 +4,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -59,9 +60,17 @@ fun RotateScreen( ), ) }, + // Root owns systemBars + IME (see `screenContentInsets`) so the confirm + // button under the passphrase field stays reachable with the keyboard up. + contentWindowInsets = WindowInsets(0, 0, 0, 0), ) { pad -> Column( - Modifier.padding(pad).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()) + .padding(16.dp), ) { Text("Rotate onion address?", style = MaterialTheme.typography.titleLarge) Spacer(Modifier.height(12.dp)) 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 7adb6f8..4e57d5e 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 @@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll @@ -68,6 +69,10 @@ fun UnlockScreen( Column( modifier = Modifier .fillMaxSize() + // This screen has no Scaffold, so its root owns every window inset: + // without this the keyboard covers the passphrase field's Open + // button and the status bar overlaps the title. + .safeDrawingPadding() .verticalScroll(rememberScrollState()) .padding(24.dp), verticalArrangement = Arrangement.Center, From 9c36814eb36507680aa58fb52b8d6eb0c3964c05 Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 14 Sep 2026 00:45:32 -0400 Subject: [PATCH 3/8] android: copy the invite with LocalClipboard, not the deprecated LocalClipboardManager LocalClipboardManager is deprecated in compose ui 1.10; the warning was the only one in :app:compileDebugKotlin. Switch ShareInviteScreen to LocalClipboard.setClipEntry(ClipEntry(ClipData.newPlainText(...))) on a rememberCoroutineScope, since the new API is suspend. Same text, same copied-state flip, same label, no permission change. --- .../siriusdevops/onionwire/ui/InviteScreens.kt | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt index b084b27..4d67f52 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/InviteScreens.kt @@ -1,5 +1,6 @@ package com.siriusdevops.onionwire.ui +import android.content.ClipData import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -32,8 +33,8 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalClipboardManager -import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import uniffi.onionwire_sdk.FriendInfo @@ -45,7 +46,8 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { var invite by remember { mutableStateOf(null) } var error by remember { mutableStateOf(null) } var copied by remember { mutableStateOf(false) } - val clip = LocalClipboardManager.current + val clipboard = LocalClipboard.current + val scope = rememberCoroutineScope() LaunchedEffect(Unit) { runCatching { ownerInvite() } @@ -107,8 +109,12 @@ fun ShareInviteScreen(ownerInvite: suspend () -> String, onBack: () -> Unit) { Spacer(Modifier.height(12.dp)) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Button(onClick = { - clip.setText(AnnotatedString(invite!!)) - copied = true + scope.launch { + clipboard.setClipEntry( + ClipEntry(ClipData.newPlainText("onionwire invite", invite!!)), + ) + copied = true + } }) { Text(if (copied) "Copied" else "Copy") } } Spacer(Modifier.height(20.dp)) From 535a2baff95aaa1fa4581e9fed016c042a96da4a Mon Sep 17 00:00:00 2001 From: apk-dev Date: Mon, 14 Sep 2026 02:05:03 -0400 Subject: [PATCH 4/8] android: wallet + roster bottom actions clipped while the keyboard is up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two screens whose action row lives inside a non-scrollable Column could not be un-covered by insets alone: the container had no scroll range at all. - WalletScreen: root Column is now a verticalScroll viewport that consumes systemBars ∪ ime itself (screenContentInsets()) before the scroll, paired with Scaffold(contentWindowInsets = 0). The nested LazyColumn becomes a plain Column (a lazy list cannot be measured inside a scroll container with unbounded height) and the weight(1f) bottom spacer goes with it: a weighted spacer cannot live in a scrollable Column. - RosterScreen: same inset treatment; the friends LazyColumn drops fillMaxSize() for weight(1f) so the wipe-confirm strip above it keeps its height when the IME shrinks the window. - Insets.kt is PR #67's helper, taken verbatim (this branch does not carry #67). Stacked on PR #67 (wt/chat-ime-insets, 08381c4) for ui/Insets.kt. --- .../com/siriusdevops/onionwire/ui/Insets.kt | 45 +++++++++++++++++++ .../siriusdevops/onionwire/ui/RosterScreen.kt | 14 +++++- .../siriusdevops/onionwire/ui/WalletScreen.kt | 31 ++++++++----- 3 files changed, 78 insertions(+), 12 deletions(-) create mode 100644 android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt new file mode 100644 index 0000000..fd7802d --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/Insets.kt @@ -0,0 +1,45 @@ +package com.siriusdevops.onionwire.ui + +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier + +/** + * The bottom + horizontal window insets one screen's content root must apply + * itself. + * + * `MainActivity` calls `enableEdgeToEdge()`, which means + * `setDecorFitsSystemWindows(window, false)`. On API 30+ that stops the + * framework from resizing the window for the soft keyboard: the manifest's + * `android:windowSoftInputMode="adjustResize"` has nothing left to resize, and + * the IME arrives as a *window inset* instead. `Scaffold`'s + * `contentWindowInsets` only covers `systemBars`, so anything anchored to the + * bottom of the window — the chat composer, a submit button under a text field + * — ends up drawn behind the keyboard, reachable only by dismissing it. + * + * The IME's bottom inset already covers the navigation bar, so the two are + * unioned (per-side `max`), never summed: keyboard height while typing, + * navigation-bar height otherwise, and no double padding in between. + * + * The `Top` side is deliberately excluded — a `Scaffold`'s `pad.top` is the app + * bar's own measured height, and the app bar carries its own status-bar inset + * (`TopAppBarDefaults.windowInsets`). + * + * Pair every use with `Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0))` + * so the same inset is not applied twice. + * + * `@Composable` because `WindowInsets.systemBars` / `WindowInsets.ime` are + * composable reads — call it from a composable (every call site is one). + */ +@Composable +fun Modifier.screenContentInsets(): Modifier = + windowInsetsPadding( + WindowInsets.systemBars.union(WindowInsets.ime) + .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom), + ) \ No newline at end of file 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 18b8750..ed641dc 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 @@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -52,6 +53,11 @@ fun RosterScreen( var confirmWipe by remember { mutableStateOf(false) } Scaffold( + // The content root below consumes systemBars ∪ ime itself (see + // `screenContentInsets`); zeroing the Scaffold's own insets keeps the + // navigation bar from being applied twice and lets the wipe-confirm + // strip sit above the keyboard instead of under it. + contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = { TopAppBar( title = { Text("OnionWire") }, @@ -64,7 +70,7 @@ fun RosterScreen( ) }, ) { pad -> - Column(Modifier.padding(pad).fillMaxSize()) { + Column(Modifier.padding(pad).fillMaxSize().screenContentInsets()) { Card( modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp), @@ -134,7 +140,11 @@ fun RosterScreen( ) } } else { - LazyColumn(Modifier.fillMaxSize()) { + // weight(1f), not fillMaxSize(): the list must yield height to + // its siblings (the action row and the wipe-confirm strip above + // it) when the IME shrinks the window, instead of claiming all + // of it and pushing them off the bottom. + LazyColumn(Modifier.weight(1f).fillMaxWidth()) { items(friends, key = { it.pubkeyHex }) { f -> FriendRow(f) { onOpenChat(f) } HorizontalDivider() diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index 0e5d8e8..bc09ec7 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -9,14 +9,15 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults @@ -82,6 +83,11 @@ fun WalletScreen( LaunchedEffect(Unit) { reload() } Scaffold( + // The content root below consumes systemBars ∪ ime itself (see + // `screenContentInsets`); zeroing the Scaffold's own insets keeps the + // navigation bar from being applied twice, and keeps the IME inset out + // of the Scaffold's inner padding. + contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = { TopAppBar( title = { Text("Wallet") }, @@ -95,7 +101,13 @@ fun WalletScreen( }, ) { pad -> Column( - Modifier.padding(pad).fillMaxSize(), + Modifier + .padding(pad) + .fillMaxSize() + // systemBars ∪ ime, applied outside the scrolling viewport so + // the inset does not scroll away with the content. + .screenContentInsets() + .verticalScroll(rememberScrollState()), ) { Card( modifier = Modifier @@ -171,19 +183,18 @@ fun WalletScreen( style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), ) - LazyColumn( + // Plain Column, not a LazyColumn: the root is a scrolling + // container now, so a nested lazy list would either throw on the + // unbounded height or need an arbitrary cap. `walletRecentTransfers` + // is bounded (25 rows), and the page scrolls as one gesture. + Column( modifier = Modifier .fillMaxWidth() - .weight(1f, fill = false) .padding(horizontal = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - items(transfers, key = { it.txid }) { t -> - TransferCard(t) - } + transfers.forEach { t -> TransferCard(t) } } - } else { - Spacer(Modifier.weight(1f)) } val kind = composer From 04c993862cd99800ae0cdaf3c14acbc7834bedda Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 14 Sep 2026 02:53:54 -0400 Subject: [PATCH 5/8] android: one chat poller owned by the ViewModel, gated auto-scroll, Enter-to-send MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The chat screen owned a LaunchedEffect(Unit) that fetched maxAttempts once and then called loadMessages/loadOutbox every 2s forever, fed by three suspend lambdas from MainActivity — one SDK poller per composition. The cadence now lives in WireViewModel: openChat(peer) starts one 2s loop in viewModelScope (closeChat stops it, re-entering the same peer is a no-op), exposed as ChatState(messages, outbox, maxAttempts, error) and collected with collectAsStateWithLifecycle. Same 2s cadence, maxAttempts read once, messages and outbox refreshed together, load failures sticky on ChatState.error, and the QUEUED notice unchanged; a send clears the load error. Auto-scroll no longer steals the reader's place: the tail is followed only when the last visible index is >= count - 2 (or the list has not filled yet), while the user's own send still scrolls their message into view. The first fill keeps its one jump to the bottom. A delivery-only change (same size) still does not re-run the effect — documented in a comment rather than changed. The composer keeps ImeAction.Send with maxLines = 4, documented as a deliberate wrap limit rather than a newline affordance: the action key sends (hardware Enter still inserts a newline inside the field). No polling LaunchedEffect remains in ChatScreen.kt. --- .../siriusdevops/onionwire/MainActivity.kt | 6 +- .../siriusdevops/onionwire/WireViewModel.kt | 122 ++++++++++++++++++ .../siriusdevops/onionwire/ui/ChatScreen.kt | 111 ++++++++++------ 3 files changed, 198 insertions(+), 41 deletions(-) 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 6038c5c..1d14fa6 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -143,15 +143,13 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str val pk = entry.arguments?.getString("pk").orEmpty() val friend = friends.firstOrNull { it.pubkeyHex == pk } ChatScreen( + vm = vm, + peer = pk, title = friend?.petname?.takeIf { it.isNotBlank() } ?: friend?.fingerprint ?: pk.take(16), fingerprint = friend?.fingerprint ?: pk.take(16), onion = friend?.onion.orEmpty(), - loadMessages = { vm.messages(pk) }, - loadOutbox = { vm.outbox(pk) }, - loadMaxAttempts = { vm.outboxMaxAttempts() }, - onSend = { body -> vm.send(pk, body) }, onBack = { nav.popBackStack() }, ) } 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 dfe66e0..f22fb12 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -12,9 +12,14 @@ 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.currentCoroutineContext +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import uniffi.onionwire_sdk.ChatMessage @@ -61,6 +66,22 @@ sealed interface Unlock { data class OneTap(val backing: KeyBacking) : Unlock } +/** + * Everything one open chat screen renders, refreshed on a single cadence. + * + * [messages] is null until the first read lands — the screen shows its spinner + * on that, exactly as it did reading the SDK itself. [error] is the last load + * failure and is sticky on purpose: it survives the ticks that succeed, so a + * transient store error is still on screen after the next 2s tick rather than + * blinking away. A send clears it (the user has acted on it). + */ +data class ChatState( + val messages: List? = null, + val outbox: List = emptyList(), + val maxAttempts: UInt? = null, + val error: String? = null, +) + /** * Owns the UI side of the process's single node. * @@ -101,6 +122,22 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { private val _keepAliveNote = MutableStateFlow(null) val keepAliveNote: StateFlow = _keepAliveNote.asStateFlow() + /** + * The currently open chat, or null when no chat screen is composed. + * + * There is exactly one node and one chat on screen at a time, so this is + * one state object rather than a map keyed by peer: a second poller for a + * second peer would double the SDK traffic for a screen nobody is looking + * at, and the node's store reads are not free. + */ + private val _chat = MutableStateFlow(null) + val chat: StateFlow = _chat.asStateFlow() + + /** The peer [chat] belongs to; guards a stale tick from a previous peer. */ + private var chatPeer: String? = null + + private var chatPoller: Job? = null + init { // 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 @@ -177,6 +214,10 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { */ fun lock() { if (NodeHost.current() == null) return + // Stop the chat tick before the node goes: the next read of a closed + // store would surface as a chat load error on a screen the user has + // already left, and every tick would keep re-reporting it. + stopChatPoller() KeepAliveService.stop(getApplication()) NodeHost.lock() _friends.value = emptyList() @@ -381,6 +422,87 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { */ suspend fun outboxMaxAttempts(): UInt = uniffi.onionwire_sdk.outboxMaxAttempts() + /** + * Starts the one 2s refresh loop for [pubkeyHex] and resets the chat state. + * + * Called from the chat screen entering the composition. Re-entering the + * same peer while its poller is alive is a no-op — navigating to the chat + * and back must never stack a second loop on top of the first. + */ + fun openChat(pubkeyHex: String) { + if (chatPeer == pubkeyHex && chatPoller?.isActive == true) return + chatPoller?.cancel() + chatPeer = pubkeyHex + _chat.value = ChatState() + chatPoller = viewModelScope.launch { pollChat(pubkeyHex) } + } + + /** + * Stops the loop when the chat screen leaves. Ignored when another peer has + * taken over in the meantime (navigating chat A → chat B disposes A after B + * has already opened). + */ + fun closeChat(pubkeyHex: String) { + if (chatPeer != pubkeyHex) return + stopChatPoller() + } + + private fun stopChatPoller() { + chatPoller?.cancel() + chatPoller = null + chatPeer = null + _chat.value = null + } + + /** + * Drops the last load error. The send path calls this: the user has acted, + * so a stale "could not read" line must not sit under the composer while + * the send is in flight. + */ + fun clearChatError() { + _chat.update { it?.copy(error = null) } + } + + /** + * The cadence, in the ViewModel: inbound messages are appended by the node + * in the background and the retry worker moves queued rows along, and in v1 + * there is no push channel into the UI, so messages and outbox are read + * together on one 2s tick. The outbox rows are read on that tick too — + * their `next_attempt_at` is a fixed instant, so a row saying "retry 45s" + * turns into "retry now" here without the store having to change. + * + * The retry budget is read once per open chat (it is a constant of the + * outbox, not per-peer state); a failure leaves it null and the rows fall + * back to the flat marker. + */ + private suspend fun pollChat(pk: String) { + runCatching { outboxMaxAttempts() }.onSuccess { budget -> + if (chatPeer == pk) _chat.update { it?.copy(maxAttempts = budget) } + } + while (currentCoroutineContext().isActive) { + val loaded = runCatching { messages(pk) } + val out = runCatching { outbox(pk) } + // A cancelled loop can still be sitting in a completed SDK read: + // writing that peer's rows into a state that now belongs to another + // peer would show the wrong conversation. + if (chatPeer != pk) return + _chat.update { state -> + val base = state ?: ChatState() + base.copy( + messages = loaded.getOrNull() ?: base.messages, + outbox = out.getOrNull() ?: base.outbox, + // Same order the screen's own loop reported them in, and + // sticky on success — a new failure replaces the last one, + // a successful tick does not clear the last one. + error = out.exceptionOrNull()?.let { it.message ?: it.toString() } + ?: loaded.exceptionOrNull()?.let { it.message ?: it.toString() } + ?: base.error, + ) + } + delay(2_000) + } + } + /** * Sends one chat message and reports what the core did with it. * 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 42ba37c..499b6f8 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 @@ -34,6 +34,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -50,21 +51,19 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp -import kotlinx.coroutines.delay -import uniffi.onionwire_sdk.ChatMessage -import uniffi.onionwire_sdk.OutboxRow +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.siriusdevops.onionwire.WireViewModel import uniffi.onionwire_sdk.SendState @OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatScreen( + vm: WireViewModel, + /** The peer's ed25519 pubkey hex — the key the open chat's poller runs for. */ + peer: String, title: String, fingerprint: String, onion: String, - loadMessages: suspend () -> List, - loadOutbox: suspend () -> List, - loadMaxAttempts: suspend () -> UInt, - onSend: suspend (String) -> SendState, onBack: () -> Unit, /** * Wall clock in unix seconds. `next_attempt_at` is absolute, so the @@ -73,17 +72,32 @@ fun ChatScreen( */ nowSeconds: () -> Long = { System.currentTimeMillis() / 1_000L }, ) { - var messages by remember { mutableStateOf?>(null) } - var outbox by remember { mutableStateOf>(emptyList()) } - // The core's retry budget, fetched once: `try 3/8` renders against this and - // never against a constant in the app. - var maxAttempts by remember { mutableStateOf(null) } + // The refresh cadence lives in the ViewModel: one poller per open chat, not + // one per composition. Collecting here means a re-composition (or a + // configuration change) does not start a second loop against the SDK. + val chat by vm.chat.collectAsStateWithLifecycle() + val messages = chat?.messages + val outbox = chat?.outbox.orEmpty() + // The core's retry budget, fetched once per open chat: `try 3/8` renders + // against this and never against a constant in the app. + val maxAttempts = chat?.maxAttempts + var draft by remember { mutableStateOf("") } var pending by remember { mutableStateOf(null) } - var error by remember { mutableStateOf(null) } + // Send-path failures are the screen's own state; load failures come back on + // [ChatState.error]. Both render in the same place under the list. + var sendError by remember { mutableStateOf(null) } var notice by remember { mutableStateOf(null) } + val error = sendError ?: chat?.error val listState = rememberLazyListState() + // Auto-scroll bookkeeping. `firstFillDone` keeps the one-jump-to-the-bottom + // on the first load (and again after leaving and re-entering the chat); + // `ownSendPending` is the user's own message asking for the list to follow + // even though they may have scrolled up in history. + var firstFillDone by remember { mutableStateOf(false) } + var ownSendPending by remember { mutableStateOf(false) } + // The composer is the only place a message can be sent from, so after a // send the keyboard is left up and the caret goes back into the field — // the next message is one keystroke away instead of a re-tap. @@ -92,27 +106,19 @@ fun ChatScreen( if (draft.isNotBlank() && pending == null) { pending = draft draft = "" + // The user's own message is the one case where the list is allowed + // to move while they are scrolled up in history. + ownSendPending = true inputFocus.requestFocus() } } - // Poll: the node appends inbound messages in the background and the retry - // worker moves queued rows along; there is no push channel into the UI in - // v1, so the delivery markers refresh on the same cadence as the bodies. - // The outbox rows are read on that cadence too — their `next_attempt_at` is - // a fixed instant, so a row saying "retry 45s" turns into "retry now" here - // without the store having to change. - LaunchedEffect(Unit) { - runCatching { loadMaxAttempts() }.onSuccess { maxAttempts = it } - while (true) { - runCatching { loadMessages() } - .onSuccess { messages = it } - .onFailure { error = it.message ?: it.toString() } - runCatching { loadOutbox() } - .onSuccess { outbox = it } - .onFailure { error = it.message ?: it.toString() } - delay(2_000) - } + // The poller's lifetime is the chat screen's: entering starts it, leaving + // stops it, and re-entering the same peer is a no-op in the ViewModel, so + // there is exactly one loop no matter how the nav stack is walked. + DisposableEffect(peer) { + vm.openChat(peer) + onDispose { vm.closeChat(peer) } } // Send. An unreachable peer's onion is not an error any more: the core @@ -122,22 +128,45 @@ fun ChatScreen( // queued for those. LaunchedEffect(pending) { val body = pending ?: return@LaunchedEffect - error = null + sendError = null notice = null - runCatching { onSend(body) } + // The user has acted on whatever the poller last reported. + vm.clearChatError() + runCatching { vm.send(peer, body) } .onSuccess { if (it == SendState.QUEUED) { notice = "Queued: their onion is unreachable. The message stays on " + "this device and is retried until it lands." } } - .onFailure { error = it.message ?: it.toString() } + .onFailure { sendError = it.message ?: it.toString() } pending = null } + // Known and accepted: this is keyed on the message count, so a delivery-only + // change (a row flipping `queued` → `sent`, same size, different marker) + // does not re-run it. That has always been the behaviour here and it is the + // safe one — the list never moves for a marker. LaunchedEffect(messages?.size) { val n = messages?.size ?: 0 - if (n > 0) listState.animateScrollToItem(n - 1) + if (n == 0) return@LaunchedEffect + if (!firstFillDone) { + // First load: one jump to the bottom so the newest message is the + // one on screen, without an animation nobody asked for. + listState.scrollToItem(n - 1) + firstFillDone = true + return@LaunchedEffect + } + // Follow the tail only when the reader is already there. `n - 2` + // rather than `!canScrollForward`: the append has already made the list + // scrollable by the time this runs, so "can I scroll further" is true + // even for someone who was glued to the bottom a frame ago — and + // `lastVisible >= n - 2` tolerates the last row being partly on screen. + val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1 + if (ownSendPending || lastVisible >= n - 2) { + listState.animateScrollToItem(n - 1) + } + ownSendPending = false } Scaffold( @@ -332,9 +361,17 @@ fun ChatScreen( .testTag("chat-input"), maxLines = 4, label = { Text("message") }, - // The IME gets its own send affordance: on a phone in - // landscape, or with the keyboard covering the button, the - // action key is the shortest path to sending. + // DECISION (item 3 of the follow-up card): the IME's action + // key sends; the soft keyboard cannot insert a manual + // newline. `ImeAction.Send` and `maxLines = 4` are not in + // conflict — `maxLines` is a wrap limit (a long message + // grows to four lines, then scrolls inside the field), not + // a newline affordance. Chat convention wins: Enter-to-send + // is what a messenger's users reach for, and the Send button + // is on the same row. Nothing is unreachable either — a + // hardware keyboard's Enter never goes through the IME + // action, so Shift+Enter still inserts a real newline in + // the field. keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.Sentences, imeAction = ImeAction.Send, From ef1248e7309cbfe32d6653c7eeb5473e6556aca5 Mon Sep 17 00:00:00 2001 From: sirius Date: Mon, 14 Sep 2026 12:16:40 -0400 Subject: [PATCH 6/8] ci(android): build the APK+AAR on android/, src/ and crates/ changes An android-only PR ran zero jobs: ci.yml's path allowlist never matches android/**, and android-release.yml is dispatch-driven. #70 merged on an empty check list. android-ci.yml runs the release's gradle targets through the release's own script (scripts/build-android-local.sh) on the amd64 runner, debug-signed, publishing nothing. Same concurrency group and runner volumes as android-release.yml so the build is warm and cannot collide with a release. --- .forgejo/workflows/android-ci.yml | 236 ++++++++++++++++++++++++++++++ README.md | 1 + docs/RELEASING.md | 12 ++ 3 files changed, 249 insertions(+) create mode 100644 .forgejo/workflows/android-ci.yml diff --git a/.forgejo/workflows/android-ci.yml b/.forgejo/workflows/android-ci.yml new file mode 100644 index 0000000..9417544 --- /dev/null +++ b/.forgejo/workflows/android-ci.yml @@ -0,0 +1,236 @@ +name: android-ci + +# Android changes had no CI at all: ci.yml's path allowlist (src/**, crates/**, +# tests/**, Cargo.toml, Cargo.lock, ci.yml) never matches android/**, and +# android-release.yml is dispatch/tag-driven — so an android-only PR ran zero +# jobs and merged on an empty check list. This is the android side of CI. +# +# It builds the same gradle targets the release builds through the same script +# android-release.yml calls (scripts/build-android-local.sh): `:sdk:assembleRelease` +# + `:app:assembleRelease`, Rust for aarch64-linux-android via cargo-ndk, UniFFI +# bindings, APK packaging with the .so. The only difference from a release is +# signing: ONIONWIRE_REQUIRE_RELEASE_KEY=false and no release keystore, so +# Gradle falls back to the debug key. Nothing here is signed for release, +# nothing is published, no tag is touched. +# +# Why a separate workflow instead of android/** added to ci.yml: the only way +# to keep the Rust jobs from running on android-only diffs is job-level change +# detection, and a gate that mis-detects hands out a green check for a suite +# that never ran. Here the runner's own paths filter decides — same mechanism +# ci.yml already uses. +on: + push: + branches: [main] + paths: + - "android/**" + - "crates/**" + - "src/**" + - "Cargo.toml" + - "Cargo.lock" + - "scripts/build-android-local.sh" + - ".forgejo/workflows/android-ci.yml" + pull_request: + paths: + - "android/**" + - "crates/**" + - "src/**" + - "Cargo.toml" + - "Cargo.lock" + - "scripts/build-android-local.sh" + - ".forgejo/workflows/android-ci.yml" + workflow_dispatch: + +# Deliberately the SAME group and the SAME volumes as android-release.yml: the +# APK build is ~9 min with warm volumes (SDK/NDK, cargo registry, cargo target, +# Gradle cache) and a cold copy of those is over a gigabyte of downloads per +# runner. Serializing the two workflows by group name is what keeps them off +# each other's volumes. +concurrency: + group: onionwire-android-release-v2 + cancel-in-progress: false + +env: + CARGO_TERM_COLOR: never + CARGO_BUILD_JOBS: "1" + ONIONWIRE_ANDROID_ABI: arm64-v8a + ANDROID_IMAGE: debian:bookworm + ANDROID_CMDLINE_TOOLS_URL: https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip + RUST_TOOLCHAIN: "1.91" + DOCKER_STATIC_URL: https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz + # Distinct container prefix: run ids are per-workflow, so this workflow and + # android-release.yml can both be holding a container named "-". + BUILD_CONTAINER: onionwire-android-ci-${{ github.run_id }} + SDK_VOLUME: onionwire-android-sdk + CARGO_VOLUME: onionwire-android-cargo-registry + TARGET_VOLUME: onionwire-android-target + GRADLE_VOLUME: onionwire-android-gradle + +jobs: + android: + runs-on: docker-amd64 + timeout-minutes: 120 + steps: + - name: Checkout + uses: https://code.forgejo.org/actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Record runner resources + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + echo "workspace=$GITHUB_WORKSPACE hostname=$(hostname) arch=$(uname -m)" + nproc || true + free -h || true + df -h || true + ls -l /var/run/docker.sock || true + + - name: Ensure docker CLI + run: | + set -euo pipefail + if ! command -v docker >/dev/null 2>&1; then + echo "docker CLI missing in job image; fetching static client" + curl -fsSL "$DOCKER_STATIC_URL" -o /tmp/docker.tgz + tar -xzf /tmp/docker.tgz -C /tmp + install -m 755 /tmp/docker/docker /usr/local/bin/docker + fi + export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}" + docker version + docker info >/tmp/docker-info.txt + grep -E 'Server Version|Operating System|Total Memory|Name' /tmp/docker-info.txt || true + + - name: Build APK + AAR (debug-signed) in bookworm container + id: build + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}" + start=$(date +%s) + cat > .ci-android-verify.sh <<'INNER' + #!/usr/bin/env bash + set -euo pipefail + export DEBIAN_FRONTEND=noninteractive + apt-get update + apt-get install -y --no-install-recommends \ + openjdk-17-jdk-headless python3 unzip curl ca-certificates file build-essential pkg-config git + if [ ! -x /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager ]; then + mkdir -p /opt/android-sdk/cmdline-tools + curl -fsSL "$ANDROID_CMDLINE_TOOLS_URL" -o /tmp/cmdline-tools.zip + rm -rf /tmp/cmdline-tools + unzip -q /tmp/cmdline-tools.zip -d /tmp/cmdline-tools + mkdir -p /opt/android-sdk/cmdline-tools/latest + cp -a /tmp/cmdline-tools/cmdline-tools/. /opt/android-sdk/cmdline-tools/latest/ + fi + yes | /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk --licenses >/tmp/sdk-licenses.log || true + /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk \ + "platform-tools" "platforms;android-36" "build-tools;36.0.0" "ndk;28.2.13676358" + test -d /opt/android-sdk/ndk/28.2.13676358 + export ANDROID_HOME=/opt/android-sdk ANDROID_SDK_ROOT=/opt/android-sdk + export ANDROID_NDK_HOME=/opt/android-sdk/ndk/28.2.13676358 + export PATH="$ANDROID_HOME/build-tools/36.0.0:$ANDROID_HOME/platform-tools:$PATH" + if [ ! -x /cargo/bin/rustup ]; then + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain "$RUST_TOOLCHAIN" --no-modify-path --profile minimal + fi + export PATH="/cargo/bin:$PATH" + rustup toolchain install "$RUST_TOOLCHAIN" + rustup default "$RUST_TOOLCHAIN" + rustup target add aarch64-linux-android + command -v cargo-ndk >/dev/null || cargo install cargo-ndk --locked + echo "=== toolchain ===" + java -version + rustc --version + cargo ndk --version + du -sh /opt/android-sdk /cargo /cargo-target /gradle || true + # No keystore here on purpose: this is a verification build, not a + # release build. The script warns that Gradle fell back to the debug + # key; that warning is expected in this job. + scripts/build-android-local.sh + version="$(python3 - <<'PY' + import re, pathlib + t = pathlib.Path('android/app/build.gradle.kts').read_text() + m = re.search(r'versionName\s*=.*?:\s*"([^"]+)"', t) + print(m.group(1) if m else '') + PY + )" + abi="${ONIONWIRE_ANDROID_ABI:-arm64-v8a}" + apk="dist/onionwire-$version-android-$abi.apk" + aar="dist/onionwire-sdk-$version.aar" + { + echo "=== file ===" + file "$apk" "$aar" + echo "=== unzip lib ===" + unzip -l "$apk" | grep -E 'lib/.+\.so' || true + unzip -l "$apk" | grep "lib/$abi/libonionwire_sdk.so" + echo "=== classes.dex + Compose entrypoints ===" + unzip -l "$apk" | grep -E 'classes[0-9]*\.dex' | head -n3 + echo "=== sha256 ===" + ( cd dist && sha256sum -c "onionwire-$version-android-$abi.apk.sha256" "onionwire-sdk-$version.aar.sha256" ) + echo "=== apksigner (expect debug cert: this is a verification build) ===" + apksigner verify --print-certs "$apk" | sed -n '1,6p' + echo "=== aapt ===" + aapt dump badging "$apk" | sed -n '1,20p' || true + echo "=== sizes ===" + wc -c "$apk" "$aar" + } | tee dist/android-ci-verify.log + INNER + chmod +x .ci-android-verify.sh + docker volume create "$SDK_VOLUME" >/dev/null + docker volume create "$CARGO_VOLUME" >/dev/null + docker volume create "$TARGET_VOLUME" >/dev/null + docker volume create "$GRADLE_VOLUME" >/dev/null + docker rm -f "$BUILD_CONTAINER" >/dev/null 2>&1 || true + docker pull "$ANDROID_IMAGE" + docker create --name "$BUILD_CONTAINER" -i \ + -e CARGO_TERM_COLOR=never \ + -e CARGO_BUILD_JOBS="$CARGO_BUILD_JOBS" \ + -e CARGO_HOME=/cargo \ + -e CARGO_TARGET_DIR=/cargo-target \ + -e GRADLE_USER_HOME=/gradle \ + -e ANDROID_HOME=/opt/android-sdk \ + -e ANDROID_SDK_ROOT=/opt/android-sdk \ + -e ANDROID_NDK_HOME=/opt/android-sdk/ndk/28.2.13676358 \ + -e ONIONWIRE_ANDROID_ABI="$ONIONWIRE_ANDROID_ABI" \ + -e ONIONWIRE_REQUIRE_RELEASE_KEY=false \ + -e RUST_TOOLCHAIN="$RUST_TOOLCHAIN" \ + -e ANDROID_CMDLINE_TOOLS_URL="$ANDROID_CMDLINE_TOOLS_URL" \ + -e GRADLE_OPTS="-Dorg.gradle.daemon=false -Dorg.gradle.jvmargs=-Xmx1024m -XX:MaxMetaspaceSize=384m -Dfile.encoding=UTF-8" \ + -v "$SDK_VOLUME":/opt/android-sdk \ + -v "$CARGO_VOLUME":/cargo \ + -v "$TARGET_VOLUME":/cargo-target \ + -v "$GRADLE_VOLUME":/gradle \ + -w /src \ + "$ANDROID_IMAGE" \ + bash -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src && bash /src/.ci-android-verify.sh' + tar czf - \ + --exclude=./target --exclude=./.git --exclude=./.worktrees \ + --exclude=./android/.gradle --exclude=./android/app/build \ + --exclude=./android/sdk/build --exclude=./dist \ + --exclude=./crates/onionwire-sdk/target \ + . \ + | docker start -a -i "$BUILD_CONTAINER" + mkdir -p dist + docker cp "$BUILD_CONTAINER:/src/dist/." dist/ + end=$(date +%s) + echo "build_wall_clock_seconds=$((end - start))" + echo "wall_clock_seconds=$((end - start))" >> "$GITHUB_OUTPUT" + docker rm -f "$BUILD_CONTAINER" >/dev/null || true + ls -l dist/ + + - name: Verify artifacts + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + abi="$ONIONWIRE_ANDROID_ABI" + ls -l dist/ + apk="$(ls dist/onionwire-*-android-$abi.apk)" + aar="$(ls dist/onionwire-sdk-*.aar)" + [ -s "$apk" ] || { echo "missing or empty $apk" >&2; exit 1; } + [ -s "$aar" ] || { echo "missing or empty $aar" >&2; exit 1; } + echo "apk=$apk bytes=$(wc -c < "$apk")" + echo "aar=$aar bytes=$(wc -c < "$aar")" + ( cd dist && sha256sum -c ./*.sha256 ) + echo "=== android-ci-verify.log (from build container) ===" + cat dist/android-ci-verify.log + echo "=== resources after build ===" + free -h || true + df -h || true diff --git a/README.md b/README.md index 7c86293..81690a6 100644 --- a/README.md +++ b/README.md @@ -345,6 +345,7 @@ FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z Workflows (Forgejo Actions, `.forgejo/workflows/`): - [`.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/android-ci.yml`](.forgejo/workflows/android-ci.yml) — the android side of CI, on the `docker-amd64` runner: builds `:sdk:assembleRelease` + `:app:assembleRelease` with the same script the release uses (`scripts/build-android-local.sh`, Rust for `aarch64-linux-android` via cargo-ndk + UniFFI bindings) and verifies the packaged `libonionwire_sdk.so`, checksums and APK badging. Debug keystore, no publish, no tag. Runs on `main` and PRs when `android/`, `src/`, `crates/`, `Cargo.toml`, `Cargo.lock` or `scripts/build-android-local.sh` change. Same concurrency group **and** the same runner volumes as `android-release.yml`, so a PR build never fights a release build over the SDK/NDK, cargo and Gradle caches. - [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). 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/docs/RELEASING.md b/docs/RELEASING.md index a4ccc3b..fe6b3b6 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -114,6 +114,18 @@ The Android build runs on the **amd64** runner (the Pi is aarch64 and cannot produce an APK), then a second job on the Pi attaches the assets. It is the long pole of a release — the Linux binaries land first. +### Android CI (not a release) + +`android-ci.yml` runs the same gradle targets on the same amd64 runner for every +PR and `main` push that touches `android/`, `src/`, `crates/`, `Cargo.toml`, +`Cargo.lock` or `scripts/build-android-local.sh`, so an android-only PR is no +longer merged on an empty check list. It signs with the **debug** key +(`ONIONWIRE_REQUIRE_RELEASE_KEY=false`, no keystore) and publishes nothing — +`apksigner` in that job reports the debug cert, which is expected there and +never in `android-release`. It shares `android-release.yml`'s concurrency group +and volumes, so the PR build is warm (~9 min) instead of re-downloading a +gigabyte of SDK/NDK. + ## Rebuilding an existing tag - **Both** Linux binaries: dispatch `release` with `tag=vX.Y.Z`. The tag's own From 2141a6e9a5cf2f55306986d132e16b484ebb89fc Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 14 Sep 2026 13:22:53 -0400 Subject: [PATCH 7/8] fix(ci): resolve conflict markers left in scripts/publish-release.sh The file reached main with an unresolved stash conflict at the auth_json helper (line 24) and the asset-upload curl (line 133). Both publish jobs run it directly, so every release/android-release publish dies with "line 24: syntax error near unexpected token <<<". Keep the HTTP Basic auth_json with the CR strip, and the single-line -X POST -u asset upload. --- scripts/publish-release.sh | 9 --------- 1 file changed, 9 deletions(-) diff --git a/scripts/publish-release.sh b/scripts/publish-release.sh index bfbbfa1..b5d075e 100755 --- a/scripts/publish-release.sh +++ b/scripts/publish-release.sh @@ -21,11 +21,7 @@ api_curl() { } auth_json() { -<<<<<<< Updated upstream - api_curl -u "sirius:${FORGEJO_TOKEN}" -H "Content-Type: application/json" "$@" -======= api_curl -u "sirius:${FORGEJO_TOKEN}" -H "Content-Type: application/json" "$@" | sed 's/\r$//' ->>>>>>> Stashed changes } tag="${1:?usage: publish-release.sh ...}" @@ -130,12 +126,7 @@ for a in json.load(sys.stdin): fi done up=$(api_curl -o /tmp/release-asset.json -w '%{http_code}' \ -<<<<<<< Updated upstream - -X POST "$api/releases/$rid/assets?name=$asset" \ - -u "sirius:${FORGEJO_TOKEN}" \ -======= -X POST -u "sirius:${FORGEJO_TOKEN}" "$api/releases/$rid/assets?name=$asset" \ ->>>>>>> Stashed changes -F "attachment=@$f") if [ "$up" != "201" ]; then die_http "upload $asset" "$up" /tmp/release-asset.json From e3a051a9809140d8e6294e33c315a6b368d65352 Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 14 Sep 2026 16:55:47 -0400 Subject: [PATCH 8/8] docs(readme): document v0.2.1 wallet create/import, tip frame, F6 screen, SDK payment surface --- README.md | 114 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 70 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 81690a6..098569c 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 + Android SDK/APK. 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. Unreachable chat peers go to a **local outbox** (device-only retry queue — no relay); file transfer and payment frames still fail closed. Optional Monero invoices if you point at a local `monero-wallet-rpc` (prefer a view-only wallet). 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. +**v0.2.1** — Linux TUI + Android SDK/APK. 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. Unreachable chat peers go to a **local outbox** (device-only retry queue — no relay); file transfer and payment frames still fail closed. Optional Monero payments: `/pay` invoices (receive), `/tip` payments (send), and a full in-app wallet create/import (`F6` wallet screen, `/wallet create`, `/wallet import`). 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. @@ -30,8 +30,8 @@ CI (`.forgejo/workflows/release.yml`) does **not** release on a merge. Releases **x86_64 (most PCs / VMs):** ```bash -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.1.0/onionwire-x86_64-unknown-linux-gnu -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.1.0/onionwire-x86_64-unknown-linux-gnu.sha256 +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.2.1/onionwire-x86_64-unknown-linux-gnu +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.2.1/onionwire-x86_64-unknown-linux-gnu.sha256 sha256sum -c onionwire-x86_64-unknown-linux-gnu.sha256 chmod +x onionwire-x86_64-unknown-linux-gnu ./onionwire-x86_64-unknown-linux-gnu --version @@ -40,8 +40,8 @@ chmod +x onionwire-x86_64-unknown-linux-gnu **aarch64 (Raspberry Pi, ARM servers):** ```bash -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.1.0/onionwire-aarch64-unknown-linux-gnu -curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.1.0/onionwire-aarch64-unknown-linux-gnu.sha256 +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.2.1/onionwire-aarch64-unknown-linux-gnu +curl -fL -O https://forgejo.siriusdevops.com/sirius/onionwire/releases/download/v0.2.1/onionwire-aarch64-unknown-linux-gnu.sha256 sha256sum -c onionwire-aarch64-unknown-linux-gnu.sha256 chmod +x onionwire-aarch64-unknown-linux-gnu ./onionwire-aarch64-unknown-linux-gnu --version @@ -104,7 +104,7 @@ Then `F2` on A (invite string), `F3`-paste on B (and the other way around). No Q ## First run -``` +```bash onionwire ``` @@ -112,7 +112,7 @@ or `cargo run --release`. On start you are prompted for a store passphrase (echo off, like other CLI passwords) or set `ONIONWIRE_STORE_PASSPHRASE`. Empty passphrase is rejected; a wrong passphrase does not open chat. Then you should see `onionwire: bootstrapping Arti…` on stderr. Directory bootstrap is usually under a minute; the onion is ready once a probe connect works (combined Arti status may still say Bootstrapping). Fail closed at 360s. Data lives in `ONIONWIRE_HOME` if set, otherwise `~/.local/share/onionwire/` (`onionwire.db` + Arti state, mode 0700). First open creates an ed25519 identity key. That key **is** you. -Then `F2` to share your invite, `F3` to paste a friend’s. Mouse-select the `onionwire:v1:…` line to copy. Highlight them in the roster, type in the composer, Enter to send. Chat rows show delivery state from the local outbox (`✓` delivered, `◷ queued (try n/8, retry …)`, `» sending`, `✗ failed: …`); the footer shows `{n} queued` while anything is outstanding. If their onion is down the message stays on this device and the retry worker re-dials with backoff — nothing is handed to a third party. File transfer and payments are still one-shot (both sides online). +Then `F2` to share your invite, `F3` to paste a friend's. Mouse-select the `onionwire:v1:…` line to copy. Highlight them in the roster, type in the composer, Enter to send. Chat rows show delivery state from the local outbox (`✓` delivered, `◷ queued (try n/8, retry …)`, `» sending`, `✗ failed: …`); the footer shows `{n} queued` while anything is outstanding. If their onion is down the message stays on this device and the retry worker re-dials with backoff — nothing is handed to a third party. File transfer and payments are still one-shot (both sides online). ## Friends are keys @@ -130,9 +130,10 @@ Focus starts on the composer so typing works immediately. `Tab` cycles panes; `j | `g` / `G` | Jump to top / bottom of the focused pane | | `?` | Keybinding help (`Esc` closes) | | `F2` | Share invite (`onionwire:v1:…`) | -| `F3` | Paste a friend’s invite | +| `F3` | Paste a friend's invite | | `F4` | Rotate **onion** (locator only) | -| `F5` | Selected friend’s profile (`/who`) | +| `F5` | Selected friend's profile (`/who`) | +| `F6` | Wallet screen (receive QR, balance, transfers) | | Enter | Send chat to the selected friend, or run a `/command` | | `Esc` | Close overlay / back to Main / clear composer | | `Ctrl-Q` | Quit: type `CLEAR`+Enter to wipe history, `QUIT`+Enter to leave it, Esc to stay | @@ -160,14 +161,26 @@ Give that string to a friend. They `F3` paste it (`(o) paste invite`). Unknown ` `messages` row and retried in-process while the app runs (exponential backoff, cap 30 min between attempts, stop after 8 attempts or a terminal failure). There is **no** server-side queue and **no** store-and-forward relay — a queued message -never leaves the device, and it dies with the device. Delivery markers in the -TUI and the Android chat UI are the store's own statuses (`Queued` / `Sending` / -`Sent` / `Failed`); see [docs/TUI.md](docs/TUI.md) and the threat-model notes on -seizure and retry traffic analysis in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md). +never leaves the device, and it dies with the device. Two consequences are real and are accepted: + +- **Device seizure.** A pending (never-delivered) message sits in the same SQLCipher store as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure *with* the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from; seizure without it reveals nothing in this store. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase — SSD wear-leveling can keep copies. Roster and identity stay. +- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure. + +Delivery markers in the TUI and Android chat UI are the store's own statuses: + +| Row state | Marker | +|---|---| +| delivered | `you: ping ✓` | +| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` | +| sending | `you: pong » sending` | +| failed | `you: pong ✗ failed: connection timed out` | +| inbound | `them: pong` (no marker) | + +The footer shows `{n} queued` while any row is outstanding. `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` / `retry now` comes from the stored absolute `next_attempt_at`. Failed reasons are sanitized, cut to the tail of the `a: b: c` chain, and capped at 24 cells. Still **fail closed** (no queue, no retry): -- file transfer (`/file`) and payment frames (`rcp` / spend paths) +- file transfer (`/file`) and payment frames (`inv` / `rcp` / `tip`) - fingerprint mismatch vs the pinned key - Arti cannot publish the onion (no C-tor fallback) - no DHT, no name server, no hosted chat server @@ -188,7 +201,7 @@ resume, no images in the TUI. ## Monero (opt-in) Chat does not need a wallet. Spend is opt-in at wallet create/restore; default -is no spend key on the device. Optional JSON-RPC to `monero-wallet-rpc` on +is no spend key, no seed on the device. Optional JSON-RPC to `monero-wallet-rpc` on loopback (you run it, or the app spawns it). Chain source is your choice: a spawned local `monerod`, or a daemon address you supply. The wallet **must** use `--rpc-login`; OnionWire refuses an open RPC (HTTP 200 without a Digest @@ -202,7 +215,7 @@ export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083 export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret ``` -Loopback only, HTTP Digest (RFC 2617, matching `--rpc-login`), 5s timeout, 1 MiB response cap. `.onion` RPC URLs are rejected (no Arti dial; do not point this at a remote wallet). Unset → chat still works; `/pay` and `/tip` say so. Do not log the RPC password. +Loopback only, HTTP Digest (RFC 2617, matching `--rpc-login`), 5s timeout, 1 MiB response cap. `.onion` RPC URLs are rejected (no Arti dial; do not point this at a remote wallet). Unset → chat still works; `/pay`, `/tip`, and `F6` say so. Do not log the RPC password. **Prefer a view-only wallet.** OnionWire only needs invoices and receipt checks (`create_address` / `get_transfers`); it does not need spend authority. Set @@ -210,10 +223,36 @@ Loopback only, HTTP Digest (RFC 2617, matching `--rpc-login`), 5s timeout, 1 MiB locally before any RPC dial — `/pay` and receipt verification keep working. Details: [docs/WALLET.md](docs/WALLET.md). -- `/pay [memo]` — invoice (we want to receive). Uses a wallet subaddress if RPC is up, else the profile `xmr_addr`. -- `/wallet create` — generate a new spend-capable wallet (no key paste; seed shown once). Needs `--wallet-dir` on the RPC. -- `/wallet import` — restore from an existing 25-word seed (the only path that takes a secret). -- `/tip [memo]` — pay the selected friend’s profile address, then send a signed `rcp` (disabled under `ONIONWIRE_WALLET_NO_SPEND`). Incoming receipts stay unverified until RPC `get_transfers` matches. +Payment frame summary: + +| Command | Wire frame | What it does | +|---|---|---| +| `/pay [memo]` | `inv ` | Invoice to receive. We want to be paid. Uses a wallet subaddress if RPC is up, else the profile `xmr_addr`. | +| `/tip [memo]` | `rcp ` + `tip ` | Pay the selected friend. Sends a Monero `transfer`, then a signed receipt claim and a tip frame. Disabled under `ONIONWIRE_WALLET_NO_SPEND`. | + +- `/pay` sends a signed `inv` frame one-shot (both sides must be online). +- `/tip` does the chain transfer first, then sends a signed `rcp` frame **and** a `tip` frame — both one-shot. Peer onion down → fails after the transfer. Not queued. + +## In-app wallet (create / import) + +`/wallet create` (F6 then `c`) generates a new spend-capable wallet on the RPC +(`create_wallet`), then shows the 25-word seed **once** for backup +(`query_key mnemonic`). Type `SPEND` to accept the spend-authority warning, set a +wallet passphrase, write the seed down, type `SEEN`. The seed is never pasted into +the composer or chat history — collect it on the dedicated screen. + +`/wallet import` (F6 then `i`) restores from an existing 25-word seed via +`restore_deterministic_wallet`. This is the only path that takes a user-supplied +secret. The seed is collected on its own screen. + +Both paths require the wallet RPC to be started with `--wallet-dir` (not only +`--wallet-file`); the in-app filename is `onionwire`. + +**Spend-authority warning** — unavoidable at create/restore: + +> An OnionWire instance pointed at a spend-capable `monero-wallet-rpc` is a local spend authority. Any process that can read the RPC credentials (env var, `/proc//environ`, shell history, a stored URL) can spend the wallet's balance, and `/tip` gives a chat peer a supported path to ask for a transfer. Prefer a view-only wallet or a separate low-balance hot wallet for spend. + +The wallet screen (`F6`) shows a receive address (fresh subaddress when the wallet is up, else the profile `xmr_addr`), the current balance, and up to 8 recent transfers. Press `r` (or Enter) to toggle a QR code of the receive address. `Esc` returns to the chat. ## Backup / restore @@ -226,7 +265,7 @@ Treat the backup file like the sqlite db. ## Mixed versions -0.1.2 peers store unknown plaintext as chat. A 0.2 sender of `prf ` / `inv ` / `rcp ` / `fil ` will leave a garbage line on an un-upgraded peer. Upgrade both sides. The Noise handshake is unchanged. +0.1.2 peers store unknown plaintext as chat. A 0.2 sender of `prf ` / `inv ` / `rcp ` / `tip ` / `fil ` will leave a garbage line on an un-upgraded peer. Upgrade both sides. The Noise handshake is unchanged. ## Wipe @@ -252,33 +291,19 @@ If you set `ONIONWIRE_HOME`, delete that directory instead. 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. -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. +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. Unlock is fail-closed: wrong or empty passphrase does not open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` never falls back to empty AAD. -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. Secret material (Noise/Ed25519/X25519 ephemerals, store key copies, TUI passphrase buffer) is zeroized with the `zeroize` crate when dropped; that shrinks the window, it does not close it. It also does not stop an attacker who has your passphrase. Pending outbox rows live in the same encrypted store as delivered chat — seizure *with* the passphrase can reveal messages that never left the device. `/wipe` deletes chat, payments and outbox 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. +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. Secret material (Noise/Ed25519/X25519 ephemerals, store key copies, TUI passphrase buffer) is zeroized with the `zeroize` crate when dropped; that shrinks the window, it does not close it. It also does not stop an attacker who has your passphrase. Pending outbox rows live in the same encrypted store as delivered chat — seizure *with* the passphrase can reveal messages that never left the device. `/wipe` deletes chat, payments and outbox history; it is not a forensic erase — SSD wear-leveling can keep copies. `/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). ## Android (SDK + APK) -Same repository, same protocol, separate product from the Linux TUI. An Android -peer and a Linux peer that exchange invites interoperate — one protocol, not two. +Same repository, same protocol, separate product from the Linux TUI. An Android peer and a Linux peer that exchange invites interoperate — one protocol, not two. -- **SDK** — `onionwire-sdk-.aar`. UniFFI Kotlin bindings over the same - Rust crate the TUI runs on, plus `libonionwire_sdk.so` for `arm64-v8a`. - `Wire.send()` returns `SendState.Sent` | `SendState.Queued`; chat rows carry - `delivery` and `id`; `Wire.outbox(pubkey)` exposes attempt count and next - attempt time so the UI can render `queued (try n/8, retry 45s)` without - inventing a countdown. Explicit Tor lifecycle bindings stop, flush, and report - observable Tor state. Another Android app depends on the AAR directly. See - [`crates/onionwire-sdk/README.md`](crates/onionwire-sdk/README.md). -- **APK** — `onionwire--android-arm64-v8a.apk`. Kotlin + Jetpack - Compose + Material 3 messenger that depends on the SDK and nothing else. - Per-row delivery markers and a chat-level outbox footer match the TUI - vocabulary. A foreground keep-alive service (ongoing notification) keeps the - in-process Arti onion published and the outbox retry worker alive through - Doze while the user wants the node reachable. The store passphrase can be - remembered as an AES-256-GCM blob wrapped by the **Android Keystore** - (StrongBox first, TEE/software fallback, labelled honestly). +- **SDK** — `onionwire-sdk-.aar`. UniFFI Kotlin bindings over the same Rust crate the TUI runs on, plus `libonionwire_sdk.so` for `arm64-v8a`. `Wire.send()` returns `SendState.Sent` | `SendState.Queued`; chat rows carry `delivery` and `id`; `Wire.outbox(pubkey)` exposes attempt count and next attempt time so the UI can render `queued (try n/8, retry 45s)` without inventing a countdown. Explicit Tor lifecycle bindings (`shutdown`/`flush`/`torState`) stop, flush, and report observable Tor state. Another Android app can depend on the AAR directly. + - **Payment surface** — `sendInvoice(pubkey, amountXmr, memo)` for `/pay`-style invoices, `sendTip(pubkey, amountXmr, memo)` for `/tip`-style payments (chain transfer + signed `rcp` + `tip`), `walletBalance()`, `walletReceiveAddress()`, `walletRecentTransfers(cap)`, `createWallet(password)` (returns the 25-word seed once), `importWallet(password, seed)`, and `spendAuthorityWarning()`. All payments are one-shot; none are queued. See [crates/onionwire-sdk/README.md](crates/onionwire-sdk/README.md). +- **APK** — `onionwire--android-arm64-v8a.apk`. Kotlin + Jetpack Compose + Material 3 messenger that depends on `:sdk` and nothing else. Per-row delivery markers and a chat-level outbox footer match the TUI vocabulary. A foreground keep-alive service (ongoing notification) keeps the in-process Arti onion published and the outbox retry worker alive through Doze while the user wants the node reachable. The store passphrase can be remembered as an AES-256-GCM blob wrapped by the **Android Keystore** (StrongBox first, TEE/software fallback, labelled honestly). A Compose wallet route (receive QR, balance, transfers, create/import) and roster bottom actions are wired without dropping wipe-chat. It is not a WebView, and `src/tui.rs` is untouched. The APK build itself is amd64-only — the Pi runner is aarch64 Linux and cannot produce an APK. @@ -295,7 +320,7 @@ body. # one-time: sdkmanager platform 36 / build-tools 36.0.0 / ndk 28.2.13676358, # rustup target add aarch64-linux-android, cargo install cargo-ndk scripts/build-android-local.sh # -> dist/, with .sha256 files -PUBLISH_TAG=v0.1.0 scripts/build-android-local.sh # + upload to that release +PUBLISH_TAG=v0.2.1 scripts/build-android-local.sh # + upload to that release ``` Every asset has a matching `.sha256` so `sha256sum -c` works. CI signs with the @@ -339,7 +364,7 @@ nothing. # (the workflow does not edit Cargo.toml) # offline x86_64 fallback (idempotent — safe to re-run) -FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z +FORGEJO_TOKEN= scripts/build-release-local.sh v0.2.1 ``` Workflows (Forgejo Actions, `.forgejo/workflows/`): @@ -347,6 +372,7 @@ Workflows (Forgejo Actions, `.forgejo/workflows/`): - [`.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/android-ci.yml`](.forgejo/workflows/android-ci.yml) — the android side of CI, on the `docker-amd64` runner: builds `:sdk:assembleRelease` + `:app:assembleRelease` with the same script the release uses (`scripts/build-android-local.sh`, Rust for `aarch64-linux-android` via cargo-ndk + UniFFI bindings) and verifies the packaged `libonionwire_sdk.so`, checksums and APK badging. Debug keystore, no publish, no tag. Runs on `main` and PRs when `android/`, `src/`, `crates/`, `Cargo.toml`, `Cargo.lock` or `scripts/build-android-local.sh` change. Same concurrency group **and** the same runner volumes as `android-release.yml`, so a PR build never fights a release build over the SDK/NDK, cargo and Gradle caches. - [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — manual, batched release (`workflow_dispatch` only: `dry_run`, `bump`, `version`, `tag`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release, fail-closed tag delete on failure. Dispatch [`android-release.yml`](.forgejo/workflows/android-release.yml) with that tag to add the APK + AAR (no automatic trigger fires on this Forgejo; it is `workflow_dispatch` only). 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`. +- [`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml) — amd64-only Android build (dispatch-only on this Forgejo; wakes from an explicit `tag=` input, not a tag push). Scripts: @@ -376,4 +402,4 @@ Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward r ## License -MIT +MIT \ No newline at end of file